JavaScript - NFC Bricklet

This is the description of the JavaScript API bindings for the NFC Bricklet. General information and technical specifications for the NFC Bricklet are summarized in its hardware description.

An installation guide for the JavaScript API bindings is part of their general description.

Examples

The example code below is Public Domain (CC0 1.0).

Scan For Tags (Node.js)

Download (ExampleScanForTags.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var Tinkerforge = require('tinkerforge');

var HOST = 'localhost';
var PORT = 4223;
var UID = 'XYZ'; // Change XYZ to the UID of your NFC Bricklet

var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object

ipcon.connect(HOST, PORT,
    function (error) {
        console.log('Error: ' + error);
    }
); // Connect to brickd
// Don't use device before ipcon is connected

ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function (connectReason) {
        // Enable reader mode
        nfc.setMode(Tinkerforge.BrickletNFC.MODE_READER);
    }
);

// Register reader state changed callback
nfc.on(Tinkerforge.BrickletNFC.CALLBACK_READER_STATE_CHANGED,
    // Callback function for reader state changed callback
    function (state, idle) {
        if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY) {
            nfc.readerGetTagID(
                function (tagType, tagID) {
                    var tagInfo = '';

                    for (var i = 0; i < tagID.length; i++) {
                        tagInfo += '0x' + ('0' + tagID[i].toString(16).toUpperCase()).substr(-2);

                        if (i < tagID.length - 1) {
                            tagInfo += ' ';
                        }
                    }

                    console.log('Found tag of type %d with ID [%s]', tagType, tagInfo);
                },
                function (error) {
                    console.log('Could not get tag ID: ' + error);
                }
            );
        }

        if(idle) {
            nfc.readerRequestTagID();
        }
    }
);

console.log('Press key to exit');
process.stdin.on('data',
    function (data) {
        ipcon.disconnect();
        process.exit(0);
    }
);

Emulate NDEF (Node.js)

Download (ExampleEmulateNDEF.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var Tinkerforge = require('tinkerforge');

var HOST = 'localhost';
var PORT = 4223;
var UID = 'XYZ'; // Change XYZ to the UID of your NFC Bricklet
var NDEF_URI = 'www.tinkerforge.com';

var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object

ipcon.connect(HOST, PORT,
    function (error) {
        console.log('Error: ' + error);
    }
); // Connect to brickd
// Don't use device before ipcon is connected

ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function (connectReason) {
        // Enable cardemu mode
        nfc.setMode(Tinkerforge.BrickletNFC.MODE_CARDEMU);
    }
);

// Register cardemu state changed callback
nfc.on(Tinkerforge.BrickletNFC.CALLBACK_CARDEMU_STATE_CHANGED,
    // Callback function for cardemu state changed callback
    function (state, idle) {
        if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_IDLE) {
            // Only short records are supported
            var ndefRecordURI = [
                0xD1,                // MB/ME/CF/SR=1/IL/TNF
                0x01,                // TYPE LENGTH
                NDEF_URI.length + 1, // Length
                'U'.charCodeAt(0),   // Type
                4                    // Status
            ];

            for(var i = 0; i < NDEF_URI.length; i++) {
                ndefRecordURI.push(NDEF_URI.charCodeAt(i));
            }

            nfc.cardemuWriteNDEF(ndefRecordURI,
                function() {
                    nfc.cardemuStartDiscovery();
                }
            );
        }
        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_DISCOVER_READY) {
            nfc.cardemuStartTransfer(Tinkerforge.BrickletNFC.CARDEMU_TRANSFER_WRITE);
        }
        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_DISCOVER_ERROR) {
            console.log('Discover error');
        }
        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_ERROR) {
            console.log('Transfer NDEF error');
        }
    }
);

console.log('Press key to exit');
process.stdin.on('data',
    function (data) {
        ipcon.disconnect();
        process.exit(0);
    }
);

Simple (Node.js)

Download (ExampleSimple.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var Tinkerforge = require('tinkerforge');

var HOST = 'localhost';
var PORT = 4223;
var UID = 'XYZ'; // Change XYZ to the UID of your NFC Bricklet

var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object
var cycle = 1;

ipcon.connect(HOST, PORT,
    function (error) {
        console.log('Error: ' + error);
    }
); // Connect to brickd
// Don't use device before ipcon is connected

function printTagID(index) {
    nfc.simpleGetTagID(
        index,
        function (tagType, tagID, lastSeen) {
            if (tagID.length == 0) {
                return;
            }

            var tagInfo = '';

            for (var i = 0; i < tagID.length; i++) {
                tagInfo += '0x' + ('0' + tagID[i].toString(16).toUpperCase()).substr(-2);

                if (i < tagID.length - 1) {
                    tagInfo += ' ';
                }
            }

            console.log('  Index: %d, Tag Type: %d, Tag ID: [%s], Last Seen: %f seconds ago', index, tagType, tagInfo, lastSeen / 1000.0);
        },
        function () {
            // On error enable simple mode again
            nfc.setMode(Tinkerforge.BrickletNFC.MODE_SIMPLE);
        }
    );
}

ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function (connectReason) {
        // Enable simple mode
        nfc.setMode(Tinkerforge.BrickletNFC.MODE_SIMPLE);

        // Get current tag IDs every second
        setInterval(function () {
            console.log('\nCycle: %d', cycle++)

            for(var index = 0; index < 8; ++index) {
                printTagID(index);
            }
        }, 1000);
    }
);

console.log('Press key to exit');
process.stdin.on('data',
    function (data) {
        ipcon.disconnect();
        process.exit(0);
    }
);

Write Read Type 2 (Node.js)

Download (ExampleWriteReadType2.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var Tinkerforge = require('tinkerforge');

var HOST = 'localhost';
var PORT = 4223;
var UID = 'XYZ'; // Change XYZ to the UID of your NFC Bricklet

var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object

ipcon.connect(HOST, PORT,
    function (error) {
        console.log('Error: ' + error);
    }
); // Connect to brickd
// Don't use device before ipcon is connected

ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function (connectReason) {
        // Enable reader mode
        nfc.setMode(Tinkerforge.BrickletNFC.MODE_READER);
    }
);

// Register reader state changed callback
nfc.on(Tinkerforge.BrickletNFC.CALLBACK_READER_STATE_CHANGED,
    // Callback function for reader state changed callback
    function (state, idle) {
        if(state == Tinkerforge.BrickletNFC.READER_STATE_IDLE) {
            nfc.readerRequestTagID();
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY) {
            nfc.readerGetTagID(
                function (tagType, tid) {
                    if(tagType != Tinkerforge.BrickletNFC.TAG_TYPE_TYPE2) {
                        console.log('Tag is not type-2');

                        return;
                    }

                    console.log('Found tag of type %d with ID [0x%s 0x%s 0x%s 0x%s]',
                                tagType,
                                tid[0].toString(16),
                                tid[1].toString(16),
                                tid[2].toString(16),
                                tid[3].toString(16));

                    nfc.readerRequestPage(1, 4);
                },
                function (error) {
                    console.log('Error: ' + error);
                }
            );
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_ERROR) {
            console.log('Request tag ID error');
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_PAGE_READY) {
            nfc.readerReadPage(
                function (page) {
                    console.log('Page read: 0x%s 0x%s 0x%s 0x%s',
                                page[0].toString(16),
                                page[1].toString(16),
                                page[2].toString(16),
                                page[3].toString(16));
                    nfc.readerWritePage(1, page);
                },
                function(error) {
                    console.log('Error: ' + error);
                }
            );
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_WRITE_PAGE_READY) {
            console.log('Write page ready');
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_PAGE_ERROR) {
            console.log('Request page error');
        }
        else if(state == Tinkerforge.BrickletNFC.READER_STATE_WRITE_PAGE_ERROR) {
            console.log('Write page error');
        }
    }
);

console.log('Press key to exit');
process.stdin.on('data',
    function (data) {
        ipcon.disconnect();
        process.exit(0);
    }
);

Scan For Tags (HTML)

Download (ExampleScanForTags.html), Test (ExampleScanForTags.html)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <title>Tinkerforge | JavaScript Example</title>
    </head>
    <body>
        <div style="text-align:center;">
            <h1>NFC Bricklet Scan For Tags Example</h1>
            <p>
                <input value="localhost" id="host" type="text" size="20">:
                <input value="4280" id="port" type="text" size="5">,
                <input value="uid" id="uid" type="text" size="5">
                <input value="Start Example" id="start" type="button" onclick="startExample();">
            </p>
            <p>
                <textarea readonly id="text" cols="80" rows="24" style="resize:none;"
                          >Press "Start Example" to begin ...</textarea>
            </p>
        </div>
        <script src="./Tinkerforge.js" type='text/javascript'></script>
        <script type='text/javascript'>
            var ipcon;
            var textArea = document.getElementById("text");
            function startExample() {
                textArea.value = "";
                var HOST = document.getElementById("host").value;
                var PORT = parseInt(document.getElementById("port").value);
                var UID = document.getElementById("uid").value;
                if(ipcon !== undefined) {
                    ipcon.disconnect();
                }
                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object
                ipcon.connect(HOST, PORT,
                    function(error) {
                        textArea.value += 'Error: ' + error + '\n';
                    }
                ); // Connect to brickd
                // Don't use device before ipcon is connected

                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                    function (connectReason) {
                        // Enable reader mode
                        nfc.setMode(Tinkerforge.BrickletNFC.MODE_READER);
                    }
                );

                // Register reader state changed callback
                nfc.on(Tinkerforge.BrickletNFC.CALLBACK_READER_STATE_CHANGED,
                    // Callback function for reader state changed callback
                    function (state, idle) {
                        if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY) {
                            nfc.readerGetTagID(
                                function (tagType, tagID) {
                                    var tagInfo = '';

                                    for (var i = 0; i < tagID.length; i++) {
                                        tagInfo += '0x' + ('0' + tagID[i].toString(16).toUpperCase()).substr(-2);

                                        if (i < tagID.length - 1) {
                                            tagInfo += ' ';
                                        }
                                    }

                                    textArea.value += 'Found tag of type ' + tagType + ' with ID [' + tagInfo + ']\n';
                                    textArea.scrollTop = textArea.scrollHeight;
                                },
                                function (error) {
                                    textArea.value += 'Could not get tag ID: ' + error + '\n';
                                    textArea.scrollTop = textArea.scrollHeight;
                                }
                            );
                        }

                        if(idle) {
                            nfc.readerRequestTagID();
                        }
                    }
                );
            }
        </script>
    </body>
</html>

Emulate NDEF (HTML)

Download (ExampleEmulateNDEF.html), Test (ExampleEmulateNDEF.html)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <title>Tinkerforge | JavaScript Example</title>
    </head>
    <body>
        <div style="text-align:center;">
            <h1>NFC Bricklet Emulate NDEF Example</h1>
            <p>
                <input value="localhost" id="host" type="text" size="20">:
                <input value="4280" id="port" type="text" size="5">,
                <input value="uid" id="uid" type="text" size="5">
                <input value="Start Example" id="start" type="button" onclick="startExample();">
            </p>
            <p>
                <textarea readonly id="text" cols="80" rows="24" style="resize:none;"
                          >Press "Start Example" to begin ...</textarea>
            </p>
        </div>
        <script src="./Tinkerforge.js" type='text/javascript'></script>
        <script type='text/javascript'>
            var ipcon;
            var textArea = document.getElementById("text");
            function startExample() {
                textArea.value = "";
                var HOST = document.getElementById("host").value;
                var PORT = parseInt(document.getElementById("port").value);
                var UID = document.getElementById("uid").value;
                if(ipcon !== undefined) {
                    ipcon.disconnect();
                }
                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object
                ipcon.connect(HOST, PORT,
                    function(error) {
                        textArea.value += 'Error: ' + error + '\n';
                    }
                ); // Connect to brickd
                // Don't use device before ipcon is connected

                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                    function (connectReason) {
                        // Enable cardemu mode
                        nfc.setMode(Tinkerforge.BrickletNFC.MODE_CARDEMU);
                    }
                );

                // Register cardemu state changed callback
                nfc.on(Tinkerforge.BrickletNFC.CALLBACK_CARDEMU_STATE_CHANGED,
                    // Callback function for cardemu state changed callback
                    function (state, idle) {
                        if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_IDLE) {
                            // Only short records are supported
                            var ndefRecordURI = [
                                0xD1,                // MB/ME/CF/SR=1/IL/TNF
                                0x01,                // TYPE LENGTH
                                NDEF_URI.length + 1, // Length
                                'U'.charCodeAt(0),   // Type
                                4                    // Status
                            ];

                            for(var i = 0; i < NDEF_URI.length; i++) {
                                ndefRecordURI.push(NDEF_URI.charCodeAt(i));
                            }

                            nfc.cardemuWriteNDEF(ndefRecordURI,
                                function() {
                                    nfc.cardemuStartDiscovery();
                                }
                            );
                        }
                        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_DISCOVER) {
                            textArea.value += 'Discover\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_DISCOVER_READY) {
                            nfc.cardemuStartTransfer(Tinkerforge.BrickletNFC.CARDEMU_TRANSFER_WRITE);
                            textArea.value += 'Discover ready\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_READY) {
                            textArea.value += 'Transfer NDEF ready\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_DISCOVER_ERROR) {
                            textArea.value += 'Discover error\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_ERROR) {
                            textArea.value += 'Transfer NDEF error\n';
                        }
                    }
                );
            }
        </script>
    </body>
</html>

Simple (HTML)

Download (ExampleSimple.html), Test (ExampleSimple.html)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <title>Tinkerforge | JavaScript Example</title>
    </head>
    <body>
        <div style="text-align:center;">
            <h1>NFC Bricklet Scan For Tags Example</h1>
            <p>
                <input value="localhost" id="host" type="text" size="20">:
                <input value="4280" id="port" type="text" size="5">,
                <input value="uid" id="uid" type="text" size="5">
                <input value="Start Example" id="start" type="button" onclick="startExample();">
            </p>
            <p>
                <textarea readonly id="text" cols="120" rows="24" style="resize:none;"
                          >Press "Start Example" to begin ...</textarea>
            </p>
        </div>
        <script src="./Tinkerforge.js" type='text/javascript'></script>
        <script type='text/javascript'>
            var ipcon;
            var interval;
            var textArea = document.getElementById("text");
            function printTagID(nfc, index) {
                nfc.simpleGetTagID(
                    index,
                    function (tagType, tagID, lastSeen) {
                        if (tagID.length == 0) {
                            return;
                        }

                        var tagInfo = '';

                        for (var i = 0; i < tagID.length; i++) {
                            tagInfo += '0x' + ('0' + tagID[i].toString(16).toUpperCase()).substr(-2);

                            if (i < tagID.length - 1) {
                                tagInfo += ' ';
                            }
                        }

                        textArea.value += '  Index: ' + index + ', Tag Type: ' + tagType + ', Tag ID: [' + tagInfo + '], Last Seen: ' + (lastSeen / 1000.0) + ' seconds ago\n';
                        textArea.scrollTop = textArea.scrollHeight;
                    },
                    function () {
                        // On error enable simple mode again
                        nfc.setMode(Tinkerforge.BrickletNFC.MODE_SIMPLE);
                    }
                );
            }
            function startExample() {
                textArea.value = "";
                var HOST = document.getElementById("host").value;
                var PORT = parseInt(document.getElementById("port").value);
                var UID = document.getElementById("uid").value;
                if(ipcon !== undefined) {
                    ipcon.disconnect();
                }
                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object
                var cycle = 1;
                ipcon.connect(HOST, PORT,
                    function(error) {
                        textArea.value += 'Error: ' + error + '\n';
                    }
                ); // Connect to brickd
                // Don't use device before ipcon is connected

                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                    function (connectReason) {
                        // Enable reader mode
                        nfc.setMode(Tinkerforge.BrickletNFC.MODE_SIMPLE);

                        // Get current tag IDs every second
                        if (interval !== undefined) {
                            clearInterval(interval);
                        }

                        interval = setInterval(function () {
                            textArea.value += '\nCycle: ' + (cycle++) + '\n';
                            textArea.scrollTop = textArea.scrollHeight;

                            for(var index = 0; index < 8; ++index) {
                                printTagID(nfc, index);
                            }
                        }, 1000);
                    }
                );
            }
        </script>
    </body>
</html>

Write Read Type 2 (HTML)

Download (ExampleWriteReadType2.html), Test (ExampleWriteReadType2.html)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <title>Tinkerforge | JavaScript Example</title>
    </head>
    <body>
        <div style="text-align:center;">
            <h1>NFC Bricklet Write Read Type2 Example</h1>
            <p>
                <input value="localhost" id="host" type="text" size="20">:
                <input value="4280" id="port" type="text" size="5">,
                <input value="uid" id="uid" type="text" size="5">
                <input value="Start Example" id="start" type="button" onclick="startExample();">
            </p>
            <p>
                <textarea readonly id="text" cols="80" rows="24" style="resize:none;"
                          >Press "Start Example" to begin ...</textarea>
            </p>
        </div>
        <script src="./Tinkerforge.js" type='text/javascript'></script>
        <script type='text/javascript'>
            var ipcon;
            var textArea = document.getElementById("text");
            function startExample() {
                textArea.value = "";
                var HOST = document.getElementById("host").value;
                var PORT = parseInt(document.getElementById("port").value);
                var UID = document.getElementById("uid").value;
                if(ipcon !== undefined) {
                    ipcon.disconnect();
                }
                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                var nfc = new Tinkerforge.BrickletNFC(UID, ipcon); // Create device object
                ipcon.connect(HOST, PORT,
                    function(error) {
                        textArea.value += 'Error: ' + error + '\n';
                    }
                ); // Connect to brickd
                // Don't use device before ipcon is connected

                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                    function (connectReason) {
                        // Enable reader mode
                        nfc.setMode(Tinkerforge.BrickletNFC.MODE_READER);
                    }
                );

                // Register reader state changed callback
                nfc.on(Tinkerforge.BrickletNFC.CALLBACK_READER_STATE_CHANGED,
                    // Callback function for reader state changed callback
                    function (state, idle) {
                        if(state == Tinkerforge.BrickletNFC.READER_STATE_IDLE) {
                            nfc.readerRequestTagID();
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY) {
                            nfc.readerGetTagID(
                                function (tagType, tid) {
                                    if(tagType != Tinkerforge.BrickletNFC.TAG_TYPE_TYPE2) {
                                        textArea.value += 'Tag is not type-2\n';

                                        return;
                                    }
                                    textArea.value += 'Found tag of type ' + tagType + ' with ID [' +
                                                      '0x' + tid[0].toString(16) + ' ' +
                                                      '0x' + tid[1].toString(16) + ' ' +
                                                      '0x' + tid[2].toString(16) + ' ' +
                                                      '0x' + tid[3].toString(16) + ']\n';

                                    nfc.readerRequestPage(1, 4);
                                },
                                function (error) {
                                    textArea.value += 'Error: ' + error + '\n';
                                }
                            );
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_TAG_ID_ERROR) {
                            textArea.value += 'Request tag ID error\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_PAGE_READY) {
                            nfc.readerReadPage(
                                function (page) {
                                    textArea.value += 'Page read: ' +
                                                      '0x' + page[0].toString(16) + ' ' +
                                                      '0x' + page[1].toString(16) + ' ' +
                                                      '0x' + page[2].toString(16) + ' ' +
                                                      '0x' + page[3].toString(16) + '\n';
                                    nfc.readerWritePage(1, page);
                                },
                                function(error) {
                                    textArea.value += 'Error: ' + error + '\n';
                                }
                            );
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_WRITE_PAGE_READY) {
                            textArea.value += 'Write page ready\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_REQUEST_PAGE_ERROR) {
                            textArea.value += 'Request page error\n';
                        }
                        else if(state == Tinkerforge.BrickletNFC.READER_STATE_WRITE_PAGE_ERROR) {
                            textArea.value += 'Write page error\n';
                        }
                    }
                );
            }
        </script>
    </body>
</html>

API

Generally, every function of the JavaScript bindings can take two optional parameters, returnCallback and errorCallback. These are two user defined callback functions. The returnCallback function is called with the results as arguments, if the function returns its results asynchronously. The errorCallback is called with an error code in case of an error. The error code can be one of the following values:

  • IPConnection.ERROR_ALREADY_CONNECTED = 11
  • IPConnection.ERROR_NOT_CONNECTED = 12
  • IPConnection.ERROR_CONNECT_FAILED = 13
  • IPConnection.ERROR_INVALID_FUNCTION_ID = 21
  • IPConnection.ERROR_TIMEOUT = 31
  • IPConnection.ERROR_INVALID_PARAMETER = 41
  • IPConnection.ERROR_FUNCTION_NOT_SUPPORTED = 42
  • IPConnection.ERROR_UNKNOWN_ERROR = 43
  • IPConnection.ERROR_STREAM_OUT_OF_SYNC = 51
  • IPConnection.ERROR_NON_ASCII_CHAR_IN_SECRET = 71
  • IPConnection.ERROR_WRONG_DEVICE_TYPE = 81
  • IPConnection.ERROR_DEVICE_REPLACED = 82
  • IPConnection.ERROR_WRONG_RESPONSE_LENGTH = 83
  • IPConnection.ERROR_INT64_NOT_SUPPORTED = 91

The namespace for the JavaScript bindings is Tinkerforge.*.

Basic Functions

new BrickletNFC(uid, ipcon)
Parameters:
  • uid – Type: string
  • ipcon – Type: IPConnection
Returns:
  • nfc – Type: BrickletNFC

Creates an object with the unique device ID uid:

var nfc = new BrickletNFC("YOUR_DEVICE_UID", ipcon);

This object can then be used after the IP Connection is connected.

BrickletNFC.setMode(mode[, returnCallback][, errorCallback])
Parameters:
  • mode – Type: int, Range: See constants, Default: 0
Callback Parameters:
  • undefined
Returns:
  • undefined

Sets the mode. The NFC Bricklet supports four modes:

  • Off
  • Card Emulation (Cardemu): Emulates a tag for other readers
  • Peer to Peer (P2P): Exchange data with other readers
  • Reader: Reads and writes tags
  • Simple: Automatically reads tag IDs

If you change a mode, the Bricklet will reconfigure the hardware for this mode. Therefore, you can only use functions corresponding to the current mode. For example, in Reader mode you can only use Reader functions.

The following constants are available for this function:

For mode:

  • BrickletNFC.MODE_OFF = 0
  • BrickletNFC.MODE_CARDEMU = 1
  • BrickletNFC.MODE_P2P = 2
  • BrickletNFC.MODE_READER = 3
  • BrickletNFC.MODE_SIMPLE = 4
BrickletNFC.getMode([returnCallback][, errorCallback])
Callback Parameters:
  • mode – Type: int, Range: See constants, Default: 0
Returns:
  • undefined

Returns the mode as set by setMode().

The following constants are available for this function:

For mode:

  • BrickletNFC.MODE_OFF = 0
  • BrickletNFC.MODE_CARDEMU = 1
  • BrickletNFC.MODE_P2P = 2
  • BrickletNFC.MODE_READER = 3
  • BrickletNFC.MODE_SIMPLE = 4
BrickletNFC.readerRequestTagID([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

After you call readerRequestTagID() the NFC Bricklet will try to read the tag ID from the tag. After this process is done the state will change. You can either register the CALLBACK_READER_STATE_CHANGED callback or you can poll readerGetState() to find out about the state change.

If the state changes to ReaderRequestTagIDError it means that either there was no tag present or that the tag has an incompatible type. If the state changes to ReaderRequestTagIDReady it means that a compatible tag was found and that the tag ID has been saved. You can now read out the tag ID by calling readerGetTagID().

If two tags are in the proximity of the NFC Bricklet, this function will cycle through the tags. To select a specific tag you have to call readerRequestTagID() until the correct tag ID is found.

In case of any ReaderError state the selection is lost and you have to start again by calling readerRequestTagID().

BrickletNFC.readerGetTagID([returnCallback][, errorCallback])
Callback Parameters:
  • tagType – Type: int, Range: See constants
  • tagID – Type: [int, ...], Length: variable, Range: [0 to 255]
Returns:
  • undefined

Returns the tag type and the tag ID. This function can only be called if the NFC Bricklet is currently in one of the ReaderReady states. The returned tag ID is the tag ID that was saved through the last call of readerRequestTagID().

To get the tag ID of a tag the approach is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to ReaderRequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. Call readerGetTagID()

The following constants are available for this function:

For tag_type:

  • BrickletNFC.TAG_TYPE_MIFARE_CLASSIC = 0
  • BrickletNFC.TAG_TYPE_TYPE1 = 1
  • BrickletNFC.TAG_TYPE_TYPE2 = 2
  • BrickletNFC.TAG_TYPE_TYPE3 = 3
  • BrickletNFC.TAG_TYPE_TYPE4 = 4
BrickletNFC.readerGetState([returnCallback][, errorCallback])
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean
Returns:
  • undefined

Returns the current reader state of the NFC Bricklet.

On startup the Bricklet will be in the ReaderInitialization state. The initialization will only take about 20ms. After that it changes to ReaderIdle.

The Bricklet is also reinitialized if the mode is changed, see setMode().

The functions of this Bricklet can be called in the ReaderIdle state and all of the ReaderReady and ReaderError states.

Example: If you call readerRequestPage(), the state will change to ReaderRequestPage until the reading of the page is finished. Then it will change to either ReaderRequestPageReady if it worked or to ReaderRequestPageError if it didn't. If the request worked you can get the page by calling readerReadPage().

The same approach is used analogously for the other API functions.

The following constants are available for this function:

For state:

  • BrickletNFC.READER_STATE_INITIALIZATION = 0
  • BrickletNFC.READER_STATE_IDLE = 128
  • BrickletNFC.READER_STATE_ERROR = 192
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID = 2
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY = 130
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID_ERROR = 194
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 3
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_READY = 131
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_ERROR = 195
  • BrickletNFC.READER_STATE_WRITE_PAGE = 4
  • BrickletNFC.READER_STATE_WRITE_PAGE_READY = 132
  • BrickletNFC.READER_STATE_WRITE_PAGE_ERROR = 196
  • BrickletNFC.READER_STATE_REQUEST_PAGE = 5
  • BrickletNFC.READER_STATE_REQUEST_PAGE_READY = 133
  • BrickletNFC.READER_STATE_REQUEST_PAGE_ERROR = 197
  • BrickletNFC.READER_STATE_WRITE_NDEF = 6
  • BrickletNFC.READER_STATE_WRITE_NDEF_READY = 134
  • BrickletNFC.READER_STATE_WRITE_NDEF_ERROR = 198
  • BrickletNFC.READER_STATE_REQUEST_NDEF = 7
  • BrickletNFC.READER_STATE_REQUEST_NDEF_READY = 135
  • BrickletNFC.READER_STATE_REQUEST_NDEF_ERROR = 199
BrickletNFC.readerWriteNDEF(ndef[, returnCallback][, errorCallback])
Parameters:
  • ndef – Type: [int, ...], Length: variable, Range: [0 to 255]
Callback Parameters:
  • undefined
Returns:
  • undefined

Writes NDEF formated data.

This function currently supports NFC Forum Type 2 and 4.

The general approach for writing a NDEF message is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to ReaderRequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. If looking for a specific tag then call readerGetTagID() and check if the expected tag was found, if it was not found got back to step 1
  4. Call readerWriteNDEF() with the NDEF message that you want to write
  5. Wait for state to change to ReaderWriteNDEFReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
BrickletNFC.readerRequestNDEF([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Reads NDEF formated data from a tag.

This function currently supports NFC Forum Type 1, 2, 3 and 4.

The general approach for reading a NDEF message is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to RequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. If looking for a specific tag then call readerGetTagID() and check if the expected tag was found, if it was not found got back to step 1
  4. Call readerRequestNDEF()
  5. Wait for state to change to ReaderRequestNDEFReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  6. Call readerReadNDEF() to retrieve the NDEF message from the buffer
BrickletNFC.readerReadNDEF([returnCallback][, errorCallback])
Callback Parameters:
  • ndef – Type: [int, ...], Length: variable, Range: [0 to 255]
Returns:
  • undefined

Returns the NDEF data from an internal buffer. To fill the buffer with a NDEF message you have to call readerRequestNDEF() beforehand.

BrickletNFC.readerAuthenticateMifareClassicPage(page, keyNumber, key[, returnCallback][, errorCallback])
Parameters:
  • page – Type: int, Range: [0 to 216 - 1]
  • keyNumber – Type: int, Range: See constants
  • key – Type: [int, ...], Length: 6, Range: [0 to 255]
Callback Parameters:
  • undefined
Returns:
  • undefined

Mifare Classic tags use authentication. If you want to read from or write to a Mifare Classic page you have to authenticate it beforehand. Each page can be authenticated with two keys: A (key_number = 0) and B (key_number = 1). A new Mifare Classic tag that has not yet been written to can be accessed with key A and the default key [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF].

The approach to read or write a Mifare Classic page is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to ReaderRequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. If looking for a specific tag then call readerGetTagID() and check if the expected tag was found, if it was not found got back to step 1
  4. Call readerAuthenticateMifareClassicPage() with page and key for the page
  5. Wait for state to change to ReaderAuthenticatingMifareClassicPageReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  6. Call readerRequestPage() or readerWritePage() to read/write page

The authentication will always work for one whole sector (4 pages).

The following constants are available for this function:

For key_number:

  • BrickletNFC.KEY_A = 0
  • BrickletNFC.KEY_B = 1
BrickletNFC.readerWritePage(page, data[, returnCallback][, errorCallback])
Parameters:
  • page – Type: int, Range: See constants
  • data – Type: [int, ...], Length: variable, Range: [0 to 255]
Callback Parameters:
  • undefined
Returns:
  • undefined

Writes a maximum of 8192 bytes starting from the given page. How many pages are written depends on the tag type. The page sizes are as follows:

  • Mifare Classic page size: 16 byte
  • NFC Forum Type 1 page size: 8 byte
  • NFC Forum Type 2 page size: 4 byte
  • NFC Forum Type 3 page size: 16 byte
  • NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below)

The general approach for writing to a tag is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to ReaderRequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. If looking for a specific tag then call readerGetTagID() and check if the expected tag was found, if it was not found got back to step 1
  4. Call readerWritePage() with page number and data
  5. Wait for state to change to ReaderWritePageReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)

If you use a Mifare Classic tag you have to authenticate a page before you can write to it. See readerAuthenticateMifareClassicPage().

NFC Forum Type 4 tags are not organized into pages but different files. We currently support two files: Capability Container file (CC) and NDEF file.

Choose CC by setting page to 3 or NDEF by setting page to 4.

The following constants are available for this function:

For page:

  • BrickletNFC.READER_WRITE_TYPE4_CAPABILITY_CONTAINER = 3
  • BrickletNFC.READER_WRITE_TYPE4_NDEF = 4
BrickletNFC.readerRequestPage(page, length[, returnCallback][, errorCallback])
Parameters:
  • page – Type: int, Range: See constants
  • length – Type: int, Range: [0 to 213]
Callback Parameters:
  • undefined
Returns:
  • undefined

Reads a maximum of 8192 bytes starting from the given page and stores them into a buffer. The buffer can then be read out with readerReadPage(). How many pages are read depends on the tag type. The page sizes are as follows:

  • Mifare Classic page size: 16 byte
  • NFC Forum Type 1 page size: 8 byte
  • NFC Forum Type 2 page size: 4 byte
  • NFC Forum Type 3 page size: 16 byte
  • NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below)

The general approach for reading a tag is as follows:

  1. Call readerRequestTagID()
  2. Wait for state to change to RequestTagIDReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  3. If looking for a specific tag then call readerGetTagID() and check if the expected tag was found, if it was not found got back to step 1
  4. Call readerRequestPage() with page number
  5. Wait for state to change to ReaderRequestPageReady (see readerGetState() or CALLBACK_READER_STATE_CHANGED callback)
  6. Call readerReadPage() to retrieve the page from the buffer

If you use a Mifare Classic tag you have to authenticate a page before you can read it. See readerAuthenticateMifareClassicPage().

NFC Forum Type 4 tags are not organized into pages but different files. We currently support two files: Capability Container file (CC) and NDEF file.

Choose CC by setting page to 3 or NDEF by setting page to 4.

The following constants are available for this function:

For page:

  • BrickletNFC.READER_REQUEST_TYPE4_CAPABILITY_CONTAINER = 3
  • BrickletNFC.READER_REQUEST_TYPE4_NDEF = 4
BrickletNFC.readerReadPage([returnCallback][, errorCallback])
Callback Parameters:
  • data – Type: [int, ...], Length: variable, Range: [0 to 255]
Returns:
  • undefined

Returns the page data from an internal buffer. To fill the buffer with specific pages you have to call readerRequestPage() beforehand.

BrickletNFC.cardemuGetState([returnCallback][, errorCallback])
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean
Returns:
  • undefined

Returns the current cardemu state of the NFC Bricklet.

On startup the Bricklet will be in the CardemuInitialization state. The initialization will only take about 20ms. After that it changes to CardemuIdle.

The Bricklet is also reinitialized if the mode is changed, see setMode().

The functions of this Bricklet can be called in the CardemuIdle state and all of the CardemuReady and CardemuError states.

Example: If you call cardemuStartDiscovery(), the state will change to CardemuDiscover until the discovery is finished. Then it will change to either CardemuDiscoverReady if it worked or to CardemuDiscoverError if it didn't.

The same approach is used analogously for the other API functions.

The following constants are available for this function:

For state:

  • BrickletNFC.CARDEMU_STATE_INITIALIZATION = 0
  • BrickletNFC.CARDEMU_STATE_IDLE = 128
  • BrickletNFC.CARDEMU_STATE_ERROR = 192
  • BrickletNFC.CARDEMU_STATE_DISCOVER = 2
  • BrickletNFC.CARDEMU_STATE_DISCOVER_READY = 130
  • BrickletNFC.CARDEMU_STATE_DISCOVER_ERROR = 194
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF = 3
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_READY = 131
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_ERROR = 195
BrickletNFC.cardemuStartDiscovery([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Starts the discovery process. If you call this function while a NFC reader device is near to the NFC Bricklet the state will change from CardemuDiscovery to CardemuDiscoveryReady.

If no NFC reader device can be found or if there is an error during discovery the cardemu state will change to CardemuDiscoveryError. In this case you have to restart the discovery process.

If the cardemu state changes to CardemuDiscoveryReady you can start the NDEF message transfer with cardemuWriteNDEF() and cardemuStartTransfer().

BrickletNFC.cardemuWriteNDEF(ndef[, returnCallback][, errorCallback])
Parameters:
  • ndef – Type: [int, ...], Length: variable, Range: [0 to 255]
Callback Parameters:
  • undefined
Returns:
  • undefined

Writes the NDEF message that is to be transferred to the NFC peer.

The maximum supported NDEF message size in Cardemu mode is 255 byte.

You can call this function at any time in Cardemu mode. The internal buffer will not be overwritten until you call this function again or change the mode.

BrickletNFC.cardemuStartTransfer(transfer[, returnCallback][, errorCallback])
Parameters:
  • transfer – Type: int, Range: See constants
Callback Parameters:
  • undefined
Returns:
  • undefined

You can start the transfer of a NDEF message if the cardemu state is CardemuDiscoveryReady.

Before you call this function to start a write transfer, the NDEF message that is to be transferred has to be written via cardemuWriteNDEF() first.

After you call this function the state will change to CardemuTransferNDEF. It will change to CardemuTransferNDEFReady if the transfer was successful or CardemuTransferNDEFError if it wasn't.

The following constants are available for this function:

For transfer:

  • BrickletNFC.CARDEMU_TRANSFER_ABORT = 0
  • BrickletNFC.CARDEMU_TRANSFER_WRITE = 1
BrickletNFC.p2pGetState([returnCallback][, errorCallback])
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean
Returns:
  • undefined

Returns the current P2P state of the NFC Bricklet.

On startup the Bricklet will be in the P2PInitialization state. The initialization will only take about 20ms. After that it changes to P2PIdle.

The Bricklet is also reinitialized if the mode is changed, see setMode().

The functions of this Bricklet can be called in the P2PIdle state and all of the P2PReady and P2PError states.

Example: If you call p2pStartDiscovery(), the state will change to P2PDiscover until the discovery is finished. Then it will change to either P2PDiscoverReady* if it worked or to P2PDiscoverError if it didn't.

The same approach is used analogously for the other API functions.

The following constants are available for this function:

For state:

  • BrickletNFC.P2P_STATE_INITIALIZATION = 0
  • BrickletNFC.P2P_STATE_IDLE = 128
  • BrickletNFC.P2P_STATE_ERROR = 192
  • BrickletNFC.P2P_STATE_DISCOVER = 2
  • BrickletNFC.P2P_STATE_DISCOVER_READY = 130
  • BrickletNFC.P2P_STATE_DISCOVER_ERROR = 194
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF = 3
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF_READY = 131
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF_ERROR = 195
BrickletNFC.p2pStartDiscovery([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Starts the discovery process. If you call this function while another NFC P2P enabled device is near to the NFC Bricklet the state will change from P2PDiscovery to P2PDiscoveryReady.

If no NFC P2P enabled device can be found or if there is an error during discovery the P2P state will change to P2PDiscoveryError. In this case you have to restart the discovery process.

If the P2P state changes to P2PDiscoveryReady you can start the NDEF message transfer with p2pStartTransfer().

BrickletNFC.p2pWriteNDEF(ndef[, returnCallback][, errorCallback])
Parameters:
  • ndef – Type: [int, ...], Length: variable, Range: [0 to 255]
Callback Parameters:
  • undefined
Returns:
  • undefined

Writes the NDEF message that is to be transferred to the NFC peer.

The maximum supported NDEF message size for P2P transfer is 255 byte.

You can call this function at any time in P2P mode. The internal buffer will not be overwritten until you call this function again, change the mode or use P2P to read an NDEF messages.

BrickletNFC.p2pStartTransfer(transfer[, returnCallback][, errorCallback])
Parameters:
  • transfer – Type: int, Range: See constants
Callback Parameters:
  • undefined
Returns:
  • undefined

You can start the transfer of a NDEF message if the P2P state is P2PDiscoveryReady.

Before you call this function to start a write transfer, the NDEF message that is to be transferred has to be written via p2pWriteNDEF() first.

After you call this function the P2P state will change to P2PTransferNDEF. It will change to P2PTransferNDEFReady if the transfer was successfull or P2PTransferNDEFError if it wasn't.

If you started a write transfer you are now done. If you started a read transfer you can now use p2pReadNDEF() to read the NDEF message that was written by the NFC peer.

The following constants are available for this function:

For transfer:

  • BrickletNFC.P2P_TRANSFER_ABORT = 0
  • BrickletNFC.P2P_TRANSFER_WRITE = 1
  • BrickletNFC.P2P_TRANSFER_READ = 2
BrickletNFC.p2pReadNDEF([returnCallback][, errorCallback])
Callback Parameters:
  • ndef – Type: [int, ...], Length: variable, Range: [0 to 255]
Returns:
  • undefined

Returns the NDEF message that was written by a NFC peer in NFC P2P mode.

The NDEF message is ready if you called p2pStartTransfer() with a read transfer and the P2P state changed to P2PTransferNDEFReady.

BrickletNFC.simpleGetTagID(index[, returnCallback][, errorCallback])
Parameters:
  • index – Type: int, Range: [0 to 255]
Callback Parameters:
  • tagType – Type: int, Range: See constants
  • tagID – Type: [int, ...], Length: variable, Range: [0 to 255]
  • lastSeen – Type: int, Range: [0 to 232 - 1]
Returns:
  • undefined

The following constants are available for this function:

For tag_type:

  • BrickletNFC.TAG_TYPE_MIFARE_CLASSIC = 0
  • BrickletNFC.TAG_TYPE_TYPE1 = 1
  • BrickletNFC.TAG_TYPE_TYPE2 = 2
  • BrickletNFC.TAG_TYPE_TYPE3 = 3
  • BrickletNFC.TAG_TYPE_TYPE4 = 4

New in version 2.0.6 (Plugin).

Advanced Functions

BrickletNFC.setDetectionLEDConfig(config[, returnCallback][, errorCallback])
Parameters:
  • config – Type: int, Range: See constants, Default: 3
Callback Parameters:
  • undefined
Returns:
  • undefined

Sets the detection LED configuration. By default the LED shows if a card/reader is detected.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is off.

The following constants are available for this function:

For config:

  • BrickletNFC.DETECTION_LED_CONFIG_OFF = 0
  • BrickletNFC.DETECTION_LED_CONFIG_ON = 1
  • BrickletNFC.DETECTION_LED_CONFIG_SHOW_HEARTBEAT = 2
  • BrickletNFC.DETECTION_LED_CONFIG_SHOW_DETECTION = 3
BrickletNFC.getDetectionLEDConfig([returnCallback][, errorCallback])
Callback Parameters:
  • config – Type: int, Range: See constants, Default: 3
Returns:
  • undefined

Returns the configuration as set by setDetectionLEDConfig()

The following constants are available for this function:

For config:

  • BrickletNFC.DETECTION_LED_CONFIG_OFF = 0
  • BrickletNFC.DETECTION_LED_CONFIG_ON = 1
  • BrickletNFC.DETECTION_LED_CONFIG_SHOW_HEARTBEAT = 2
  • BrickletNFC.DETECTION_LED_CONFIG_SHOW_DETECTION = 3
BrickletNFC.setMaximumTimeout(timeout[, returnCallback][, errorCallback])
Parameters:
  • timeout – Type: int, Unit: 1 ms, Range: [0 to 216 - 1], Default: 2000
Callback Parameters:
  • undefined
Returns:
  • undefined

Sets the maximum timeout.

This is a global maximum used for all internal state timeouts. The timeouts depend heavily on the used tags etc. For example: If you use a Type 2 tag and you want to detect if it is present, you have to use readerRequestTagID() and wait for the state to change to either the error state or the ready state.

With the default configuration this takes 2-3 seconds. By setting the maximum timeout to 100ms you can reduce this time to ~150-200ms. For Type 2 this would also still work with a 20ms timeout (a Type 2 tag answers usually within 10ms). A type 4 tag can take up to 500ms in our tests.

If you need a fast response time to discover if a tag is present or not you can find a good timeout value by trial and error for your specific tag.

By default we use a very conservative timeout, to be sure that any tag can always answer in time.

New in version 2.0.1 (Plugin).

BrickletNFC.getMaximumTimeout([returnCallback][, errorCallback])
Callback Parameters:
  • timeout – Type: int, Unit: 1 ms, Range: [0 to 216 - 1], Default: 2000
Returns:
  • undefined

Returns the timeout as set by setMaximumTimeout()

New in version 2.0.1 (Plugin).

BrickletNFC.getSPITFPErrorCount([returnCallback][, errorCallback])
Callback Parameters:
  • errorCountAckChecksum – Type: int, Range: [0 to 232 - 1]
  • errorCountMessageChecksum – Type: int, Range: [0 to 232 - 1]
  • errorCountFrame – Type: int, Range: [0 to 232 - 1]
  • errorCountOverflow – Type: int, Range: [0 to 232 - 1]
Returns:
  • undefined

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

  • ACK checksum errors,
  • message checksum errors,
  • framing errors and
  • overflow errors.

The errors counts are for errors that occur on the Bricklet side. All Bricks have a similar function that returns the errors on the Brick side.

BrickletNFC.setStatusLEDConfig(config[, returnCallback][, errorCallback])
Parameters:
  • config – Type: int, Range: See constants, Default: 3
Callback Parameters:
  • undefined
Returns:
  • undefined

Sets the status LED configuration. By default the LED shows communication traffic between Brick and Bricklet, it flickers once for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.

The following constants are available for this function:

For config:

  • BrickletNFC.STATUS_LED_CONFIG_OFF = 0
  • BrickletNFC.STATUS_LED_CONFIG_ON = 1
  • BrickletNFC.STATUS_LED_CONFIG_SHOW_HEARTBEAT = 2
  • BrickletNFC.STATUS_LED_CONFIG_SHOW_STATUS = 3
BrickletNFC.getStatusLEDConfig([returnCallback][, errorCallback])
Callback Parameters:
  • config – Type: int, Range: See constants, Default: 3
Returns:
  • undefined

Returns the configuration as set by setStatusLEDConfig()

The following constants are available for this function:

For config:

  • BrickletNFC.STATUS_LED_CONFIG_OFF = 0
  • BrickletNFC.STATUS_LED_CONFIG_ON = 1
  • BrickletNFC.STATUS_LED_CONFIG_SHOW_HEARTBEAT = 2
  • BrickletNFC.STATUS_LED_CONFIG_SHOW_STATUS = 3
BrickletNFC.getChipTemperature([returnCallback][, errorCallback])
Callback Parameters:
  • temperature – Type: int, Unit: 1 °C, Range: [-215 to 215 - 1]
Returns:
  • undefined

Returns the temperature as measured inside the microcontroller. The value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad accuracy. Practically it is only useful as an indicator for temperature changes.

BrickletNFC.reset([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Calling this function will reset the Bricklet. All configurations will be lost.

After a reset you have to create new device objects, calling functions on the existing ones will result in undefined behavior!

BrickletNFC.getIdentity([returnCallback][, errorCallback])
Callback Parameters:
  • uid – Type: string, Length: up to 8
  • connectedUid – Type: string, Length: up to 8
  • position – Type: char, Range: ['a' to 'h', 'z']
  • hardwareVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • firmwareVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • deviceIdentifier – Type: int, Range: [0 to 216 - 1]
Returns:
  • undefined

Returns the UID, the UID where the Bricklet is connected to, the position, the hardware and firmware version as well as the device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port). A Bricklet connected to an Isolator Bricklet is always at position 'z'.

The device identifier numbers can be found here. There is also a constant for the device identifier of this Bricklet.

Callback Configuration Functions

BrickletNFC.on(callback_id, function[, errorCallback])
Parameters:
  • callback_id – Type: int
  • function – Type: function
Returns:
  • undefined

Registers the given function with the given callback_id.

The available callback IDs with corresponding function signatures are listed below.

Callbacks

Callbacks can be registered to receive time critical or recurring data from the device. The registration is done with the on() function of the device object. The first parameter is the callback ID and the second parameter the callback function:

nfc.on(BrickletNFC.CALLBACK_EXAMPLE,
    function (param) {
        console.log(param);
    }
);

The available constants with inherent number and type of parameters are described below.

Note

Using callbacks for recurring events is always preferred compared to using getters. It will use less USB bandwidth and the latency will be a lot better, since there is no round trip time.

BrickletNFC.CALLBACK_READER_STATE_CHANGED
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean

This callback is called if the reader state of the NFC Bricklet changes. See readerGetState() for more information about the possible states.

The following constants are available for this function:

For state:

  • BrickletNFC.READER_STATE_INITIALIZATION = 0
  • BrickletNFC.READER_STATE_IDLE = 128
  • BrickletNFC.READER_STATE_ERROR = 192
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID = 2
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID_READY = 130
  • BrickletNFC.READER_STATE_REQUEST_TAG_ID_ERROR = 194
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 3
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_READY = 131
  • BrickletNFC.READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_ERROR = 195
  • BrickletNFC.READER_STATE_WRITE_PAGE = 4
  • BrickletNFC.READER_STATE_WRITE_PAGE_READY = 132
  • BrickletNFC.READER_STATE_WRITE_PAGE_ERROR = 196
  • BrickletNFC.READER_STATE_REQUEST_PAGE = 5
  • BrickletNFC.READER_STATE_REQUEST_PAGE_READY = 133
  • BrickletNFC.READER_STATE_REQUEST_PAGE_ERROR = 197
  • BrickletNFC.READER_STATE_WRITE_NDEF = 6
  • BrickletNFC.READER_STATE_WRITE_NDEF_READY = 134
  • BrickletNFC.READER_STATE_WRITE_NDEF_ERROR = 198
  • BrickletNFC.READER_STATE_REQUEST_NDEF = 7
  • BrickletNFC.READER_STATE_REQUEST_NDEF_READY = 135
  • BrickletNFC.READER_STATE_REQUEST_NDEF_ERROR = 199
BrickletNFC.CALLBACK_CARDEMU_STATE_CHANGED
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean

This callback is called if the cardemu state of the NFC Bricklet changes. See cardemuGetState() for more information about the possible states.

The following constants are available for this function:

For state:

  • BrickletNFC.CARDEMU_STATE_INITIALIZATION = 0
  • BrickletNFC.CARDEMU_STATE_IDLE = 128
  • BrickletNFC.CARDEMU_STATE_ERROR = 192
  • BrickletNFC.CARDEMU_STATE_DISCOVER = 2
  • BrickletNFC.CARDEMU_STATE_DISCOVER_READY = 130
  • BrickletNFC.CARDEMU_STATE_DISCOVER_ERROR = 194
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF = 3
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_READY = 131
  • BrickletNFC.CARDEMU_STATE_TRANSFER_NDEF_ERROR = 195
BrickletNFC.CALLBACK_P2P_STATE_CHANGED
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: boolean

This callback is called if the P2P state of the NFC Bricklet changes. See p2pGetState() for more information about the possible states.

The following constants are available for this function:

For state:

  • BrickletNFC.P2P_STATE_INITIALIZATION = 0
  • BrickletNFC.P2P_STATE_IDLE = 128
  • BrickletNFC.P2P_STATE_ERROR = 192
  • BrickletNFC.P2P_STATE_DISCOVER = 2
  • BrickletNFC.P2P_STATE_DISCOVER_READY = 130
  • BrickletNFC.P2P_STATE_DISCOVER_ERROR = 194
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF = 3
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF_READY = 131
  • BrickletNFC.P2P_STATE_TRANSFER_NDEF_ERROR = 195

Virtual Functions

Virtual functions don't communicate with the device itself, but operate only on the API bindings device object. They can be called without the corresponding IP Connection object being connected.

BrickletNFC.getAPIVersion()
Returns:
  • apiVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]

Returns the version of the API definition implemented by this API bindings. This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.

BrickletNFC.getResponseExpected(functionId[, errorCallback])
Parameters:
  • functionId – Type: int, Range: See constants
Returns:
  • responseExpected – Type: boolean

Returns the response expected flag for the function specified by the function ID parameter. It is true if the function is expected to send a response, false otherwise.

For getter functions this is enabled by default and cannot be disabled, because those functions will always send a response. For callback configuration functions it is enabled by default too, but can be disabled by setResponseExpected(). For setter functions it is disabled by default and can be enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletNFC.FUNCTION_SET_MODE = 1
  • BrickletNFC.FUNCTION_READER_REQUEST_TAG_ID = 3
  • BrickletNFC.FUNCTION_READER_WRITE_NDEF = 6
  • BrickletNFC.FUNCTION_READER_REQUEST_NDEF = 7
  • BrickletNFC.FUNCTION_READER_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 9
  • BrickletNFC.FUNCTION_READER_WRITE_PAGE = 10
  • BrickletNFC.FUNCTION_READER_REQUEST_PAGE = 11
  • BrickletNFC.FUNCTION_CARDEMU_START_DISCOVERY = 15
  • BrickletNFC.FUNCTION_CARDEMU_WRITE_NDEF = 16
  • BrickletNFC.FUNCTION_CARDEMU_START_TRANSFER = 17
  • BrickletNFC.FUNCTION_P2P_START_DISCOVERY = 20
  • BrickletNFC.FUNCTION_P2P_WRITE_NDEF = 21
  • BrickletNFC.FUNCTION_P2P_START_TRANSFER = 22
  • BrickletNFC.FUNCTION_SET_DETECTION_LED_CONFIG = 25
  • BrickletNFC.FUNCTION_SET_MAXIMUM_TIMEOUT = 27
  • BrickletNFC.FUNCTION_SET_WRITE_FIRMWARE_POINTER = 237
  • BrickletNFC.FUNCTION_SET_STATUS_LED_CONFIG = 239
  • BrickletNFC.FUNCTION_RESET = 243
  • BrickletNFC.FUNCTION_WRITE_UID = 248
BrickletNFC.setResponseExpected(functionId, responseExpected[, errorCallback])
Parameters:
  • functionId – Type: int, Range: See constants
  • responseExpected – Type: boolean
Returns:
  • undefined

Changes the response expected flag of the function specified by the function ID parameter. This flag can only be changed for setter (default value: false) and callback configuration functions (default value: true). For getter functions it is always enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletNFC.FUNCTION_SET_MODE = 1
  • BrickletNFC.FUNCTION_READER_REQUEST_TAG_ID = 3
  • BrickletNFC.FUNCTION_READER_WRITE_NDEF = 6
  • BrickletNFC.FUNCTION_READER_REQUEST_NDEF = 7
  • BrickletNFC.FUNCTION_READER_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 9
  • BrickletNFC.FUNCTION_READER_WRITE_PAGE = 10
  • BrickletNFC.FUNCTION_READER_REQUEST_PAGE = 11
  • BrickletNFC.FUNCTION_CARDEMU_START_DISCOVERY = 15
  • BrickletNFC.FUNCTION_CARDEMU_WRITE_NDEF = 16
  • BrickletNFC.FUNCTION_CARDEMU_START_TRANSFER = 17
  • BrickletNFC.FUNCTION_P2P_START_DISCOVERY = 20
  • BrickletNFC.FUNCTION_P2P_WRITE_NDEF = 21
  • BrickletNFC.FUNCTION_P2P_START_TRANSFER = 22
  • BrickletNFC.FUNCTION_SET_DETECTION_LED_CONFIG = 25
  • BrickletNFC.FUNCTION_SET_MAXIMUM_TIMEOUT = 27
  • BrickletNFC.FUNCTION_SET_WRITE_FIRMWARE_POINTER = 237
  • BrickletNFC.FUNCTION_SET_STATUS_LED_CONFIG = 239
  • BrickletNFC.FUNCTION_RESET = 243
  • BrickletNFC.FUNCTION_WRITE_UID = 248
BrickletNFC.setResponseExpectedAll(responseExpected)
Parameters:
  • responseExpected – Type: boolean
Returns:
  • undefined

Changes the response expected flag for all setter and callback configuration functions of this device at once.

Internal Functions

Internal functions are used for maintenance tasks such as flashing a new firmware of changing the UID of a Bricklet. These task should be performed using Brick Viewer instead of using the internal functions directly.

BrickletNFC.setBootloaderMode(mode[, returnCallback][, errorCallback])
Parameters:
  • mode – Type: int, Range: See constants
Callback Parameters:
  • status – Type: int, Range: See constants
Returns:
  • undefined

Sets the bootloader mode and returns the status after the requested mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change from bootloader mode to firmware mode will only take place if the entry function, device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

The following constants are available for this function:

For mode:

  • BrickletNFC.BOOTLOADER_MODE_BOOTLOADER = 0
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE = 1
  • BrickletNFC.BOOTLOADER_MODE_BOOTLOADER_WAIT_FOR_REBOOT = 2
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_REBOOT = 3
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_ERASE_AND_REBOOT = 4

For status:

  • BrickletNFC.BOOTLOADER_STATUS_OK = 0
  • BrickletNFC.BOOTLOADER_STATUS_INVALID_MODE = 1
  • BrickletNFC.BOOTLOADER_STATUS_NO_CHANGE = 2
  • BrickletNFC.BOOTLOADER_STATUS_ENTRY_FUNCTION_NOT_PRESENT = 3
  • BrickletNFC.BOOTLOADER_STATUS_DEVICE_IDENTIFIER_INCORRECT = 4
  • BrickletNFC.BOOTLOADER_STATUS_CRC_MISMATCH = 5
BrickletNFC.getBootloaderMode([returnCallback][, errorCallback])
Callback Parameters:
  • mode – Type: int, Range: See constants
Returns:
  • undefined

Returns the current bootloader mode, see setBootloaderMode().

The following constants are available for this function:

For mode:

  • BrickletNFC.BOOTLOADER_MODE_BOOTLOADER = 0
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE = 1
  • BrickletNFC.BOOTLOADER_MODE_BOOTLOADER_WAIT_FOR_REBOOT = 2
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_REBOOT = 3
  • BrickletNFC.BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_ERASE_AND_REBOOT = 4
BrickletNFC.setWriteFirmwarePointer(pointer[, returnCallback][, errorCallback])
Parameters:
  • pointer – Type: int, Unit: 1 B, Range: [0 to 232 - 1]
Callback Parameters:
  • undefined
Returns:
  • undefined

Sets the firmware pointer for writeFirmware(). The pointer has to be increased by chunks of size 64. The data is written to flash every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

BrickletNFC.writeFirmware(data[, returnCallback][, errorCallback])
Parameters:
  • data – Type: [int, ...], Length: 64, Range: [0 to 255]
Callback Parameters:
  • status – Type: int, Range: [0 to 255]
Returns:
  • undefined

Writes 64 Bytes of firmware at the position as written by setWriteFirmwarePointer() before. The firmware is written to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

BrickletNFC.writeUID(uid[, returnCallback][, errorCallback])
Parameters:
  • uid – Type: int, Range: [0 to 232 - 1]
Callback Parameters:
  • undefined
Returns:
  • undefined

Writes a new UID into flash. If you want to set a new UID you have to decode the Base58 encoded UID string into an integer first.

We recommend that you use Brick Viewer to change the UID.

BrickletNFC.readUID([returnCallback][, errorCallback])
Callback Parameters:
  • uid – Type: int, Range: [0 to 232 - 1]
Returns:
  • undefined

Returns the current UID as an integer. Encode as Base58 to get the usual string version.

Constants

BrickletNFC.DEVICE_IDENTIFIER

This constant is used to identify a NFC Bricklet.

The getIdentity() function and the IPConnection.CALLBACK_ENUMERATE callback of the IP Connection have a device_identifier parameter to specify the Brick's or Bricklet's type.

BrickletNFC.DEVICE_DISPLAY_NAME

This constant represents the human readable name of a NFC Bricklet.