pn5180.py 23 KB

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