nfc_reader.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 read_tag 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. def poll(self) -> tuple[str, dict | None]:
  72. """Poll for tag. Returns (event_type, event_data).
  73. event_type: "none", "tag_detected", "tag_removed"
  74. """
  75. self._poll_count += 1
  76. # Periodic status log (every 60s)
  77. now = time.monotonic()
  78. if now - self._last_status_log >= 60.0:
  79. logger.info(
  80. "NFC status: state=%s, polls=%d, errors=%d, ok=%s",
  81. self._state.name,
  82. self._poll_count,
  83. self._error_count,
  84. self._ok,
  85. )
  86. self._last_status_log = now
  87. if self._state == NFCState.IDLE:
  88. # Full hardware reset before every idle poll. Each activate_type_a()
  89. # call that returns None corrupts the PN5180 state — subsequent calls
  90. # silently fail even when a tag is present. Only a full RST pin toggle
  91. # recovers the reader. ~240ms overhead per poll, giving ~1.8 Hz poll
  92. # rate which is fine for a spool tag reader.
  93. try:
  94. self._init_rf()
  95. except Exception as e:
  96. logger.warning("NFC pre-poll reset failed: %s", e)
  97. else:
  98. # Tag present: light RF cycle to reset card from ACTIVE back to IDLE
  99. # state after previous SELECT, so it responds to the next WUPA/REQA.
  100. try:
  101. self._nfc.rf_off()
  102. time.sleep(0.003)
  103. self._nfc.rf_on()
  104. time.sleep(0.010)
  105. except Exception:
  106. pass # Will be caught by activate_type_a() error handling below
  107. try:
  108. result = self._nfc.activate_type_a()
  109. except Exception as e:
  110. self._error_count += 1
  111. self._ok = False
  112. if self._error_count == 1:
  113. logger.warning("NFC poll error: %s", e)
  114. elif self._error_count == ERROR_RECOVERY_THRESHOLD:
  115. logger.warning(
  116. "NFC reader stuck (%d consecutive errors), attempting recovery...",
  117. self._error_count,
  118. )
  119. if self._full_reset():
  120. return "none", None
  121. # Reset failed — will keep trying on next threshold
  122. self._error_count = 0
  123. elif self._error_count % ERROR_RECOVERY_THRESHOLD == 0:
  124. logger.warning("NFC recovery attempt #%d", self._error_count // ERROR_RECOVERY_THRESHOLD)
  125. self._full_reset()
  126. return "none", None
  127. # Successful poll — clear error streak
  128. if self._error_count > 0:
  129. logger.info("NFC reader recovered after %d errors", self._error_count)
  130. self._error_count = 0
  131. self._ok = True
  132. if result is not None:
  133. uid_bytes, sak = result
  134. uid_hex = uid_bytes.hex().upper()
  135. self._miss_count = 0
  136. if self._state == NFCState.IDLE:
  137. self._state = NFCState.TAG_PRESENT
  138. self._current_uid = uid_hex
  139. self._current_sak = sak
  140. # Try reading Bambu tag data
  141. tray_uuid = None
  142. tag_type = "mifare_classic" if sak in (0x08, 0x18) else "ntag" if sak == 0x00 else "unknown"
  143. if sak in (0x08, 0x18):
  144. blocks = self._nfc.read_bambu_tag(uid_bytes)
  145. if blocks:
  146. tray_uuid = _extract_tray_uuid(blocks)
  147. logger.info("Tag detected: %s (SAK=0x%02X, type=%s)", uid_hex, sak, tag_type)
  148. return "tag_detected", {
  149. "tag_uid": uid_hex,
  150. "sak": sak,
  151. "tag_type": tag_type,
  152. "tray_uuid": tray_uuid,
  153. }
  154. # Tag still present — no event
  155. return "none", None
  156. # No tag found
  157. if self._state == NFCState.TAG_PRESENT:
  158. self._miss_count += 1
  159. if self._miss_count >= MISS_THRESHOLD:
  160. old_uid = self._current_uid
  161. self._state = NFCState.IDLE
  162. self._current_uid = None
  163. self._current_sak = None
  164. self._miss_count = 0
  165. logger.info("Tag removed: %s", old_uid)
  166. return "tag_removed", {"tag_uid": old_uid}
  167. return "none", None
  168. def _extract_tray_uuid(blocks: dict[int, bytes]) -> str | None:
  169. """Extract tray_uuid from Bambu MIFARE Classic data blocks."""
  170. # Block 4-5 contain the 32-char tray UUID (first 16 bytes from block 4 + 5)
  171. if 4 in blocks and 5 in blocks:
  172. raw = blocks[4] + blocks[5]
  173. # UUID is stored as ASCII hex in the first 16 bytes of blocks 4-5
  174. uuid_bytes = raw[:16]
  175. try:
  176. uuid_str = uuid_bytes.hex().upper()
  177. if uuid_str and uuid_str != "0" * 32:
  178. return uuid_str
  179. except Exception:
  180. pass
  181. return None