Python - NFC/RFID Bricklet

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

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

Examples

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

Scan For Tags

Download (example_scan_for_tags.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your NFC/RFID Bricklet
 7
 8from tinkerforge.ip_connection import IPConnection
 9from tinkerforge.bricklet_nfc_rfid import BrickletNFCRFID
10
11tag_type = 0
12
13# Callback function for state changed callback
14def cb_state_changed(state, idle, nr):
15    if state == nr.STATE_REQUEST_TAG_ID_READY:
16        ret = nr.get_tag_id()
17        print("Found tag of type " + str(ret.tag_type) + " with ID [" +
18              " ".join(map(str, map(hex, ret.tid[:ret.tid_length]))) + "]")
19
20    # Cycle through all types
21    if idle:
22        global tag_type
23        tag_type = (tag_type + 1) % 3
24        nr.request_tag_id(tag_type)
25
26if __name__ == "__main__":
27    ipcon = IPConnection() # Create IP connection
28    nr = BrickletNFCRFID(UID, ipcon) # Create device object
29
30    ipcon.connect(HOST, PORT) # Connect to brickd
31    # Don't use device before ipcon is connected
32
33    # Register state changed callback to function cb_state_changed
34    nr.register_callback(nr.CALLBACK_STATE_CHANGED,
35                         lambda x, y: cb_state_changed(x, y, nr))
36
37    # Start scan loop
38    nr.request_tag_id(nr.TAG_TYPE_MIFARE_CLASSIC)
39
40    input("Press key to exit\n") # Use raw_input() in Python 2
41    ipcon.disconnect()

Write Read Type2

Download (example_write_read_type2.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your NFC/RFID Bricklet
 7
 8from tinkerforge.ip_connection import IPConnection
 9from tinkerforge.bricklet_nfc_rfid import BrickletNFCRFID
10
11# Callback function for state changed callback
12def cb_state_changed(state, idle, nr):
13    if state == nr.STATE_REQUEST_TAG_ID_READY:
14        print("Tag found")
15
16        # Write 16 byte to pages 5-8
17        data_write = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
18        nr.write_page(5, data_write)
19        print("Writing data...")
20    elif state == nr.STATE_WRITE_PAGE_READY:
21        # Request pages 5-8
22        nr.request_page(5)
23        print("Requesting data...")
24    elif state == nr.STATE_REQUEST_PAGE_READY:
25        # Get and print pages
26        data = nr.get_page()
27        print("Read data: [" + " ".join(map(str, data)) + "]")
28    elif state & (1 << 6):
29        # All errors have bit 6 set
30        print("Error: " + str(state))
31
32if __name__ == "__main__":
33    ipcon = IPConnection() # Create IP connection
34    nr = BrickletNFCRFID(UID, ipcon) # Create device object
35
36    ipcon.connect(HOST, PORT) # Connect to brickd
37    # Don't use device before ipcon is connected
38
39    # Register state changed callback to function cb_state_changed
40    nr.register_callback(nr.CALLBACK_STATE_CHANGED,
41                         lambda x, y: cb_state_changed(x, y, nr))
42
43    # Select NFC Forum Type 2 tag
44    nr.request_tag_id(nr.TAG_TYPE_TYPE2)
45
46    input("Press key to exit\n") # Use raw_input() in Python 2
47    ipcon.disconnect()

Write Ndef Message

Download (example_write_ndef_message.py)

  1#!/usr/bin/env python
  2# -*- coding: utf-8 -*-
  3
  4# The following specifications have been used
  5# as a basis for writing this example.
  6#
  7# NFC Data Exchange Format (NDEF), NDEF 1.0:
  8# https://github.com/Tinkerforge/nfc-rfid-bricklet/raw/master/datasheets/specification_ndef.pdf
  9#
 10# Type 1 Tag Operation Specification, T1TOP 1.1:
 11# https://github.com/Tinkerforge/nfc-rfid-bricklet/raw/master/datasheets/specification_type1.pdf
 12#
 13# Type 2 Tag Operation Specification, T2TOP 1.1:
 14# https://github.com/Tinkerforge/nfc-rfid-bricklet/raw/master/datasheets/specification_type2.pdf
 15
 16from tinkerforge.ip_connection import IPConnection
 17from tinkerforge.bricklet_nfc_rfid import BrickletNFCRFID
 18
 19try:
 20    from queue import Queue
 21except ImportError:
 22    from Queue import Queue
 23
 24from pprint import pprint
 25import os
 26
 27class NdefMessage:
 28    tag_type = None
 29    records = []
 30    capability_container = [0, 0, 0, 0]
 31
 32    def __init__(self, tag_type):
 33        self.tag_type = tag_type
 34
 35    def add_record(self, record):
 36        self.records.append(record)
 37
 38        # Set end and begin flags as needed
 39        if len(self.records) == 1:
 40            record.begin = True
 41            record.end = True
 42        else:
 43            self.records[-2].end = False
 44            self.records[-1].end = True
 45
 46    def set_capability_container(self, version, tag_size, read_write_access):
 47        # Magic number to indicate NFC Forum defined data is stored
 48        self.capability_container[0] = 0xE1
 49        self.capability_container[1] = version
 50
 51        if self.tag_type == BrickletNFCRFID.TAG_TYPE_TYPE1:
 52            self.capability_container[2] = tag_size/8 - 1
 53        else:
 54            self.capability_container[2] = tag_size/8
 55
 56        self.capability_container[3] = read_write_access
 57
 58    def get_raw_data_in_chunks(self):
 59        raw_data = []
 60
 61        for record in self.records:
 62            raw_data.extend(record.get_raw_data())
 63
 64        # Use three consecutive byte format if necessary, see 2.3 TLV blocks
 65        data_len = len(raw_data)
 66
 67        if data_len < 0xFF:
 68            tlv_ndef = [0x03, data_len]
 69        else:
 70            tlv_ndef = [0x03, 0xFF, data_len >> 8, data_len % 256]
 71
 72        if self.tag_type == BrickletNFCRFID.TAG_TYPE_TYPE1:
 73            # CC set by set_capability_container
 74            # default lock and memory TLVs
 75            # NDEF TLV
 76            # NDEF message
 77            # Terminator TLV
 78            raw_data = self.capability_container + \
 79                       [0x01, 0x03, 0xF2, 0x30, 0x33, 0x02, 0x03, 0xF0, 0x02, 0x03] + \
 80                       tlv_ndef + \
 81                       raw_data + \
 82                       [0xFE]
 83        elif self.tag_type == BrickletNFCRFID.TAG_TYPE_TYPE2:
 84            # CC set by set_capability_container
 85            # NDEF TLV
 86            # NDEF message
 87            # Terminator TLV
 88            raw_data = self.capability_container + \
 89                       tlv_ndef + \
 90                       raw_data + \
 91                       [0xFE]
 92        else:
 93            # TODO: We could support TAG_TYPE_MIFARE_CLASSIC here, but Mifare
 94            # Classic it is not supported in modern smart phones anyway.
 95            return [[]]
 96
 97        chunks = []
 98
 99        for i in range(0, len(raw_data), 16):
100            chunks.append(raw_data[i:i+16])
101
102        last_chunk_length = len(chunks[-1])
103
104        if last_chunk_length < 16:
105            chunks[-1].extend([0]*(16-last_chunk_length))
106
107        return chunks
108
109class NdefRecord:
110    FLAG_ID_LENGTH     = 1 << 3
111    FLAG_SHORT_RECORD  = 1 << 4
112    FLAG_CHUNK         = 1 << 5
113    FLAG_MESSAGE_END   = 1 << 6
114    FLAG_MESSAGE_BEGIN = 1 << 7
115
116    TNF_EMPTY          = 0x0
117    TNF_WELL_KNOWN     = 0x01
118    TNF_MIME_MEDIA     = 0x02
119    TNF_ABSOLUTE_URI   = 0x03
120    TNF_EXTERNAL_TYPE  = 0x04
121    TNF_UNKNOWN        = 0x05
122    TNF_UNCHANGED      = 0x06
123    TNF_RESERVED       = 0x07
124
125    NDEF_URIPREFIX_NONE         = 0x00
126    NDEF_URIPREFIX_HTTP_WWWDOT  = 0x01
127    NDEF_URIPREFIX_HTTPS_WWWDOT = 0x02
128    NDEF_URIPREFIX_HTTP         = 0x03
129    NDEF_URIPREFIX_HTTPS        = 0x04
130    NDEF_URIPREFIX_TEL          = 0x05
131    NDEF_URIPREFIX_MAILTO       = 0x06
132    NDEF_URIPREFIX_FTP_ANONAT   = 0x07
133    NDEF_URIPREFIX_FTP_FTPDOT   = 0x08
134    NDEF_URIPREFIX_FTPS         = 0x09
135    NDEF_URIPREFIX_SFTP         = 0x0A
136    NDEF_URIPREFIX_SMB          = 0x0B
137    NDEF_URIPREFIX_NFS          = 0x0C
138    NDEF_URIPREFIX_FTP          = 0x0D
139    NDEF_URIPREFIX_DAV          = 0x0E
140    NDEF_URIPREFIX_NEWS         = 0x0F
141    NDEF_URIPREFIX_TELNET       = 0x10
142    NDEF_URIPREFIX_IMAP         = 0x11
143    NDEF_URIPREFIX_RTSP         = 0x12
144    NDEF_URIPREFIX_URN          = 0x13
145    NDEF_URIPREFIX_POP          = 0x14
146    NDEF_URIPREFIX_SIP          = 0x15
147    NDEF_URIPREFIX_SIPS         = 0x16
148    NDEF_URIPREFIX_TFTP         = 0x17
149    NDEF_URIPREFIX_BTSPP        = 0x18
150    NDEF_URIPREFIX_BTL2CAP      = 0x19
151    NDEF_URIPREFIX_BTGOEP       = 0x1A
152    NDEF_URIPREFIX_TCPOBEX      = 0x1B
153    NDEF_URIPREFIX_IRDAOBEX     = 0x1C
154    NDEF_URIPREFIX_FILE         = 0x1D
155    NDEF_URIPREFIX_URN_EPC_ID   = 0x1E
156    NDEF_URIPREFIX_URN_EPC_TAG  = 0x1F
157    NDEF_URIPREFIX_URN_EPC_PAT  = 0x20
158    NDEF_URIPREFIX_URN_EPC_RAW  = 0x21
159    NDEF_URIPREFIX_URN_EPC      = 0x22
160    NDEF_URIPREFIX_URN_NFC      = 0x23
161
162    NDEF_TYPE_MIME              = 0x02
163    NDEF_TYPE_URI               = 0x55
164    NDEF_TYPE_TEXT              = 0x54
165
166    begin = False
167    end = False
168
169    tnf = 0
170    record_type = None
171    payload = None
172    identifier = None
173
174    def set_identifier(self, identifier):
175        self.identifier = identifier
176
177    def get_raw_data(self):
178        if self.record_type == None or self.payload == None:
179            return []
180
181        # Construct tnf and flags (byte 0 of header)
182        header = [self.tnf]
183
184        if self.begin:
185            header[0] |= NdefRecord.FLAG_MESSAGE_BEGIN
186
187        if self.end:
188            header[0] |= NdefRecord.FLAG_MESSAGE_END
189
190        if len(self.payload) < 256:
191            header[0] |= NdefRecord.FLAG_SHORT_RECORD
192
193        if self.identifier != None:
194            header[0] |= NdefRecord.FLAG_ID_LENGTH
195
196        # Type length (byte 1 of header)
197        header.append(len(self.record_type))
198
199        # Payload length (byte 2 of header)
200        # TODO: payload > 255?
201        header.append(len(self.payload))
202
203        # ID length (byte 3 of header)
204        if self.identifier != None:
205            header.append(len(self.identifier))
206
207        # Record type (byte 4ff of header)
208        header.extend(self.record_type)
209
210        # ID
211        if self.identifier != None:
212            header.extend(self.identifier)
213
214        return header + self.payload
215
216class NdefTextRecord(NdefRecord):
217    # Call with text and ISO/IANA language code
218    def __init__(self, text, language='en'):
219        self.tnf = NdefRecord.TNF_WELL_KNOWN
220        self.record_type = [NdefRecord.NDEF_TYPE_TEXT]
221
222        lang_list = map(ord, language)
223        text_list = map(ord, text)
224
225        # Text Record Content: Status byte, ISO/IANA language code, text
226        # See NDEF 1.0: 3.2.1
227        self.payload = [len(lang_list)] + lang_list + text_list
228
229class NdefUriRecord(NdefRecord):
230    def __init__(self, uri, uri_prefix=NdefRecord.NDEF_URIPREFIX_NONE):
231        self.tnf = NdefRecord.TNF_WELL_KNOWN
232        self.record_type = [NdefRecord.NDEF_TYPE_URI]
233
234        uri_list = map(ord, uri)
235
236        # Text Record Content: URI prefix, URI
237        # See NDEF 1.0: 3.2.2
238        self.payload = [uri_prefix] + uri_list
239
240class NdefMediaRecord(NdefRecord):
241    def __init__(self, mime_type, data):
242        self.tnf = NdefRecord.TNF_MIME_MEDIA
243        self.record_type = map(ord, mime_type)
244
245        if isinstance(data, str):
246            self.payload = map(ord, data)
247        else:
248            self.payload = data
249
250class ExampleNdef:
251    HOST = "localhost"
252    PORT = 4223
253    UID = "XYZ" # Change XYZ to the UID of your NFC/RFID Bricklet
254
255    state_queue = Queue()
256    tag_type = None
257    tag_size = None
258
259    def __init__(self, tag_type, tag_size=512):
260        self.tag_type = tag_type
261        self.tag_size = tag_size
262        self.ipcon = IPConnection() # Create IP connection
263        self.nr = BrickletNFCRFID(self.UID, self.ipcon) # Create device object
264
265        self.ipcon.connect(self.HOST, self.PORT) # Connect to brickd
266
267        self.nr.register_callback(self.nr.CALLBACK_STATE_CHANGED, self.state_changed)
268
269    def write_message(self):
270        chunks = self.message.get_raw_data_in_chunks()
271        print("Trying to write the follwing data to the tag:")
272        pprint(chunks)
273
274        self.nr.request_tag_id(self.tag_type)
275        state = self.state_queue.get()
276
277        if state != self.nr.STATE_REQUEST_TAG_ID:
278            return -1
279
280        state = self.state_queue.get()
281
282        if state != self.nr.STATE_REQUEST_TAG_ID_READY:
283            return -2
284
285        # NFC Forum Type 1 start page is 1 (start of capability container)
286        # NFC Forum Type 2 start page is 3 (start of capability container)
287        if self.tag_type == self.nr.TAG_TYPE_TYPE1:
288            current_page = 1
289        else:
290            current_page = 3
291
292        for chunk in chunks:
293            self.nr.write_page(current_page, chunk)
294            state = self.state_queue.get()
295
296            if state != self.nr.STATE_WRITE_PAGE:
297                return -3
298
299            state = self.state_queue.get()
300
301            if state != self.nr.STATE_WRITE_PAGE_READY:
302                return -4
303
304            # NFC Forum Type 1 has 2 pages per chunk (16 byte)
305            # NFC Forum Type 2 has 4 pages per chunk (16 byte)
306            if self.tag_type == self.nr.TAG_TYPE_TYPE1:
307                current_page += 2
308            else:
309                current_page += 4
310
311        return 0
312
313    def state_changed(self, state, idle):
314        self.state_queue.put(state)
315
316    def make_message_small(self):
317        self.message = NdefMessage(self.tag_type)
318
319        # Capabilities:
320        # Version 1.0               (0x10)
321        # Tag size bytes            (given by self.tag_size)
322        # Read/write access for all (0x00)
323        self.message.set_capability_container(0x10, self.tag_size, 0x00)
324
325        record = NdefUriRecord('tinkerforge.com', NdefRecord.NDEF_URIPREFIX_HTTP_WWWDOT)
326        self.message.add_record(record)
327
328    def make_message_large(self):
329        self.message = NdefMessage(self.tag_type)
330
331        # Capabilities:
332        # Version 1.0               (0x10)
333        # Tag size bytes            (given by self.tag_size)
334        # Read/write access for all (0x00)
335        self.message.set_capability_container(0x10, self.tag_size, 0x00)
336
337        rec1 = NdefTextRecord('Hello World', 'en')
338        self.message.add_record(rec1)
339        rec2 = NdefTextRecord('Hallo Welt', 'de')
340        self.message.add_record(rec2)
341        rec3 = NdefUriRecord('tinkerforge.com', NdefRecord.NDEF_URIPREFIX_HTTP_WWWDOT)
342        self.message.add_record(rec3)
343        text = '<html><head><title>Hello</title></head><body>World!</body></html>'
344        rec4 = NdefMediaRecord('text/html', text)
345        self.message.add_record(rec4)
346
347        # To test an "image/png" you can can download the file from:
348        # http://download.tinkerforge.com/_stuff/tf_16x16.png
349        if os.path.isfile('tf_16x16.png'):
350            with open('tf_16x16.png', 'rb') as f:
351                logo = f.read()
352
353            rec5 = NdefMediaRecord('image/png', map(ord, logo))
354            self.message.add_record(rec5)
355
356if __name__ == '__main__':
357    example = ExampleNdef(tag_type=BrickletNFCRFID.TAG_TYPE_TYPE2, tag_size=888)
358    #example.make_message_large() # Writes different texts, URI, html site and image
359    example.make_message_small() # Writes simple URI record
360    ret = example.write_message()
361
362    if ret < 0:
363        print('Could not write NDEF Message: ' + str(ret))
364    else:
365        print('NDEF Message written successfully')

API

Generally, every function of the Python bindings can throw an tinkerforge.ip_connection.Error exception that has a value and a description property. value can have different values:

  • Error.TIMEOUT = -1

  • Error.NOT_ADDED = -6 (unused since Python bindings version 2.0.0)

  • Error.ALREADY_CONNECTED = -7

  • Error.NOT_CONNECTED = -8

  • Error.INVALID_PARAMETER = -9

  • Error.NOT_SUPPORTED = -10

  • Error.UNKNOWN_ERROR_CODE = -11

  • Error.STREAM_OUT_OF_SYNC = -12

  • Error.INVALID_UID = -13

  • Error.NON_ASCII_CHAR_IN_SECRET = -14

  • Error.WRONG_DEVICE_TYPE = -15

  • Error.DEVICE_REPLACED = -16

  • Error.WRONG_RESPONSE_LENGTH = -17

All functions listed below are thread-safe.

Basic Functions

BrickletNFCRFID(uid, ipcon)
Parameters:
  • uid – Type: str
  • ipcon – Type: IPConnection
Returns:
  • nfc_rfid – Type: BrickletNFCRFID

Creates an object with the unique device ID uid:

nfc_rfid = BrickletNFCRFID("YOUR_DEVICE_UID", ipcon)

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

BrickletNFCRFID.request_tag_id(tag_type)
Parameters:
  • tag_type – Type: int, Range: See constants
Returns:
  • None

To read or write a tag that is in proximity of the NFC/RFID Bricklet you first have to call this function with the expected tag type as parameter. It is no problem if you don't know the tag type. You can cycle through the available tag types until the tag gives an answer to the request.

Currently the following tag types are supported:

  • Mifare Classic

  • NFC Forum Type 1

  • NFC Forum Type 2

After you call request_tag_id() the NFC/RFID 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_STATE_CHANGED callback or you can poll get_state() to find out about the state change.

If the state changes to RequestTagIDError it means that either there was no tag present or that the tag is of an incompatible type. If the state changes to RequestTagIDReady it means that a compatible tag was found and that the tag ID could be read out. You can now get the tag ID by calling get_tag_id().

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

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

The following constants are available for this function:

For tag_type:

  • BrickletNFCRFID.TAG_TYPE_MIFARE_CLASSIC = 0

  • BrickletNFCRFID.TAG_TYPE_TYPE1 = 1

  • BrickletNFCRFID.TAG_TYPE_TYPE2 = 2

BrickletNFCRFID.get_tag_id()
Return Object:
  • tag_type – Type: int, Range: See constants
  • tid_length – Type: int, Range: [4, 7]
  • tid – Type: [int, ...], Length: 7, Range: [0 to 255]

Returns the tag type, tag ID and the length of the tag ID (4 or 7 bytes are possible length). This function can only be called if the NFC/RFID is currently in one of the Ready states. The returned ID is the ID that was saved through the last call of request_tag_id().

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

  1. Call request_tag_id()

  2. Wait for state to change to RequestTagIDReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  3. Call get_tag_id()

The following constants are available for this function:

For tag_type:

  • BrickletNFCRFID.TAG_TYPE_MIFARE_CLASSIC = 0

  • BrickletNFCRFID.TAG_TYPE_TYPE1 = 1

  • BrickletNFCRFID.TAG_TYPE_TYPE2 = 2

BrickletNFCRFID.get_state()
Return Object:
  • state – Type: int, Range: See constants
  • idle – Type: bool

Returns the current state of the NFC/RFID Bricklet.

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

The functions of this Bricklet can be called in the Idle state and all of the Ready and Error states.

Example: If you call request_page(), the state will change to RequestPage until the reading of the page is finished. Then it will change to either RequestPageReady if it worked or to RequestPageError if it didn't. If the request worked you can get the page by calling get_page().

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

The following constants are available for this function:

For state:

  • BrickletNFCRFID.STATE_INITIALIZATION = 0

  • BrickletNFCRFID.STATE_IDLE = 128

  • BrickletNFCRFID.STATE_ERROR = 192

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID = 2

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID_READY = 130

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID_ERROR = 194

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE = 3

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE_READY = 131

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE_ERROR = 195

  • BrickletNFCRFID.STATE_WRITE_PAGE = 4

  • BrickletNFCRFID.STATE_WRITE_PAGE_READY = 132

  • BrickletNFCRFID.STATE_WRITE_PAGE_ERROR = 196

  • BrickletNFCRFID.STATE_REQUEST_PAGE = 5

  • BrickletNFCRFID.STATE_REQUEST_PAGE_READY = 133

  • BrickletNFCRFID.STATE_REQUEST_PAGE_ERROR = 197

BrickletNFCRFID.authenticate_mifare_classic_page(page, key_number, key)
Parameters:
  • page – Type: int, Range: [0 to 216 - 1]
  • key_number – Type: int, Range: See constants
  • key – Type: [int, ...], Length: 6, Range: [0 to 255]
Returns:
  • None

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 request_tag_id()

  2. Wait for state to change to RequestTagIDReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  3. If looking for a specific tag then call get_tag_id() and check if the expected tag was found, if it was not found go back to step 1

  4. Call authenticate_mifare_classic_page() with page and key for the page

  5. Wait for state to change to AuthenticatingMifareClassicPageReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  6. Call request_page() or write_page() to read/write page

The following constants are available for this function:

For key_number:

  • BrickletNFCRFID.KEY_A = 0

  • BrickletNFCRFID.KEY_B = 1

BrickletNFCRFID.write_page(page, data)
Parameters:
  • page – Type: int, Range: [0 to 216 - 1]
  • data – Type: [int, ...], Length: 16, Range: [0 to 255]
Returns:
  • None

Writes 16 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 (one page is written)

  • NFC Forum Type 1 page size: 8 byte (two pages are written)

  • NFC Forum Type 2 page size: 4 byte (four pages are written)

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

  1. Call request_tag_id()

  2. Wait for state to change to RequestTagIDReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  3. If looking for a specific tag then call get_tag_id() and check if the expected tag was found, if it was not found got back to step 1

  4. Call write_page() with page number and data

  5. Wait for state to change to WritePageReady (see get_state() or CALLBACK_STATE_CHANGED callback)

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

BrickletNFCRFID.request_page(page)
Parameters:
  • page – Type: int, Range: [0 to 216 - 1]
Returns:
  • None

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

  • Mifare Classic page size: 16 byte (one page is read)

  • NFC Forum Type 1 page size: 8 byte (two pages are read)

  • NFC Forum Type 2 page size: 4 byte (four pages are read)

The general approach for reading a tag is as follows:

  1. Call request_tag_id()

  2. Wait for state to change to RequestTagIDReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  3. If looking for a specific tag then call get_tag_id() and check if the expected tag was found, if it was not found got back to step 1

  4. Call request_page() with page number

  5. Wait for state to change to RequestPageReady (see get_state() or CALLBACK_STATE_CHANGED callback)

  6. Call get_page() 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 authenticate_mifare_classic_page().

BrickletNFCRFID.get_page()
Returns:
  • data – Type: [int, ...], Length: 16, Range: [0 to 255]

Returns 16 bytes of data from an internal buffer. To fill the buffer with specific pages you have to call request_page() beforehand.

Advanced Functions

BrickletNFCRFID.get_identity()
Return Object:
  • uid – Type: str, Length: up to 8
  • connected_uid – Type: str, Length: up to 8
  • position – Type: chr, Range: ["a" to "h", "z"]
  • hardware_version – 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]
  • firmware_version – 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]
  • device_identifier – Type: int, Range: [0 to 216 - 1]

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

BrickletNFCRFID.register_callback(callback_id, function)
Parameters:
  • callback_id – Type: int
  • function – Type: callable
Returns:
  • None

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 register_callback() function of the device object. The first parameter is the callback ID and the second parameter the callback function:

def my_callback(param):
    print(param)

nfc_rfid.register_callback(BrickletNFCRFID.CALLBACK_EXAMPLE, my_callback)

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.

BrickletNFCRFID.CALLBACK_STATE_CHANGED
Callback Parameters:
  • state – Type: int, Range: See constants
  • idle – Type: bool

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

The following constants are available for this function:

For state:

  • BrickletNFCRFID.STATE_INITIALIZATION = 0

  • BrickletNFCRFID.STATE_IDLE = 128

  • BrickletNFCRFID.STATE_ERROR = 192

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID = 2

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID_READY = 130

  • BrickletNFCRFID.STATE_REQUEST_TAG_ID_ERROR = 194

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE = 3

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE_READY = 131

  • BrickletNFCRFID.STATE_AUTHENTICATING_MIFARE_CLASSIC_PAGE_ERROR = 195

  • BrickletNFCRFID.STATE_WRITE_PAGE = 4

  • BrickletNFCRFID.STATE_WRITE_PAGE_READY = 132

  • BrickletNFCRFID.STATE_WRITE_PAGE_ERROR = 196

  • BrickletNFCRFID.STATE_REQUEST_PAGE = 5

  • BrickletNFCRFID.STATE_REQUEST_PAGE_READY = 133

  • BrickletNFCRFID.STATE_REQUEST_PAGE_ERROR = 197

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.

BrickletNFCRFID.get_api_version()
Return Object:
  • api_version – 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.

BrickletNFCRFID.get_response_expected(function_id)
Parameters:
  • function_id – Type: int, Range: See constants
Returns:
  • response_expected – Type: bool

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 set_response_expected(). 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:

  • BrickletNFCRFID.FUNCTION_REQUEST_TAG_ID = 1

  • BrickletNFCRFID.FUNCTION_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 4

  • BrickletNFCRFID.FUNCTION_WRITE_PAGE = 5

  • BrickletNFCRFID.FUNCTION_REQUEST_PAGE = 6

BrickletNFCRFID.set_response_expected(function_id, response_expected)
Parameters:
  • function_id – Type: int, Range: See constants
  • response_expected – Type: bool
Returns:
  • None

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:

  • BrickletNFCRFID.FUNCTION_REQUEST_TAG_ID = 1

  • BrickletNFCRFID.FUNCTION_AUTHENTICATE_MIFARE_CLASSIC_PAGE = 4

  • BrickletNFCRFID.FUNCTION_WRITE_PAGE = 5

  • BrickletNFCRFID.FUNCTION_REQUEST_PAGE = 6

BrickletNFCRFID.set_response_expected_all(response_expected)
Parameters:
  • response_expected – Type: bool
Returns:
  • None

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

Constants

BrickletNFCRFID.DEVICE_IDENTIFIER

This constant is used to identify a NFC/RFID Bricklet.

The get_identity() 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.

BrickletNFCRFID.DEVICE_DISPLAY_NAME

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