nfc_reader.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. class NFCState(Enum):
  8. IDLE = auto()
  9. TAG_PRESENT = auto()
  10. class NFCReader:
  11. def __init__(self):
  12. from read_tag import PN5180
  13. self._nfc = PN5180()
  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. try:
  20. self._nfc.reset()
  21. self._nfc.load_rf_config(0x00, 0x80)
  22. time.sleep(0.010)
  23. self._nfc.rf_on()
  24. time.sleep(0.030)
  25. self._nfc.set_transceive_mode()
  26. self._ok = True
  27. logger.info("NFC reader initialized")
  28. except Exception as e:
  29. logger.error("NFC reader init failed: %s", e)
  30. @property
  31. def ok(self) -> bool:
  32. return self._ok
  33. @property
  34. def state(self) -> NFCState:
  35. return self._state
  36. @property
  37. def current_uid(self) -> str | None:
  38. return self._current_uid
  39. def close(self):
  40. try:
  41. self._nfc.rf_off()
  42. self._nfc.close()
  43. except Exception:
  44. pass
  45. def poll(self) -> tuple[str, dict | None]:
  46. """Poll for tag. Returns (event_type, event_data).
  47. event_type: "none", "tag_detected", "tag_removed"
  48. """
  49. try:
  50. result = self._nfc.activate_type_a()
  51. except Exception as e:
  52. logger.debug("NFC poll error: %s", e)
  53. self._ok = False
  54. return "none", None
  55. self._ok = True
  56. if result is not None:
  57. uid_bytes, sak = result
  58. uid_hex = uid_bytes.hex().upper()
  59. self._miss_count = 0
  60. if self._state == NFCState.IDLE:
  61. self._state = NFCState.TAG_PRESENT
  62. self._current_uid = uid_hex
  63. self._current_sak = sak
  64. # Try reading Bambu tag data
  65. tray_uuid = None
  66. tag_type = "mifare_classic" if sak in (0x08, 0x18) else "ntag" if sak == 0x00 else "unknown"
  67. if sak in (0x08, 0x18):
  68. blocks = self._nfc.read_bambu_tag(uid_bytes)
  69. if blocks:
  70. tray_uuid = _extract_tray_uuid(blocks)
  71. logger.info("Tag detected: %s (SAK=0x%02X)", uid_hex, sak)
  72. return "tag_detected", {
  73. "tag_uid": uid_hex,
  74. "sak": sak,
  75. "tag_type": tag_type,
  76. "tray_uuid": tray_uuid,
  77. }
  78. # Tag still present — no event
  79. return "none", None
  80. # No tag found
  81. if self._state == NFCState.TAG_PRESENT:
  82. self._miss_count += 1
  83. if self._miss_count >= MISS_THRESHOLD:
  84. old_uid = self._current_uid
  85. self._state = NFCState.IDLE
  86. self._current_uid = None
  87. self._current_sak = None
  88. self._miss_count = 0
  89. logger.info("Tag removed: %s", old_uid)
  90. return "tag_removed", {"tag_uid": old_uid}
  91. return "none", None
  92. def _extract_tray_uuid(blocks: dict[int, bytes]) -> str | None:
  93. """Extract tray_uuid from Bambu MIFARE Classic data blocks."""
  94. # Block 4-5 contain the 32-char tray UUID (first 16 bytes from block 4 + 5)
  95. if 4 in blocks and 5 in blocks:
  96. raw = blocks[4] + blocks[5]
  97. # UUID is stored as ASCII hex in the first 16 bytes of blocks 4-5
  98. uuid_bytes = raw[:16]
  99. try:
  100. uuid_str = uuid_bytes.hex().upper()
  101. if uuid_str and uuid_str != "0" * 32:
  102. return uuid_str
  103. except Exception:
  104. pass
  105. return None