Write NDEF Records From Python With ndeflib
ndeflib builds and parses NDEF messages in pure Python. Here is how to make Text, URI and Smartposter records, encode them to bytes, and check them before any tag is involved.
You can build the exact bytes an NFC tag should hold from a Python script using ndeflib, and check them before you ever tap a tag. The library makes and reads NDEF messages. It doesn't talk to a tag, which is the part people often expect it to do.
What is inside an NDEF message
An NDEF message is one or more records. Each record has a header with a 3-bit TNF (Type Name Format), then a type, an optional ID and a payload, as the Android NdefRecord reference describes. The well-known TNF is 1, and its type names include T for text, U for URI and Sp for Smart Poster.
ndeflib mirrors that layout. You make record objects, and the library turns a list of them into bytes.
Install ndeflib
pip install ndeflib
You import it as ndef. According to its PyPI page, ndeflib is pure Python with an ISC licence. The latest release is 0.3.3, from May 2019, and the classifiers list Python 2.7 and 3.4/3.5. That's old. Pure Python usually ages well, but test it on your own Python version before you build a workflow on it.
Build a Text record and a URI record
A text record takes the text, a language code and an encoding:
import ndef
text = ndef.TextRecord("Hallo Welt", "de")
The language defaults to en and the encoding to UTF-8. UTF-16 is the other option. If you want to know when that matters, see UTF-8 versus UTF-16 in text records.
A URI record takes the address:
link = ndef.UriRecord("http://www.example.com")
Encoded, that record is d1 01 0c 55 01 followed by example.com. The 01 after the U is a prefix code that stands in for http://www., which saves bytes on a small tag. The ndeflib URI page says the library expands those prefix codes for you when it decodes. Its uri attribute gives an ASCII-only form, while iri keeps the original characters.
Encode a message to bytes and decode it back
ndef.message_encoder takes a list of records and yields bytes, one chunk per record. Join the chunks to get the full message:
message = [ndef.TextRecord("Hello"), ndef.TextRecord("World")]
payload = b"".join(ndef.message_encoder(message))
print(payload.hex())
That prints 9101085402656e48656c6c6f5101085402656e576f726c64, which is the example on the ndeflib front page. Going the other way:
for record in ndef.message_decoder(bytearray.fromhex(payload.hex())):
print(record)
You get NDEF Text Record ID '' Text 'Hello' Language 'en' Encoding 'UTF-8' and the same for World.
The decoder has three modes through its errors argument, per the encode and decode docs:
strictis the default. It wants a valid message, with the Message Begin flag on the first record and Message End on the last.relaxaccepts minor format errors.ignorestops quietly at an error it cannot fix.
Bad input to the encoder raises ndef.EncodeError, and a format error in the decoder raises ndef.DecodeError. Use strict while you build, so mistakes show up now and not on a tag in a drawer.
Smartposter and generic records
A Smartposter bundles a link with a title and a suggested action. Only the resource is required:
poster = ndef.SmartposterRecord("https://github.com/nfcpy/ndeflib")
poster.set_title("Python package for parsing and generating NDEF", "en")
poster.resource_type = "text/html"
poster.action = "exec"
The action can be exec, save or edit. The docs show a similar poster, with a size set as well, coming out at 115 bytes. Keep that in mind: a small tag may not have room for it.
For anything else there is the generic ndef.Record(type, name, data). It covers every TNF form, and name is the record ID, up to 255 characters. Payloads are capped at 1 MB by default through Record.MAX_PAYLOAD_SIZE. The library also lists Wi-Fi Simple Configuration and Bluetooth pairing record types; our look at the Wi-Fi WSC record shows what that payload holds.
Get the bytes onto a tag
ndeflib stops at bytes. To write them you need a reader/writer and a library or app that sends them to the tag. Before you do, compare the message length with the tag's capacity, and check whether the tag is locked. A locked tag will refuse the write, and changing a tag after writing it is only possible when it is not.
If you would rather skip the scripting for a one-off tag, NFCore on the App Store and Google Play write NDEF records from your phone.
Quick recap
Use ndeflib to make and check NDEF bytes offline: build records, encode with message_encoder, decode with message_decoder in strict mode, and compare the length with your tag's capacity. Treat the 2019 release date as a reason to test, not a reason to avoid it.
Frequently Asked Questions
Does ndeflib write to a tag by itself?
No. ndeflib only builds and parses NDEF bytes. You need a reader/writer and a separate tool or library to send those bytes to a tag.
Is ndeflib still maintained?
PyPI shows 0.3.3 as the latest release, dated May 2019, and its classifiers list Python 2.7 and 3.4/3.5. It is pure Python, so test it on your own Python version before relying on it.
How do I make a Wi-Fi or Bluetooth record?
The docs list Wi-Fi Simple Configuration and Bluetooth Secure Simple Pairing record types, each on its own page. For anything private, the generic Record class takes a type, an ID and raw payload bytes.
What does an invalid value do?
The encoder raises ndef.EncodeError for invalid record values, and the decoder raises ndef.DecodeError on a format error unless you pass errors='ignore'.