read_tag.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. #!/usr/bin/env python3
  2. """PN5180 NFC tag reader — ported from working Pico firmware (pico-nfc-bridge.ino).
  3. Key learnings from pico-nfc-bridge.ino:
  4. - Must call setTransceiveMode() before every SEND_DATA
  5. - waitBusy() must wait for HIGH then LOW (not just LOW)
  6. - Bambu tags are MIFARE Classic 1K (ISO 14443A), not ISO 15693
  7. - SPI at 500kHz, 5µs CS setup, 100µs post-CS delay
  8. - MFC_AUTHENTICATE (0x0C) is a PN5180 host command — Crypto1 handled in hardware
  9. - HKDF-SHA256 derives per-sector keys from master key + UID
  10. """
  11. import hashlib
  12. import hmac
  13. import os
  14. import sys
  15. import time
  16. import gpiod
  17. import spidev
  18. def _env_int(name: str, default: int) -> int:
  19. value = os.environ.get(name)
  20. if value is None or value == "":
  21. return default
  22. try:
  23. return int(value)
  24. except ValueError:
  25. return default
  26. BUSY_PIN = _env_int("SPOOLBUDDY_NFC_BUSY_PIN", 25)
  27. RST_PIN = _env_int("SPOOLBUDDY_NFC_RST_PIN", 24)
  28. NSS_PIN = _env_int("SPOOLBUDDY_NFC_NSS_PIN", 23) # Manual CS by default
  29. SPI_BUS = _env_int("SPOOLBUDDY_NFC_SPI_BUS", 0)
  30. SPI_DEVICE = _env_int("SPOOLBUDDY_NFC_SPI_DEVICE", 0)
  31. SPI_SPEED_HZ = _env_int("SPOOLBUDDY_NFC_SPI_SPEED_HZ", 500_000)
  32. # Bambu Lab MIFARE Classic key derivation constants (from pico-nfc-bridge.ino)
  33. BAMBU_MASTER_KEY = bytes(
  34. [
  35. 0x9A,
  36. 0x75,
  37. 0x9C,
  38. 0xF2,
  39. 0xC4,
  40. 0xF7,
  41. 0xCA,
  42. 0xFF,
  43. 0x22,
  44. 0x2C,
  45. 0xB9,
  46. 0x76,
  47. 0x9B,
  48. 0x41,
  49. 0xBC,
  50. 0x96,
  51. ]
  52. )
  53. BAMBU_CONTEXT = b"RFID-A\x00" # 7 bytes including null terminator
  54. # Blocks to read for Bambu tag data
  55. BAMBU_BLOCKS = [1, 2, 4, 5]
  56. def hkdf_derive_keys(uid: bytes) -> bytes:
  57. """Derive 96 bytes of MIFARE key material (16 sectors * 6 bytes each).
  58. Uses HKDF-SHA256 with the Bambu master key as salt and the tag UID as IKM.
  59. """
  60. # HKDF-Extract: PRK = HMAC-SHA256(salt=master_key, IKM=uid)
  61. prk = hmac.new(BAMBU_MASTER_KEY, uid, hashlib.sha256).digest()
  62. # HKDF-Expand: generate 96 bytes using context "RFID-A\0"
  63. okm = b""
  64. t = b""
  65. counter = 1
  66. while len(okm) < 96:
  67. t = hmac.new(prk, t + BAMBU_CONTEXT + bytes([counter]), hashlib.sha256).digest()
  68. okm += t
  69. counter += 1
  70. return okm[:96]
  71. def get_sector_key(keys: bytes, block: int) -> bytes:
  72. """Get the 6-byte key for the sector containing the given block."""
  73. sector = block // 4
  74. return keys[sector * 6 : sector * 6 + 6]
  75. def _find_gpio_chip():
  76. for path in ["/dev/gpiochip4", "/dev/gpiochip0"]:
  77. try:
  78. chip = gpiod.Chip(path)
  79. if "pinctrl" in chip.get_info().label:
  80. return chip
  81. chip.close()
  82. except (FileNotFoundError, PermissionError, OSError):
  83. continue
  84. raise RuntimeError("No GPIO chip")
  85. class PN5180:
  86. def __init__(self):
  87. self._chip = _find_gpio_chip()
  88. self._lines = self._chip.request_lines(
  89. consumer="pn5180",
  90. config={
  91. BUSY_PIN: gpiod.LineSettings(direction=gpiod.line.Direction.INPUT),
  92. RST_PIN: gpiod.LineSettings(
  93. direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
  94. ),
  95. NSS_PIN: gpiod.LineSettings(
  96. direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
  97. ),
  98. },
  99. )
  100. self._spi = spidev.SpiDev()
  101. self._spi.open(SPI_BUS, SPI_DEVICE)
  102. self._spi.max_speed_hz = SPI_SPEED_HZ
  103. self._spi.mode = 0b00
  104. # #1424: Pi 5's RP1 spi-rp1 driver rejects SPI_NO_CS, which used to
  105. # work on Pi 4. Harmless either way on this hardware — NSS is wired
  106. # to GPIO23 (manual CS in _cs_low/_cs_high), so the kernel's CE0
  107. # toggling has no electrical effect on the reader.
  108. try:
  109. self._spi.no_cs = True
  110. except OSError:
  111. pass
  112. def close(self):
  113. self._spi.close()
  114. self._lines.release()
  115. self._chip.close()
  116. def _cs_low(self):
  117. self._lines.set_value(NSS_PIN, gpiod.line.Value.INACTIVE)
  118. time.sleep(0.000005) # 5µs setup
  119. def _cs_high(self):
  120. self._lines.set_value(NSS_PIN, gpiod.line.Value.ACTIVE)
  121. time.sleep(0.000100) # 100µs post-CS delay
  122. def _wait_busy(self, timeout_s=1.0):
  123. """Wait for BUSY to go HIGH (processing) then LOW (done) — matches Pico firmware."""
  124. deadline = time.monotonic() + min(timeout_s, 0.010)
  125. # Wait for BUSY HIGH (PN5180 started processing)
  126. while self._lines.get_value(BUSY_PIN) != gpiod.line.Value.ACTIVE:
  127. if time.monotonic() > deadline:
  128. break # Timeout waiting for HIGH — command may have processed already
  129. time.sleep(0.00001)
  130. # Wait for BUSY LOW (PN5180 done)
  131. deadline = time.monotonic() + timeout_s
  132. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  133. if time.monotonic() > deadline:
  134. raise TimeoutError("BUSY timeout")
  135. time.sleep(0.0001)
  136. def _cmd(self, data):
  137. self._cs_low()
  138. self._spi.xfer2(list(data))
  139. self._cs_high()
  140. self._wait_busy()
  141. def _read_response(self, n):
  142. self._cs_low()
  143. result = self._spi.xfer2([0xFF] * n)
  144. self._cs_high()
  145. return result
  146. # -- Register ops --
  147. def write_reg(self, reg, val):
  148. self._cmd([0x00, reg, val & 0xFF, (val >> 8) & 0xFF, (val >> 16) & 0xFF, (val >> 24) & 0xFF])
  149. def write_reg_or(self, reg, mask):
  150. self._cmd([0x01, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  151. def write_reg_and(self, reg, mask):
  152. self._cmd([0x02, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  153. def read_reg(self, reg):
  154. self._cmd([0x04, reg])
  155. time.sleep(0.000100) # Extra 100µs before read
  156. return int.from_bytes(self._read_response(4), "little")
  157. def read_eeprom(self, addr, length):
  158. self._cmd([0x07, addr, length])
  159. time.sleep(0.000100)
  160. return bytes(self._read_response(length))
  161. # -- Commands --
  162. def reset(self):
  163. self._lines.set_value(RST_PIN, gpiod.line.Value.INACTIVE)
  164. time.sleep(0.050)
  165. self._lines.set_value(RST_PIN, gpiod.line.Value.ACTIVE)
  166. time.sleep(0.100)
  167. self._wait_busy(2.0)
  168. time.sleep(0.050)
  169. def load_rf_config(self, tx, rx):
  170. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs first
  171. time.sleep(0.000100)
  172. self._cmd([0x11, tx, rx])
  173. time.sleep(0.010)
  174. def rf_on(self):
  175. self._cmd([0x16, 0x00])
  176. time.sleep(0.010)
  177. def rf_off(self):
  178. self._cmd([0x17, 0x00])
  179. time.sleep(0.005)
  180. def set_transceive_mode(self):
  181. """Set SYSTEM_CONFIG command bits to TRANSCEIVE (0x03) — CRITICAL!"""
  182. sys_cfg = self.read_reg(0x00)
  183. sys_cfg = (sys_cfg & 0xFFFFFFF8) | 0x03
  184. self.write_reg(0x00, sys_cfg)
  185. def send_data(self, data, valid_bits=0x00):
  186. self._cs_low()
  187. self._spi.xfer2([0x09, valid_bits] + list(data))
  188. self._cs_high()
  189. time.sleep(0.000100)
  190. self._wait_busy()
  191. def read_data(self, length):
  192. self._cmd([0x0A, 0x00])
  193. return bytes(self._read_response(length))
  194. # -- ISO 14443A --
  195. def activate_type_a(self):
  196. """Full Type A activation: WUPA -> Anticollision -> SELECT. Returns (uid, sak) or None."""
  197. # Crypto off, CRC off
  198. self.write_reg_and(0x00, 0xFFFFFFBF)
  199. self.write_reg_and(0x12, 0xFFFFFFFE)
  200. self.write_reg_and(0x19, 0xFFFFFFFE)
  201. self.write_reg(0x03, 0xFFFFFFFF)
  202. # Reset to IDLE then TRANSCEIVE
  203. sys_cfg = self.read_reg(0x00)
  204. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  205. time.sleep(0.001)
  206. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  207. time.sleep(0.002)
  208. # WUPA (7-bit)
  209. self.send_data([0x52], valid_bits=0x07)
  210. time.sleep(0.005)
  211. rx_status = self.read_reg(0x13)
  212. rx_len = rx_status & 0x1FF
  213. if rx_len < 2 or rx_len == 511:
  214. # Try REQA
  215. self.write_reg(0x03, 0xFFFFFFFF)
  216. time.sleep(0.002)
  217. self.set_transceive_mode()
  218. time.sleep(0.002)
  219. self.send_data([0x26], valid_bits=0x07)
  220. time.sleep(0.005)
  221. rx_status = self.read_reg(0x13)
  222. rx_len = rx_status & 0x1FF
  223. if rx_len < 2 or rx_len == 511:
  224. return None
  225. atqa = self.read_data(2)
  226. if atqa[0] == 0xFF or atqa[0] == 0x00:
  227. return None
  228. # Anti-collision Level 1
  229. self.write_reg(0x03, 0xFFFFFFFF)
  230. self.set_transceive_mode()
  231. time.sleep(0.002)
  232. self.send_data([0x93, 0x20])
  233. time.sleep(0.010)
  234. rx_status = self.read_reg(0x13)
  235. rx_len = rx_status & 0x1FF
  236. if rx_len < 5 or rx_len > 64:
  237. return None
  238. uid_buf = self.read_data(5)
  239. uid = uid_buf[:4]
  240. bcc = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]
  241. if bcc != uid_buf[4]:
  242. return None
  243. # SELECT
  244. self.write_reg(0x03, 0xFFFFFFFF)
  245. self.set_transceive_mode()
  246. time.sleep(0.002)
  247. # Enable CRC for SELECT
  248. self.write_reg_or(0x19, 0x01)
  249. self.write_reg_or(0x12, 0x01)
  250. self.send_data([0x93, 0x70, uid[0], uid[1], uid[2], uid[3], bcc])
  251. time.sleep(0.010)
  252. rx_status = self.read_reg(0x13)
  253. rx_len = rx_status & 0x1FF
  254. if rx_len < 1:
  255. return None
  256. sak_buf = self.read_data(min(rx_len, 3))
  257. sak = sak_buf[0]
  258. return bytes(uid), sak
  259. # -- MIFARE Classic --
  260. def mfc_authenticate(self, block: int, key: bytes, uid: bytes) -> bool:
  261. """MIFARE Classic authentication via PN5180 MFC_AUTHENTICATE (0x0C).
  262. The PN5180 handles Crypto1 internally. After success, bit 6 of
  263. SYSTEM_CONFIG is set (MFC_CRYPTO1_ON) and all subsequent RF
  264. communication is encrypted/decrypted by the hardware.
  265. Args:
  266. block: Block number to authenticate
  267. key: 6-byte MIFARE Key A
  268. uid: 4-byte tag UID
  269. Returns:
  270. True if authentication succeeded
  271. """
  272. # Wait for BUSY LOW before starting
  273. deadline = time.monotonic() + 0.100
  274. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  275. if time.monotonic() > deadline:
  276. return False
  277. time.sleep(0.001)
  278. # MFC_AUTHENTICATE: [0x0C][key 6B][keyType][blockNo][uid 4B] = 13 bytes
  279. cmd = [0x0C] + list(key) + [0x60, block] + list(uid[:4])
  280. self._cs_low()
  281. self._spi.xfer2(cmd)
  282. self._cs_high()
  283. # Wait for BUSY HIGH then LOW (auth can take up to 1s)
  284. self._wait_busy(timeout_s=1.0)
  285. # Read 1-byte response: 0x00 = success
  286. self._cs_low()
  287. response = self._spi.xfer2([0xFF])
  288. self._cs_high()
  289. return response[0] == 0x00
  290. def mfc_read_block(self, block: int) -> bytes | None:
  291. """Read a 16-byte MIFARE Classic block (must be authenticated first).
  292. Returns 16 bytes of block data, or None on failure.
  293. """
  294. # Clear IRQs
  295. self.write_reg(0x03, 0xFFFFFFFF)
  296. # Set transceive mode (Crypto1 stays active from MFC_AUTHENTICATE)
  297. self.set_transceive_mode()
  298. time.sleep(0.001)
  299. # Enable TX and RX CRC for encrypted read
  300. self.write_reg_or(0x19, 0x01)
  301. self.write_reg_or(0x12, 0x01)
  302. # Send MIFARE READ command: 0x30 + block number
  303. self.send_data([0x30, block])
  304. time.sleep(0.010)
  305. # Check RX status
  306. rx_status = self.read_reg(0x13)
  307. rx_len = rx_status & 0x1FF
  308. if rx_len != 16:
  309. return None
  310. return self.read_data(16)
  311. def _ntag_reactivate(self) -> bool:
  312. """Full hardware reset + RF activation for NTAG re-selection between reads.
  313. The PN5180 enters an unrecoverable state after an NTAG READ command —
  314. simple RF off/on cycles cannot re-select the tag. A full GPIO hardware
  315. reset is required to clear the internal transceiver state.
  316. """
  317. self.reset()
  318. self.load_rf_config(0x00, 0x80) # ISO 14443A
  319. time.sleep(0.010)
  320. self.rf_on()
  321. time.sleep(0.030)
  322. self.set_transceive_mode()
  323. return self.activate_type_a() is not None
  324. def ntag_read_pages(self, start_page: int, num_pages: int) -> bytes | None:
  325. """Read NTAG pages (4 bytes each). No authentication required.
  326. Uses NTAG READ command (0x30) which returns 4 pages (16 bytes) at a time.
  327. The PN5180 cannot issue consecutive NTAG READs in one session — the card
  328. stops responding after the first READ. We do a full RF cycle and re-select
  329. with extended timing between each 4-page batch.
  330. """
  331. result = bytearray()
  332. pages_read = 0
  333. while pages_read < num_pages:
  334. if pages_read > 0:
  335. if not self._ntag_reactivate():
  336. print(f" Failed to reactivate card before page {start_page + pages_read}")
  337. return None
  338. # Setup: Crypto1 off, TX CRC on, RX CRC off, IDLE→TRANSCEIVE
  339. self.write_reg_and(0x00, 0xFFFFFFBF)
  340. self.write_reg_or(0x19, 0x01)
  341. self.write_reg_and(0x12, 0xFFFFFFFE)
  342. self.write_reg(0x03, 0xFFFFFFFF)
  343. sys_cfg = self.read_reg(0x00)
  344. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  345. time.sleep(0.001)
  346. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  347. time.sleep(0.002)
  348. # READ command: 0x30 + page → returns 16 bytes (4 pages)
  349. self.send_data([0x30, start_page + pages_read])
  350. time.sleep(0.010)
  351. rx_status = self.read_reg(0x13)
  352. rx_len = rx_status & 0x1FF
  353. if rx_len < 16:
  354. # Tag may have fewer pages than requested (e.g. MIFARE Ultralight
  355. # has only 16 pages). Return what we have so far.
  356. if result:
  357. return bytes(result)
  358. print(f" NTAG read page {start_page + pages_read}: rx_len={rx_len} (expected >=16)")
  359. return None
  360. data = self.read_data(16)
  361. pages_to_copy = min(4, num_pages - pages_read)
  362. result.extend(data[: pages_to_copy * 4])
  363. pages_read += 4
  364. return bytes(result)
  365. def reactivate_card(self) -> tuple[bytes, int] | None:
  366. """RF cycle and full re-select of the card. Returns (uid, sak) or None."""
  367. self.rf_off()
  368. time.sleep(0.010)
  369. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  370. self.load_rf_config(0x00, 0x80) # ISO 14443A
  371. time.sleep(0.005)
  372. self.rf_on()
  373. time.sleep(0.020)
  374. return self.activate_type_a()
  375. def read_bambu_tag(self, uid: bytes) -> dict[int, bytes] | None:
  376. """Read Bambu tag data blocks using HKDF-derived keys.
  377. Args:
  378. uid: 4-byte tag UID (from activate_type_a)
  379. Returns:
  380. Dict mapping block number -> 16 bytes of data, or None on failure
  381. """
  382. # Derive per-sector keys from UID
  383. keys = hkdf_derive_keys(uid)
  384. # Clear Crypto1 state and IRQs
  385. self.write_reg_and(0x00, 0xFFFFFFBF) # Clear MFC_CRYPTO1_ON (bit 6)
  386. self.write_reg(0x03, 0xFFFFFFFF)
  387. # Reactivate card (may have timed out)
  388. result = self.reactivate_card()
  389. if result is None:
  390. print(" Failed to reactivate card")
  391. return None
  392. uid_check, _ = result
  393. if uid_check != uid:
  394. print(f" UID mismatch after reactivation: {uid_check.hex()} != {uid.hex()}")
  395. return None
  396. # Read blocks with per-sector authentication
  397. blocks = {}
  398. current_sector = -1
  399. for block in BAMBU_BLOCKS:
  400. sector = block // 4
  401. # Authenticate when entering a new sector
  402. if sector != current_sector:
  403. key = get_sector_key(keys, block)
  404. if not self.mfc_authenticate(block, key, uid):
  405. print(f" Auth failed for block {block} (sector {sector})")
  406. return None
  407. current_sector = sector
  408. # Read the block
  409. data = self.mfc_read_block(block)
  410. if data is None:
  411. print(f" Read failed for block {block}")
  412. return None
  413. blocks[block] = data
  414. return blocks
  415. def ntag_write_page(self, page: int, data: bytes) -> bool:
  416. """Write 4 bytes to a single NTAG page.
  417. NTAG WRITE command: 0xA2 + page_number + 4 bytes data.
  418. TX CRC on (tag requires it). Always returns True — the 4-bit ACK
  419. cannot be captured by the PN5180, so verification is deferred to
  420. ntag_write_pages() which reads back all written data.
  421. """
  422. if len(data) != 4:
  423. return False
  424. # Crypto1 off, TX CRC on (tag expects CRC), RX CRC off (ACK is 4-bit, no CRC)
  425. self.write_reg_and(0x00, 0xFFFFFFBF) # Crypto1 off
  426. self.write_reg_or(0x19, 0x01) # TX CRC on
  427. self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
  428. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  429. # Reset state machine: IDLE then TRANSCEIVE
  430. sys_cfg = self.read_reg(0x00)
  431. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  432. time.sleep(0.001)
  433. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  434. time.sleep(0.002)
  435. # WRITE command: 0xA2 + page + 4 bytes
  436. self.send_data([0xA2, page] + list(data))
  437. time.sleep(0.005)
  438. # PN5180 cannot reliably capture the 4-bit ACK, so always return True
  439. return True
  440. def ntag_write_pages(self, start_page: int, data: bytes) -> bool:
  441. """Write data to consecutive NTAG pages starting at start_page.
  442. Pads last chunk to 4 bytes. Verification is skipped — the PN5180
  443. cannot reliably read back NTAG pages after a batch write (the
  444. second READ command gets no response). The write itself is reliable:
  445. the tag ACKs each page (RX SOF detected on every response).
  446. """
  447. # Pad to 4-byte boundary
  448. padded = bytearray(data)
  449. while len(padded) % 4 != 0:
  450. padded.append(0x00)
  451. # Write page by page
  452. num_pages = len(padded) // 4
  453. for i in range(0, len(padded), 4):
  454. page = start_page + (i // 4)
  455. chunk = bytes(padded[i : i + 4])
  456. if not self.ntag_write_page(page, chunk):
  457. print(f" NTAG write failed at page {page} (of {num_pages} pages)")
  458. return False
  459. time.sleep(0.002)
  460. print(f" NTAG write complete ({num_pages} pages)")
  461. return True
  462. def read_ntag(self, uid: bytes) -> bytes | None:
  463. """Read NTAG pages 4-20 (NDEF data area, 68 bytes). No auth needed.
  464. Used for SpoolEase / OpenPrintTag community tags.
  465. """
  466. # Reactivate card
  467. result = self.reactivate_card()
  468. if result is None:
  469. print(" Failed to reactivate card")
  470. return None
  471. return self.ntag_read_pages(start_page=4, num_pages=17)
  472. def _print_hex_dump(data: bytes, label: str, bytes_per_line: int = 16):
  473. """Print a hex dump with ASCII sidebar."""
  474. for i in range(0, len(data), bytes_per_line):
  475. chunk = data[i : i + bytes_per_line]
  476. hex_str = " ".join(f"{b:02X}" for b in chunk)
  477. ascii_str = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
  478. print(f" {label}{i:3d}: {hex_str:<{bytes_per_line * 3}}|{ascii_str}|")
  479. def main():
  480. print("=" * 60)
  481. print("PN5180 NFC Tag Reader")
  482. print(" Supports: Bambu (MIFARE Classic) + NTAG (SpoolEase/OpenPrintTag)")
  483. print("=" * 60)
  484. try:
  485. nfc = PN5180()
  486. except (OSError, RuntimeError, PermissionError) as e:
  487. print(f"\nERROR: Failed to initialize NFC reader: {e}")
  488. # Check if it's a resource conflict
  489. error_str = str(e).lower()
  490. is_resource_conflict = any(x in error_str for x in ["busy", "resource", "already in use", "permission denied"])
  491. if is_resource_conflict:
  492. print("\nGPIO/SPI RESOURCE IN USE: Another process is using the NFC reader.")
  493. print("This typically means the SpoolBuddy daemon is already reading tags.")
  494. print("\nTo run this diagnostic, stop the daemon first:")
  495. print(" sudo systemctl stop bambuddy")
  496. print(" # Run diagnostic")
  497. print(" .../read_tag.py")
  498. print(" # Restart daemon when done:")
  499. print(" sudo systemctl start bambuddy")
  500. else:
  501. print("\nCheck:")
  502. print(" - Correct GPIO chip is available (/dev/gpiochip0 or /dev/gpiochip4)")
  503. print(f" - SPI device is available (SPI_BUS={SPI_BUS}, SPI_DEVICE={SPI_DEVICE})")
  504. print(" - GPIO and SPI permissions are correct")
  505. # Only print full traceback for unexpected errors
  506. import traceback
  507. traceback.print_exc()
  508. sys.exit(1)
  509. try:
  510. nfc.reset()
  511. ver = nfc.read_eeprom(0x10, 2)
  512. print(f"[1] Reset OK — product v{ver[1]}.{ver[0]}")
  513. nfc.load_rf_config(0x00, 0x80) # ISO 14443A
  514. time.sleep(0.010)
  515. nfc.rf_on()
  516. time.sleep(0.030)
  517. nfc.set_transceive_mode()
  518. rf = nfc.read_reg(0x1D)
  519. print(f"[2] RF ON (RF_STATUS=0x{rf:08X}, TX_RF={'ON' if rf & 1 else 'OFF'})")
  520. print("[3] Scanning for tag...")
  521. result = nfc.activate_type_a()
  522. if result is None:
  523. print(" No tag found.")
  524. sys.exit(1)
  525. uid, sak = result
  526. tag_types = {
  527. 0x00: "NTAG",
  528. 0x04: "NTAG (MIFARE Ultralight)",
  529. 0x08: "MIFARE Classic 1K",
  530. 0x18: "MIFARE Classic 4K",
  531. }
  532. print(f" UID : {uid.hex().upper()}")
  533. print(f" SAK : 0x{sak:02X} ({tag_types.get(sak, 'Unknown')})")
  534. if sak in (0x08, 0x18):
  535. # MIFARE Classic 1K or 4K — Bambu Lab tag
  536. print("[4] Reading Bambu tag data (MIFARE Classic)...")
  537. blocks = nfc.read_bambu_tag(uid)
  538. if blocks is None:
  539. print(" Failed to read tag data.")
  540. nfc.rf_off()
  541. sys.exit(1)
  542. print("[5] Tag data:")
  543. for block_num in BAMBU_BLOCKS:
  544. data = blocks[block_num]
  545. hex_str = " ".join(f"{b:02X}" for b in data)
  546. ascii_str = "".join(chr(b) if 32 <= b < 127 else "." for b in data)
  547. print(f" Block {block_num:2d}: {hex_str} |{ascii_str}|")
  548. raw = b""
  549. for block_num in BAMBU_BLOCKS:
  550. raw += blocks[block_num]
  551. print(f"\n Raw payload ({len(raw)} bytes): {raw.hex().upper()}")
  552. elif sak in (0x00, 0x04):
  553. # NTAG / MIFARE Ultralight family — SpoolEase / OpenPrintTag
  554. print("[4] Reading NTAG data (pages 4-20)...")
  555. ntag_data = nfc.read_ntag(uid)
  556. if ntag_data is None:
  557. print(" Failed to read NTAG data.")
  558. nfc.rf_off()
  559. sys.exit(1)
  560. print(f"[5] NTAG data ({len(ntag_data)} bytes):")
  561. _print_hex_dump(ntag_data, "page ")
  562. else:
  563. print(f" Unsupported tag type (SAK=0x{sak:02X})")
  564. nfc.rf_off()
  565. sys.exit(1)
  566. nfc.rf_off()
  567. print("\n" + "=" * 60)
  568. print("Tag read complete!")
  569. print("=" * 60)
  570. except Exception as e:
  571. print(f"\nERROR: {e}")
  572. import traceback
  573. traceback.print_exc()
  574. sys.exit(1)
  575. finally:
  576. nfc.close()
  577. if __name__ == "__main__":
  578. main()