pn5180.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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
  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. self._spi.no_cs = True
  105. def close(self):
  106. self._spi.close()
  107. self._lines.release()
  108. self._chip.close()
  109. def _cs_low(self):
  110. self._lines.set_value(NSS_PIN, gpiod.line.Value.INACTIVE)
  111. time.sleep(0.000005) # 5us setup
  112. def _cs_high(self):
  113. self._lines.set_value(NSS_PIN, gpiod.line.Value.ACTIVE)
  114. time.sleep(0.000100) # 100us post-CS delay
  115. def _wait_busy(self, timeout_s=1.0):
  116. """Wait for BUSY to go HIGH (processing) then LOW (done) — matches Pico firmware."""
  117. deadline = time.monotonic() + min(timeout_s, 0.010)
  118. # Wait for BUSY HIGH (PN5180 started processing)
  119. while self._lines.get_value(BUSY_PIN) != gpiod.line.Value.ACTIVE:
  120. if time.monotonic() > deadline:
  121. break # Timeout waiting for HIGH — command may have processed already
  122. time.sleep(0.00001)
  123. # Wait for BUSY LOW (PN5180 done)
  124. deadline = time.monotonic() + timeout_s
  125. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  126. if time.monotonic() > deadline:
  127. raise TimeoutError("BUSY timeout")
  128. time.sleep(0.0001)
  129. def _cmd(self, data):
  130. self._cs_low()
  131. self._spi.xfer2(list(data))
  132. self._cs_high()
  133. self._wait_busy()
  134. def _read_response(self, n):
  135. self._cs_low()
  136. result = self._spi.xfer2([0xFF] * n)
  137. self._cs_high()
  138. return result
  139. # -- Register ops --
  140. def write_reg(self, reg, val):
  141. self._cmd([0x00, reg, val & 0xFF, (val >> 8) & 0xFF, (val >> 16) & 0xFF, (val >> 24) & 0xFF])
  142. def write_reg_or(self, reg, mask):
  143. self._cmd([0x01, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  144. def write_reg_and(self, reg, mask):
  145. self._cmd([0x02, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
  146. def read_reg(self, reg):
  147. self._cmd([0x04, reg])
  148. time.sleep(0.000100) # Extra 100us before read
  149. return int.from_bytes(self._read_response(4), "little")
  150. def read_eeprom(self, addr, length):
  151. self._cmd([0x07, addr, length])
  152. time.sleep(0.000100)
  153. return bytes(self._read_response(length))
  154. # -- Commands --
  155. def reset(self):
  156. self._lines.set_value(RST_PIN, gpiod.line.Value.INACTIVE)
  157. time.sleep(0.050)
  158. self._lines.set_value(RST_PIN, gpiod.line.Value.ACTIVE)
  159. time.sleep(0.100)
  160. self._wait_busy(2.0)
  161. time.sleep(0.050)
  162. def load_rf_config(self, tx, rx):
  163. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs first
  164. time.sleep(0.000100)
  165. self._cmd([0x11, tx, rx])
  166. time.sleep(0.010)
  167. def rf_on(self):
  168. self._cmd([0x16, 0x00])
  169. time.sleep(0.010)
  170. def rf_off(self):
  171. self._cmd([0x17, 0x00])
  172. time.sleep(0.005)
  173. def set_transceive_mode(self):
  174. """Set SYSTEM_CONFIG command bits to TRANSCEIVE (0x03) — CRITICAL!"""
  175. sys_cfg = self.read_reg(0x00)
  176. sys_cfg = (sys_cfg & 0xFFFFFFF8) | 0x03
  177. self.write_reg(0x00, sys_cfg)
  178. def send_data(self, data, valid_bits=0x00):
  179. self._cs_low()
  180. self._spi.xfer2([0x09, valid_bits] + list(data))
  181. self._cs_high()
  182. time.sleep(0.000100)
  183. self._wait_busy()
  184. def read_data(self, length):
  185. self._cmd([0x0A, 0x00])
  186. return bytes(self._read_response(length))
  187. # -- ISO 14443A --
  188. def activate_type_a(self):
  189. """Full Type A activation: WUPA -> Anticollision -> SELECT. Returns (uid, sak) or None."""
  190. # Crypto off, CRC off
  191. self.write_reg_and(0x00, 0xFFFFFFBF)
  192. self.write_reg_and(0x12, 0xFFFFFFFE)
  193. self.write_reg_and(0x19, 0xFFFFFFFE)
  194. self.write_reg(0x03, 0xFFFFFFFF)
  195. # Reset to IDLE then TRANSCEIVE
  196. sys_cfg = self.read_reg(0x00)
  197. self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
  198. time.sleep(0.001)
  199. self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
  200. time.sleep(0.002)
  201. # WUPA (7-bit)
  202. self.send_data([0x52], valid_bits=0x07)
  203. time.sleep(0.005)
  204. rx_status = self.read_reg(0x13)
  205. rx_len = rx_status & 0x1FF
  206. if rx_len < 2 or rx_len == 511:
  207. # Try REQA
  208. self.write_reg(0x03, 0xFFFFFFFF)
  209. time.sleep(0.002)
  210. self.set_transceive_mode()
  211. time.sleep(0.002)
  212. self.send_data([0x26], valid_bits=0x07)
  213. time.sleep(0.005)
  214. rx_status = self.read_reg(0x13)
  215. rx_len = rx_status & 0x1FF
  216. if rx_len < 2 or rx_len == 511:
  217. return None
  218. atqa = self.read_data(2)
  219. if atqa[0] == 0xFF or atqa[0] == 0x00:
  220. return None
  221. # Anti-collision Level 1
  222. self.write_reg(0x03, 0xFFFFFFFF)
  223. self.set_transceive_mode()
  224. time.sleep(0.002)
  225. self.send_data([0x93, 0x20])
  226. time.sleep(0.010)
  227. rx_status = self.read_reg(0x13)
  228. rx_len = rx_status & 0x1FF
  229. if rx_len < 5 or rx_len > 64:
  230. return None
  231. uid_buf = self.read_data(5)
  232. uid = uid_buf[:4]
  233. bcc = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]
  234. if bcc != uid_buf[4]:
  235. return None
  236. # SELECT
  237. self.write_reg(0x03, 0xFFFFFFFF)
  238. self.set_transceive_mode()
  239. time.sleep(0.002)
  240. # Enable CRC for SELECT
  241. self.write_reg_or(0x19, 0x01)
  242. self.write_reg_or(0x12, 0x01)
  243. self.send_data([0x93, 0x70, uid[0], uid[1], uid[2], uid[3], bcc])
  244. time.sleep(0.010)
  245. rx_status = self.read_reg(0x13)
  246. rx_len = rx_status & 0x1FF
  247. if rx_len < 1:
  248. return None
  249. sak_buf = self.read_data(min(rx_len, 3))
  250. sak = sak_buf[0]
  251. return bytes(uid), sak
  252. # -- MIFARE Classic --
  253. def mfc_authenticate(self, block: int, key: bytes, uid: bytes) -> bool:
  254. """MIFARE Classic authentication via PN5180 MFC_AUTHENTICATE (0x0C).
  255. The PN5180 handles Crypto1 internally. After success, bit 6 of
  256. SYSTEM_CONFIG is set (MFC_CRYPTO1_ON) and all subsequent RF
  257. communication is encrypted/decrypted by the hardware.
  258. Args:
  259. block: Block number to authenticate
  260. key: 6-byte MIFARE Key A
  261. uid: 4-byte tag UID
  262. Returns:
  263. True if authentication succeeded
  264. """
  265. # Wait for BUSY LOW before starting
  266. deadline = time.monotonic() + 0.100
  267. while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
  268. if time.monotonic() > deadline:
  269. return False
  270. time.sleep(0.001)
  271. # MFC_AUTHENTICATE: [0x0C][key 6B][keyType][blockNo][uid 4B] = 13 bytes
  272. cmd = [0x0C] + list(key) + [0x60, block] + list(uid[:4])
  273. self._cs_low()
  274. self._spi.xfer2(cmd)
  275. self._cs_high()
  276. # Wait for BUSY HIGH then LOW (auth can take up to 1s)
  277. self._wait_busy(timeout_s=1.0)
  278. # Read 1-byte response: 0x00 = success
  279. self._cs_low()
  280. response = self._spi.xfer2([0xFF])
  281. self._cs_high()
  282. return response[0] == 0x00
  283. def mfc_read_block(self, block: int) -> bytes | None:
  284. """Read a 16-byte MIFARE Classic block (must be authenticated first).
  285. Returns 16 bytes of block data, or None on failure.
  286. """
  287. # Clear IRQs
  288. self.write_reg(0x03, 0xFFFFFFFF)
  289. # Set transceive mode (Crypto1 stays active from MFC_AUTHENTICATE)
  290. self.set_transceive_mode()
  291. time.sleep(0.001)
  292. # Enable TX and RX CRC for encrypted read
  293. self.write_reg_or(0x19, 0x01)
  294. self.write_reg_or(0x12, 0x01)
  295. # Send MIFARE READ command: 0x30 + block number
  296. self.send_data([0x30, block])
  297. time.sleep(0.010)
  298. # Check RX status
  299. rx_status = self.read_reg(0x13)
  300. rx_len = rx_status & 0x1FF
  301. if rx_len != 16:
  302. return None
  303. return self.read_data(16)
  304. def ntag_read_pages(self, start_page: int, num_pages: int) -> bytes | None:
  305. """Read NTAG pages (4 bytes each). No authentication required.
  306. Uses NTAG READ command (0x30) which returns 4 pages (16 bytes) at a time.
  307. """
  308. # NTAG READ needs TX CRC on (tag expects CRC), RX CRC off (response includes raw CRC bytes we ignore)
  309. self.write_reg_or(0x19, 0x01) # TX CRC on
  310. self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
  311. result = bytearray()
  312. pages_read = 0
  313. while pages_read < num_pages:
  314. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  315. self.set_transceive_mode()
  316. time.sleep(0.001)
  317. # READ command: 0x30 + page number -> returns 16 bytes (4 pages)
  318. self.send_data([0x30, start_page + pages_read])
  319. time.sleep(0.005)
  320. rx_status = self.read_reg(0x13)
  321. rx_len = rx_status & 0x1FF
  322. if rx_len < 16:
  323. return None
  324. data = self.read_data(16)
  325. # Copy only the pages we need
  326. pages_to_copy = min(4, num_pages - pages_read)
  327. result.extend(data[: pages_to_copy * 4])
  328. pages_read += 4 # Always advances by 4 (READ returns 4 pages)
  329. return bytes(result)
  330. def reactivate_card(self) -> tuple[bytes, int] | None:
  331. """RF cycle and full re-select of the card. Returns (uid, sak) or None."""
  332. self.rf_off()
  333. time.sleep(0.010)
  334. self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
  335. self.load_rf_config(0x00, 0x80) # ISO 14443A
  336. time.sleep(0.005)
  337. self.rf_on()
  338. time.sleep(0.020)
  339. return self.activate_type_a()
  340. def read_bambu_tag(self, uid: bytes) -> dict[int, bytes] | None:
  341. """Read Bambu tag data blocks using HKDF-derived keys.
  342. Args:
  343. uid: 4-byte tag UID (from activate_type_a)
  344. Returns:
  345. Dict mapping block number -> 16 bytes of data, or None on failure
  346. """
  347. # Derive per-sector keys from UID
  348. keys = hkdf_derive_keys(uid)
  349. # Clear Crypto1 state and IRQs
  350. self.write_reg_and(0x00, 0xFFFFFFBF) # Clear MFC_CRYPTO1_ON (bit 6)
  351. self.write_reg(0x03, 0xFFFFFFFF)
  352. # Reactivate card (may have timed out)
  353. result = self.reactivate_card()
  354. if result is None:
  355. logger.debug("Failed to reactivate card for Bambu tag read")
  356. return None
  357. uid_check, _ = result
  358. if uid_check != uid:
  359. logger.debug("UID mismatch after reactivation: %s != %s", uid_check.hex(), uid.hex())
  360. return None
  361. # Read blocks with per-sector authentication
  362. blocks = {}
  363. current_sector = -1
  364. for block in BAMBU_BLOCKS:
  365. sector = block // 4
  366. # Authenticate when entering a new sector
  367. if sector != current_sector:
  368. key = get_sector_key(keys, block)
  369. if not self.mfc_authenticate(block, key, uid):
  370. logger.debug("Auth failed for block %d (sector %d)", block, sector)
  371. return None
  372. current_sector = sector
  373. # Read the block
  374. data = self.mfc_read_block(block)
  375. if data is None:
  376. logger.debug("Read failed for block %d", block)
  377. return None
  378. blocks[block] = data
  379. return blocks
  380. def ntag_write_page(self, page: int, data: bytes) -> bool:
  381. """Write 4 bytes to a single NTAG page.
  382. NTAG WRITE command: 0xA2 + page_number + 4 bytes data.
  383. TX CRC on (tag requires it), RX CRC off (ACK is 4-bit). Returns True on ACK (0x0A).
  384. """
  385. if len(data) != 4:
  386. return False
  387. # NTAG WRITE needs TX CRC on (tag expects CRC), RX CRC off (ACK is 4-bit, no CRC)
  388. self.write_reg_or(0x19, 0x01) # TX CRC on
  389. self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
  390. # Clear IRQs and set transceive mode
  391. self.write_reg(0x03, 0xFFFFFFFF)
  392. self.set_transceive_mode()
  393. time.sleep(0.001)
  394. # WRITE command: 0xA2 + page + 4 bytes
  395. self.send_data([0xA2, page] + list(data))
  396. time.sleep(0.005)
  397. # Check for ACK: NTAG ACK is 4-bit 0x0A
  398. rx_status = self.read_reg(0x13)
  399. rx_len = rx_status & 0x1FF
  400. if rx_len < 1:
  401. return False
  402. ack = self.read_data(1)
  403. return ack[0] == 0x0A
  404. def ntag_write_pages(self, start_page: int, data: bytes) -> bool:
  405. """Write data to consecutive NTAG pages starting at start_page.
  406. Pads last chunk to 4 bytes. Verifies by reading back.
  407. Returns True if write + verify succeeded.
  408. """
  409. # Pad to 4-byte boundary
  410. padded = bytearray(data)
  411. while len(padded) % 4 != 0:
  412. padded.append(0x00)
  413. # Write page by page
  414. for i in range(0, len(padded), 4):
  415. page = start_page + (i // 4)
  416. chunk = bytes(padded[i : i + 4])
  417. if not self.ntag_write_page(page, chunk):
  418. return False
  419. time.sleep(0.002)
  420. # Reactivate card for verification read
  421. result = self.reactivate_card()
  422. if result is None:
  423. return False
  424. # Read back and verify
  425. num_pages = len(padded) // 4
  426. readback = self.ntag_read_pages(start_page, num_pages)
  427. if readback is None:
  428. return False
  429. return readback[: len(data)] == data
  430. def read_ntag(self, uid: bytes) -> bytes | None:
  431. """Read NTAG pages 4-20 (NDEF data area, 68 bytes). No auth needed.
  432. Used for SpoolEase / OpenPrintTag community tags.
  433. """
  434. # Reactivate card
  435. result = self.reactivate_card()
  436. if result is None:
  437. logger.debug("Failed to reactivate card for NTAG read")
  438. return None
  439. return self.ntag_read_pages(start_page=4, num_pages=17)