pn5180.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. """PN5180 NFC frontend driver — ported from working Pico firmware (pico-nfc-bridge.ino).
  2. Key learnings from pico-nfc-bridge.ino:
  3. - Must call setTransceiveMode() before every SEND_DATA
  4. - waitBusy() must wait for HIGH then LOW (not just LOW)
  5. - Bambu tags are MIFARE Classic 1K (ISO 14443A), not ISO 15693
  6. - SPI at 500kHz, 5us CS setup, 100us post-CS delay
  7. - MFC_AUTHENTICATE (0x0C) is a PN5180 host command — Crypto1 handled in hardware
  8. - HKDF-SHA256 derives per-sector keys from master key + UID
  9. """
  10. import hashlib
  11. import hmac
  12. import logging
  13. import os
  14. import time
  15. import gpiod
  16. import spidev
  17. logger = logging.getLogger(__name__)
  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. Block 9 (sector 2) holds the tray UUID,
  55. # the same on both tags of a spool and equal to the AMS's tray_uuid (#984).
  56. BAMBU_BLOCKS = [1, 2, 4, 5, 9]
  57. # ISO 14443-3 anticollision: SEL codes of cascade levels 1-3, the cascade tag
  58. # that opens a level's four bytes when the UID goes on at the next level, and
  59. # the SAK bit that says it does. A 4-byte UID ends at level 1, a 7-byte UID
  60. # (NTAG, Ultralight) at level 2, a 10-byte UID at level 3 (#3258).
  61. CASCADE_LEVELS = (0x93, 0x95, 0x97)
  62. CASCADE_TAG = 0x88
  63. SAK_UID_INCOMPLETE = 0x04
  64. def hkdf_derive_keys(uid: bytes) -> bytes:
  65. """Derive 96 bytes of MIFARE key material (16 sectors * 6 bytes each).
  66. Uses HKDF-SHA256 with the Bambu master key as salt and the tag UID as IKM.
  67. """
  68. # HKDF-Extract: PRK = HMAC-SHA256(salt=master_key, IKM=uid)
  69. prk = hmac.new(BAMBU_MASTER_KEY, uid, hashlib.sha256).digest()
  70. # HKDF-Expand: generate 96 bytes using context "RFID-A\0"
  71. okm = b""
  72. t = b""
  73. counter = 1
  74. while len(okm) < 96:
  75. t = hmac.new(prk, t + BAMBU_CONTEXT + bytes([counter]), hashlib.sha256).digest()
  76. okm += t
  77. counter += 1
  78. return okm[:96]
  79. def get_sector_key(keys: bytes, block: int) -> bytes:
  80. """Get the 6-byte key for the sector containing the given block."""
  81. sector = block // 4
  82. return keys[sector * 6 : sector * 6 + 6]
  83. def _find_gpio_chip():
  84. for path in ["/dev/gpiochip4", "/dev/gpiochip0"]:
  85. try:
  86. chip = gpiod.Chip(path)
  87. if "pinctrl" in chip.get_info().label:
  88. return chip
  89. chip.close()
  90. except (FileNotFoundError, PermissionError, OSError):
  91. continue
  92. raise RuntimeError("No GPIO chip")
  93. class PN5180:
  94. def __init__(self):
  95. self._chip = _find_gpio_chip()
  96. self._lines = self._chip.request_lines(
  97. consumer="pn5180",
  98. config={
  99. BUSY_PIN: gpiod.LineSettings(direction=gpiod.line.Direction.INPUT),
  100. RST_PIN: gpiod.LineSettings(
  101. direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
  102. ),
  103. NSS_PIN: gpiod.LineSettings(
  104. direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
  105. ),
  106. },
  107. )
  108. self._spi = spidev.SpiDev()
  109. self._spi.open(SPI_BUS, SPI_DEVICE)
  110. self._spi.max_speed_hz = SPI_SPEED_HZ
  111. self._spi.mode = 0b00
  112. # #1424: Pi 5's RP1 spi-rp1 driver rejects SPI_NO_CS, which used to
  113. # work on Pi 4. Harmless either way on this hardware — NSS is wired
  114. # to GPIO23 (manual CS in _cs_low/_cs_high), so the kernel's CE0
  115. # toggling has no electrical effect on the reader.
  116. try:
  117. self._spi.no_cs = True
  118. except OSError as e:
  119. logger.debug("spidev.no_cs not supported (likely Pi 5 RP1 driver): %s", e)
  120. def close(self):
  121. self._spi.close()
  122. self._lines.release()
  123. self._chip.close()
  124. def _cs_low(self):
  125. self._lines.set_value(NSS_PIN, gpiod.line.Value.INACTIVE)
  126. time.sleep(0.000005) # 5us setup
  127. def _cs_high(self):
  128. self._lines.set_value(NSS_PIN, gpiod.line.Value.ACTIVE)
  129. time.sleep(0.000100) # 100us post-CS delay
  130. def _wait_busy(self, timeout_s=1.0):
  131. """Wait for BUSY to go HIGH (processing) then LOW (done) — matches Pico firmware."""
  132. deadline = time.monotonic() + min(timeout_s, 0.010)
  133. # Wait for BUSY HIGH (PN5180 started processing)
  134. while self._lines.get_value(BUSY_PIN) != gpiod.line.Value.ACTIVE:
  135. if time.monotonic() > deadline:
  136. break # Timeout waiting for HIGH — command may have processed already
  137. time.sleep(0.00001)
  138. # Wait for BUSY LOW (PN5180 done)
  139. deadline = time.monotonic() + timeout_s
  140. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  141. if time.monotonic() > deadline:
  142. raise TimeoutError("BUSY timeout")
  143. time.sleep(0.0001)
  144. def _cmd(self, data):
  145. self._cs_low()
  146. self._spi.xfer2(list(data))
  147. self._cs_high()
  148. self._wait_busy()
  149. def _read_response(self, n):
  150. self._cs_low()
  151. result = self._spi.xfer2([0xFF] * n)
  152. self._cs_high()
  153. return result
  154. # -- Register ops --
  155. def write_reg(self, reg, val):
  156. self._cmd([0x00, reg, val & 0xFF, (val >> 8) & 0xFF, (val >> 16) & 0xFF, (val >> 24) & 0xFF])
  157. def write_reg_or(self, reg, mask):
  158. self._cmd([0x01, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  159. def write_reg_and(self, reg, mask):
  160. self._cmd([0x02, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  161. def read_reg(self, reg):
  162. self._cmd([0x04, reg])
  163. time.sleep(0.000100) # Extra 100us before read
  164. return int.from_bytes(self._read_response(4), "little")
  165. def read_eeprom(self, addr, length):
  166. self._cmd([0x07, addr, length])
  167. time.sleep(0.000100)
  168. return bytes(self._read_response(length))
  169. # -- Commands --
  170. def reset(self):
  171. self._lines.set_value(RST_PIN, gpiod.line.Value.INACTIVE)
  172. time.sleep(0.050)
  173. self._lines.set_value(RST_PIN, gpiod.line.Value.ACTIVE)
  174. time.sleep(0.100)
  175. self._wait_busy(2.0)
  176. time.sleep(0.050)
  177. def load_rf_config(self, tx, rx):
  178. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs first
  179. time.sleep(0.000100)
  180. self._cmd([0x11, tx, rx])
  181. time.sleep(0.010)
  182. def rf_on(self):
  183. self._cmd([0x16, 0x00])
  184. time.sleep(0.010)
  185. def rf_off(self):
  186. self._cmd([0x17, 0x00])
  187. time.sleep(0.005)
  188. def set_pin(self, pin: int, value: bool) -> None:
  189. """Set the state of a control pin (NSS or RST). Value: True=ACTIVE, False=INACTIVE."""
  190. if pin not in (NSS_PIN, RST_PIN):
  191. raise ValueError("Only NSS_PIN and RST_PIN can be set via set_pin().")
  192. self._lines.set_value(pin, gpiod.line.Value.ACTIVE if value else gpiod.line.Value.INACTIVE)
  193. def get_pin(self, pin: int) -> bool:
  194. """Get the state of a control pin (NSS or RST). Returns True if ACTIVE, False if INACTIVE."""
  195. if pin not in (NSS_PIN, RST_PIN):
  196. raise ValueError("Only NSS_PIN and RST_PIN can be read via get_pin().")
  197. return self._lines.get_value(pin) == gpiod.line.Value.ACTIVE
  198. def set_transceive_mode(self):
  199. """Set SYSTEM_CONFIG command bits to TRANSCEIVE (0x03) — CRITICAL!"""
  200. sys_cfg = self.read_reg(0x00)
  201. sys_cfg = (sys_cfg & 0xFFFFFFF8) | 0x03
  202. self.write_reg(0x00, sys_cfg)
  203. def send_data(self, data, valid_bits=0x00):
  204. self._cs_low()
  205. self._spi.xfer2([0x09, valid_bits] + list(data))
  206. self._cs_high()
  207. time.sleep(0.000100)
  208. self._wait_busy()
  209. def read_data(self, length):
  210. self._cmd([0x0A, 0x00])
  211. return bytes(self._read_response(length))
  212. # -- ISO 14443A --
  213. def activate_type_a(self):
  214. """Full Type A activation: WUPA -> Anticollision -> SELECT, for each cascade level.
  215. Returns (uid, sak) with the complete 4-, 7- or 10-byte UID, cascade tags
  216. dropped, and the SAK of the last SELECT; or None.
  217. """
  218. # Crypto off, CRC off
  219. self.write_reg_and(0x00, 0xFFFFFFBF)
  220. self.write_reg_and(0x12, 0xFFFFFFFE)
  221. self.write_reg_and(0x19, 0xFFFFFFFE)
  222. self.write_reg(0x03, 0xFFFFFFFF)
  223. # Reset to IDLE then TRANSCEIVE
  224. sys_cfg = self.read_reg(0x00)
  225. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  226. time.sleep(0.001)
  227. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  228. time.sleep(0.002)
  229. # WUPA (7-bit)
  230. self.send_data([0x52], valid_bits=0x07)
  231. time.sleep(0.005)
  232. rx_status = self.read_reg(0x13)
  233. rx_len = rx_status & 0x1FF
  234. if rx_len < 2 or rx_len == 511:
  235. # Try REQA
  236. self.write_reg(0x03, 0xFFFFFFFF)
  237. time.sleep(0.002)
  238. self.set_transceive_mode()
  239. time.sleep(0.002)
  240. self.send_data([0x26], valid_bits=0x07)
  241. time.sleep(0.005)
  242. rx_status = self.read_reg(0x13)
  243. rx_len = rx_status & 0x1FF
  244. if rx_len < 2 or rx_len == 511:
  245. return None
  246. atqa = self.read_data(2)
  247. if atqa[0] == 0xFF or atqa[0] == 0x00:
  248. return None
  249. uid = b""
  250. for level, sel in enumerate(CASCADE_LEVELS):
  251. if level > 0:
  252. # The previous SELECT turned CRC on; anticollision frames carry none
  253. self.write_reg_and(0x12, 0xFFFFFFFE)
  254. self.write_reg_and(0x19, 0xFFFFFFFE)
  255. # Anti-collision
  256. self.write_reg(0x03, 0xFFFFFFFF)
  257. self.set_transceive_mode()
  258. time.sleep(0.002)
  259. self.send_data([sel, 0x20])
  260. time.sleep(0.010)
  261. rx_status = self.read_reg(0x13)
  262. rx_len = rx_status & 0x1FF
  263. if rx_len < 5 or rx_len > 64:
  264. return None
  265. uid_buf = self.read_data(5)
  266. part = uid_buf[:4]
  267. bcc = part[0] ^ part[1] ^ part[2] ^ part[3]
  268. if bcc != uid_buf[4]:
  269. return None
  270. # SELECT
  271. self.write_reg(0x03, 0xFFFFFFFF)
  272. self.set_transceive_mode()
  273. time.sleep(0.002)
  274. # Enable CRC for SELECT
  275. self.write_reg_or(0x19, 0x01)
  276. self.write_reg_or(0x12, 0x01)
  277. self.send_data([sel, 0x70, part[0], part[1], part[2], part[3], bcc])
  278. time.sleep(0.010)
  279. rx_status = self.read_reg(0x13)
  280. rx_len = rx_status & 0x1FF
  281. if rx_len < 1:
  282. return None
  283. sak_buf = self.read_data(min(rx_len, 3))
  284. sak = sak_buf[0]
  285. if not sak & SAK_UID_INCOMPLETE:
  286. return bytes(uid + part), sak
  287. # UID goes on at the next level: these four bytes are the cascade
  288. # tag and the next three bytes of the UID
  289. if part[0] != CASCADE_TAG:
  290. logger.debug("SAK 0x%02X at cascade level %d without cascade tag: %s", sak, level + 1, part.hex())
  291. return None
  292. uid += part[1:]
  293. logger.debug("UID still incomplete after cascade level 3: %s", uid.hex())
  294. return None
  295. # -- MIFARE Classic --
  296. def mfc_authenticate(self, block: int, key: bytes, uid: bytes) -> bool:
  297. """MIFARE Classic authentication via PN5180 MFC_AUTHENTICATE (0x0C).
  298. The PN5180 handles Crypto1 internally. After success, bit 6 of
  299. SYSTEM_CONFIG is set (MFC_CRYPTO1_ON) and all subsequent RF
  300. communication is encrypted/decrypted by the hardware.
  301. Args:
  302. block: Block number to authenticate
  303. key: 6-byte MIFARE Key A
  304. uid: 4-byte tag UID
  305. Returns:
  306. True if authentication succeeded
  307. """
  308. # Wait for BUSY LOW before starting
  309. deadline = time.monotonic() + 0.100
  310. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  311. if time.monotonic() > deadline:
  312. return False
  313. time.sleep(0.001)
  314. # MFC_AUTHENTICATE: [0x0C][key 6B][keyType][blockNo][uid 4B] = 13 bytes
  315. cmd = [0x0C] + list(key) + [0x60, block] + list(uid[:4])
  316. self._cs_low()
  317. self._spi.xfer2(cmd)
  318. self._cs_high()
  319. # Wait for BUSY HIGH then LOW (auth can take up to 1s)
  320. self._wait_busy(timeout_s=1.0)
  321. # Read 1-byte response: 0x00 = success
  322. self._cs_low()
  323. response = self._spi.xfer2([0xFF])
  324. self._cs_high()
  325. return response[0] == 0x00
  326. def mfc_read_block(self, block: int) -> bytes | None:
  327. """Read a 16-byte MIFARE Classic block (must be authenticated first).
  328. Returns 16 bytes of block data, or None on failure.
  329. """
  330. # Clear IRQs
  331. self.write_reg(0x03, 0xFFFFFFFF)
  332. # Set transceive mode (Crypto1 stays active from MFC_AUTHENTICATE)
  333. self.set_transceive_mode()
  334. time.sleep(0.001)
  335. # Enable TX and RX CRC for encrypted read
  336. self.write_reg_or(0x19, 0x01)
  337. self.write_reg_or(0x12, 0x01)
  338. # Send MIFARE READ command: 0x30 + block number
  339. self.send_data([0x30, block])
  340. time.sleep(0.010)
  341. # Check RX status
  342. rx_status = self.read_reg(0x13)
  343. rx_len = rx_status & 0x1FF
  344. if rx_len != 16:
  345. return None
  346. return self.read_data(16)
  347. def ntag_read_pages(self, start_page: int, num_pages: int) -> bytes | None:
  348. """Read NTAG pages (4 bytes each). No authentication required.
  349. Uses NTAG READ command (0x30) which returns 4 pages (16 bytes) at a time.
  350. """
  351. # One-time setup: Crypto1 off, TX CRC on, RX CRC off, IDLE→TRANSCEIVE
  352. self.write_reg_and(0x00, 0xFFFFFFBF) # Crypto1 off
  353. self.write_reg_or(0x19, 0x01) # TX CRC on
  354. self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
  355. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  356. sys_cfg = self.read_reg(0x00)
  357. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  358. time.sleep(0.001)
  359. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  360. time.sleep(0.002)
  361. result = bytearray()
  362. pages_read = 0
  363. while pages_read < num_pages:
  364. if pages_read > 0:
  365. # Subsequent iterations: just clear IRQs and re-enter TRANSCEIVE
  366. self.write_reg(0x03, 0xFFFFFFFF)
  367. self.set_transceive_mode()
  368. time.sleep(0.001)
  369. # READ command: 0x30 + page number -> returns 16 bytes (4 pages)
  370. self.send_data([0x30, start_page + pages_read])
  371. time.sleep(0.010)
  372. rx_status = self.read_reg(0x13)
  373. rx_len = rx_status & 0x1FF
  374. if rx_len < 16:
  375. logger.warning(
  376. "NTAG read page %d: rx_len=%d (expected >=16), rx_status=0x%08X",
  377. start_page + pages_read,
  378. rx_len,
  379. rx_status,
  380. )
  381. return None
  382. data = self.read_data(16)
  383. pages_to_copy = min(4, num_pages - pages_read)
  384. result.extend(data[: pages_to_copy * 4])
  385. pages_read += 4
  386. return bytes(result)
  387. def reactivate_card(self) -> tuple[bytes, int] | None:
  388. """RF cycle and full re-select of the card. Returns (uid, sak) or None."""
  389. self.rf_off()
  390. time.sleep(0.010)
  391. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  392. self.load_rf_config(0x00, 0x80) # ISO 14443A
  393. time.sleep(0.005)
  394. self.rf_on()
  395. time.sleep(0.020)
  396. return self.activate_type_a()
  397. def read_bambu_tag(self, uid: bytes) -> dict[int, bytes] | None:
  398. """Read Bambu tag data blocks using HKDF-derived keys.
  399. Args:
  400. uid: 4-byte tag UID (from activate_type_a)
  401. Returns:
  402. Dict mapping block number -> 16 bytes of data, or None on failure
  403. """
  404. # Derive per-sector keys from UID
  405. keys = hkdf_derive_keys(uid)
  406. # Clear Crypto1 state and IRQs
  407. self.write_reg_and(0x00, 0xFFFFFFBF) # Clear MFC_CRYPTO1_ON (bit 6)
  408. self.write_reg(0x03, 0xFFFFFFFF)
  409. # Reactivate card (may have timed out)
  410. result = self.reactivate_card()
  411. if result is None:
  412. logger.debug("Failed to reactivate card for Bambu tag read")
  413. return None
  414. uid_check, _ = result
  415. if uid_check != uid:
  416. logger.debug("UID mismatch after reactivation: %s != %s", uid_check.hex(), uid.hex())
  417. return None
  418. # Read blocks with per-sector authentication
  419. blocks = {}
  420. current_sector = -1
  421. for block in BAMBU_BLOCKS:
  422. sector = block // 4
  423. # Authenticate when entering a new sector
  424. if sector != current_sector:
  425. key = get_sector_key(keys, block)
  426. if not self.mfc_authenticate(block, key, uid):
  427. logger.debug("Auth failed for block %d (sector %d)", block, sector)
  428. return None
  429. current_sector = sector
  430. # Read the block
  431. data = self.mfc_read_block(block)
  432. if data is None:
  433. logger.debug("Read failed for block %d", block)
  434. return None
  435. blocks[block] = data
  436. return blocks
  437. def ntag_write_page(self, page: int, data: bytes) -> bool:
  438. """Write 4 bytes to a single NTAG page.
  439. NTAG WRITE command: 0xA2 + page_number + 4 bytes data.
  440. TX CRC on (tag requires it). Always returns True — the 4-bit ACK
  441. cannot be captured by the PN5180, so verification is deferred to
  442. ntag_write_pages() which reads back all written data.
  443. """
  444. if len(data) != 4:
  445. return False
  446. # Crypto1 off, TX CRC on (tag expects CRC), RX CRC off (ACK is 4-bit, no CRC)
  447. self.write_reg_and(0x00, 0xFFFFFFBF) # Crypto1 off
  448. self.write_reg_or(0x19, 0x01) # TX CRC on
  449. self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
  450. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  451. # Reset state machine: IDLE then TRANSCEIVE
  452. sys_cfg = self.read_reg(0x00)
  453. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  454. time.sleep(0.001)
  455. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  456. time.sleep(0.002)
  457. # WRITE command: 0xA2 + page + 4 bytes
  458. self.send_data([0xA2, page] + list(data))
  459. time.sleep(0.010)
  460. # The NTAG ACK is only 4 bits (0x0A). The PN5180 detects SOF but
  461. # cannot capture sub-byte frames — RX_IRQ never fires. Skip ACK
  462. # checking; the tag's SOF response confirms it received the command.
  463. return True
  464. def ntag_write_pages(self, start_page: int, data: bytes) -> bool:
  465. """Write data to consecutive NTAG pages starting at start_page.
  466. Pads last chunk to 4 bytes. Verification is skipped — the PN5180
  467. cannot reliably read back NTAG pages after a batch write (the
  468. second READ command gets no response). The write itself is reliable:
  469. the tag ACKs each page (RX SOF detected on every response).
  470. """
  471. # Pad to 4-byte boundary
  472. padded = bytearray(data)
  473. while len(padded) % 4 != 0:
  474. padded.append(0x00)
  475. # Write page by page
  476. num_pages = len(padded) // 4
  477. for i in range(0, len(padded), 4):
  478. page = start_page + (i // 4)
  479. chunk = bytes(padded[i : i + 4])
  480. if not self.ntag_write_page(page, chunk):
  481. logger.warning("NTAG write failed at page %d (of %d pages)", page, num_pages)
  482. return False
  483. time.sleep(0.002)
  484. logger.info("NTAG write complete (%d pages)", num_pages)
  485. return True
  486. def read_ntag(self, uid: bytes) -> bytes | None:
  487. """Read NTAG pages 4-20 (NDEF data area, 68 bytes). No auth needed.
  488. Used for SpoolEase / OpenPrintTag community tags.
  489. """
  490. # Reactivate card
  491. result = self.reactivate_card()
  492. if result is None:
  493. logger.debug("Failed to reactivate card for NTAG read")
  494. return None
  495. return self.ntag_read_pages(start_page=4, num_pages=17)