nfc_reader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """NFC reader wrapper with state machine for tag presence detection."""
  2. import logging
  3. import time
  4. from enum import Enum, auto
  5. logger = logging.getLogger(__name__)
  6. MISS_THRESHOLD = 3 # Consecutive misses before declaring tag removed
  7. ERROR_RECOVERY_THRESHOLD = 10 # Consecutive errors before attempting RF reset
  8. class NFCState(Enum):
  9. IDLE = auto()
  10. TAG_PRESENT = auto()
  11. class NFCReader:
  12. def __init__(self):
  13. self._nfc = None
  14. self._state = NFCState.IDLE
  15. self._current_uid: str | None = None
  16. self._current_sak: int | None = None
  17. self._miss_count = 0
  18. self._ok = False
  19. self._error_count = 0
  20. self._poll_count = 0
  21. self._last_status_log = 0.0
  22. try:
  23. from .pn5180 import PN5180
  24. self._nfc = PN5180()
  25. self._init_rf()
  26. self._ok = True
  27. logger.info("NFC reader initialized")
  28. except Exception as e:
  29. logger.warning("NFC not available: %s", e)
  30. def _init_rf(self):
  31. """Full RF initialization sequence."""
  32. self._nfc.reset()
  33. self._nfc.load_rf_config(0x00, 0x80)
  34. time.sleep(0.010)
  35. self._nfc.rf_on()
  36. time.sleep(0.030)
  37. self._nfc.set_transceive_mode()
  38. def _full_reset(self):
  39. """Full hardware reset + RF init to recover from stuck state."""
  40. try:
  41. self._init_rf()
  42. self._error_count = 0
  43. logger.info("NFC reader recovered after full reset")
  44. return True
  45. except Exception as e:
  46. logger.warning("NFC full reset failed: %s", e)
  47. return False
  48. @property
  49. def reader_type(self) -> str:
  50. """Return NFC reader hardware type."""
  51. return "PN5180" if self._nfc is not None else "Unknown"
  52. @property
  53. def connection(self) -> str:
  54. """Return NFC reader connection type."""
  55. return "SPI" if self._nfc is not None else "None"
  56. @property
  57. def ok(self) -> bool:
  58. return self._ok
  59. @property
  60. def state(self) -> NFCState:
  61. return self._state
  62. @property
  63. def current_uid(self) -> str | None:
  64. return self._current_uid
  65. def close(self):
  66. try:
  67. self._nfc.rf_off()
  68. self._nfc.close()
  69. except Exception:
  70. pass
  71. @property
  72. def current_sak(self) -> int | None:
  73. return self._current_sak
  74. def write_ntag(self, data: bytes, data_v2: bytes | None = None) -> tuple[bool, str]:
  75. """Write raw NDEF bytes to currently present NTAG tag.
  76. *data* is OpenTag3D v1, which fits every NTAG. *data_v2* (OpenTag3D
  77. 2.004, #3500) is written instead when the tag's Capability Container
  78. says it has room for it; v2 does not fit an NTAG213.
  79. Requires tag in TAG_PRESENT state with SAK=0x00.
  80. Returns (success, message).
  81. """
  82. if self._state != NFCState.TAG_PRESENT:
  83. return False, "No tag present"
  84. if self._current_sak not in (0x00, 0x04):
  85. return False, f"Not an NTAG (SAK=0x{self._current_sak:02X})"
  86. if not self._nfc:
  87. return False, "NFC reader not available"
  88. try:
  89. # Reactivate card before writing
  90. result = self._nfc.reactivate_card()
  91. if result is None:
  92. return False, "Failed to reactivate card for write"
  93. uid_bytes, sak = result
  94. if uid_bytes.hex().upper() != self._current_uid:
  95. return False, "Tag UID changed during write"
  96. version = "v1"
  97. if data_v2 is not None:
  98. # Page 3 is the Capability Container; READ returns pages 3-6.
  99. try:
  100. cc_pages = self._nfc.ntag_read_pages(start_page=3, num_pages=1)
  101. except Exception as e:
  102. logger.warning("Could not read the tag's Capability Container: %s", e)
  103. cc_pages = None
  104. data, version = choose_ndef(cc_pages, data, data_v2)
  105. # A fresh select before writing, as the write path always had.
  106. if self._nfc.reactivate_card() is None:
  107. return False, "Failed to reactivate card for write"
  108. # Write starting at page 4
  109. success = self._nfc.ntag_write_pages(start_page=4, data=data)
  110. if success:
  111. logger.info(
  112. "NTAG write successful: %d bytes (OpenTag3D %s) to tag %s", len(data), version, self._current_uid
  113. )
  114. return True, f"Write successful (OpenTag3D {version})"
  115. else:
  116. return False, "Write or verification failed"
  117. except Exception as e:
  118. logger.error("NTAG write error: %s", e)
  119. return False, f"Write error: {e}"
  120. def poll(self) -> tuple[str, dict | None]:
  121. """Poll for tag. Returns (event_type, event_data).
  122. event_type: "none", "tag_detected", "tag_removed"
  123. """
  124. self._poll_count += 1
  125. # Periodic status log (every 60s)
  126. now = time.monotonic()
  127. if now - self._last_status_log >= 60.0:
  128. logger.info(
  129. "NFC status: state=%s, polls=%d, errors=%d, ok=%s",
  130. self._state.name,
  131. self._poll_count,
  132. self._error_count,
  133. self._ok,
  134. )
  135. self._last_status_log = now
  136. if self._state == NFCState.IDLE:
  137. # Full hardware reset before every idle poll. Each activate_type_a()
  138. # call that returns None corrupts the PN5180 state — subsequent calls
  139. # silently fail even when a tag is present. Only a full RST pin toggle
  140. # recovers the reader. ~240ms overhead per poll, giving ~1.8 Hz poll
  141. # rate which is fine for a spool tag reader.
  142. try:
  143. self._init_rf()
  144. except Exception as e:
  145. logger.warning("NFC pre-poll reset failed: %s", e)
  146. else:
  147. # Tag present: light RF cycle to reset card from ACTIVE back to IDLE
  148. # state after previous SELECT, so it responds to the next WUPA/REQA.
  149. try:
  150. self._nfc.rf_off()
  151. time.sleep(0.003)
  152. self._nfc.rf_on()
  153. time.sleep(0.010)
  154. except Exception:
  155. pass # Will be caught by activate_type_a() error handling below
  156. try:
  157. result = self._nfc.activate_type_a()
  158. except Exception as e:
  159. self._error_count += 1
  160. self._ok = False
  161. if self._error_count == 1:
  162. logger.warning("NFC poll error: %s", e)
  163. elif self._error_count == ERROR_RECOVERY_THRESHOLD:
  164. logger.warning(
  165. "NFC reader stuck (%d consecutive errors), attempting recovery...",
  166. self._error_count,
  167. )
  168. if self._full_reset():
  169. return "none", None
  170. # Reset failed — will keep trying on next threshold
  171. self._error_count = 0
  172. elif self._error_count % ERROR_RECOVERY_THRESHOLD == 0:
  173. logger.warning("NFC recovery attempt #%d", self._error_count // ERROR_RECOVERY_THRESHOLD)
  174. self._full_reset()
  175. return "none", None
  176. # Successful poll — clear error streak
  177. if self._error_count > 0:
  178. logger.info("NFC reader recovered after %d errors", self._error_count)
  179. self._error_count = 0
  180. self._ok = True
  181. if result is not None:
  182. uid_bytes, sak = result
  183. uid_hex = uid_bytes.hex().upper()
  184. self._miss_count = 0
  185. if self._state == NFCState.IDLE:
  186. self._state = NFCState.TAG_PRESENT
  187. self._current_uid = uid_hex
  188. self._current_sak = sak
  189. # Try reading Bambu tag data
  190. tray_uuid = None
  191. raw_blocks = None
  192. tag_type = "mifare_classic" if sak in (0x08, 0x18) else "ntag" if sak in (0x00, 0x04) else "unknown"
  193. if sak in (0x08, 0x18):
  194. # A reader fault mid-read (a BUSY timeout, an SPI error) must
  195. # not escape poll() and stop the loop: report the tag without
  196. # its tray UUID, so matching falls back to the UID (#3377)
  197. try:
  198. blocks = self._nfc.read_bambu_tag(uid_bytes)
  199. except Exception as e:
  200. logger.warning("Bambu tag read failed for %s: %s", uid_hex, e)
  201. blocks = None
  202. if blocks:
  203. tray_uuid = _extract_tray_uuid(blocks)
  204. raw_blocks = _raw_blocks(blocks)
  205. logger.info("Tag detected: %s (SAK=0x%02X, type=%s)", uid_hex, sak, tag_type)
  206. return "tag_detected", {
  207. "tag_uid": uid_hex,
  208. "sak": sak,
  209. "tag_type": tag_type,
  210. "tray_uuid": tray_uuid,
  211. "raw_blocks": raw_blocks,
  212. }
  213. # Tag still present — no event
  214. return "none", None
  215. # No tag found
  216. if self._state == NFCState.TAG_PRESENT:
  217. self._miss_count += 1
  218. if self._miss_count >= MISS_THRESHOLD:
  219. old_uid = self._current_uid
  220. self._state = NFCState.IDLE
  221. self._current_uid = None
  222. self._current_sak = None
  223. self._miss_count = 0
  224. logger.info("Tag removed: %s", old_uid)
  225. return "tag_removed", {"tag_uid": old_uid}
  226. return "none", None
  227. def _extract_tray_uuid(blocks: dict[int, bytes]) -> str | None:
  228. """Extract tray_uuid from Bambu MIFARE Classic data blocks.
  229. The tray UUID is the 16 raw bytes of block 9, as 32 uppercase hex chars.
  230. Both tags of a spool carry the same value, and it is what the AMS reports
  231. as tray_uuid. Blocks 4-5 hold the filament type ("PLA Matte"), not the UUID:
  232. reading them made every spool of one type share an id (#984).
  233. """
  234. data = blocks.get(9)
  235. if not data or len(data) < 16:
  236. return None
  237. uuid_str = data[:16].hex().upper()
  238. if uuid_str == "0" * 32:
  239. return None
  240. return uuid_str
  241. def choose_ndef(cc_pages: bytes | None, data_v1: bytes, data_v2: bytes) -> tuple[bytes, str]:
  242. """Pick the OpenTag3D encoding the tag has room for (#3500).
  243. *cc_pages* starts with page 3, the NDEF Capability Container
  244. (E1, version, data area size / 8, access). v2 is chosen only when the CC
  245. reads as NDEF and its data area holds the whole v2 message: an NTAG213
  246. (size byte 0x12, 144 bytes) gets v1, an NTAG215/216 (0x3E/0x6D) gets v2.
  247. Anything unreadable gets v1, which fits every NTAG.
  248. """
  249. if cc_pages and len(cc_pages) >= 4 and cc_pages[0] == 0xE1 and len(data_v2) <= cc_pages[2] * 8:
  250. return data_v2, "v2"
  251. return data_v1, "v1"
  252. def _raw_blocks(blocks: dict[int, bytes]) -> dict[str, str]:
  253. """Bambu tag blocks as {"block number": "32 uppercase hex chars"}, for the backend to decode (#2685)."""
  254. return {str(block): data.hex().upper() for block, data in sorted(blocks.items())}