← Back to the chapter · Previous detail · Next detail →
Technical detail · NFC Tag Programming
Python and USB reader pattern
Python tools are useful for programming batches, lab stations, and maintenance tags. The writer should read the tag first, reject non-writable or undersized tags, write the records, and then read the records back.
import nfc
import ndef
RECORDS = [
ndef.UriRecord("https://ops.example.invalid/a/gateway-041"),
ndef.TextRecord("Gateway 041 maintenance record", language="en"),
]
def on_tag(tag):
if not tag.ndef:
print("Tag is not NDEF formatted")
return False
if not tag.ndef.is_writeable:
print("Tag is read-only")
return False
encoded = b"".join(ndef.message_encoder(RECORDS))
if len(encoded) > tag.ndef.capacity:
print("Payload does not fit this tag")
return False
tag.ndef.records = RECORDS
changed = tag.ndef.has_changed
if changed or tag.ndef is None or tag.ndef.octets != encoded:
print("Read-back validation failed")
return False
print("Tag written and verified")
return False
with nfc.ContactlessFrontend("usb") as reader:
reader.connect(rdwr={"on-connect": on_tag})
nfc.ContactlessFrontend("usb") is common for supported USB readers. PN532 boards may require a serial or driver-specific connection string. Keep the exact station hardware and driver version in the deployment notes so batch writes are repeatable.