read_tag.py 20 KB

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