main.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #!/usr/bin/env python3
  2. """SpoolBuddy daemon — reads NFC tags and scale, pushes events to Bambuddy backend."""
  3. import asyncio
  4. import logging
  5. import socket
  6. import sys
  7. import time
  8. from pathlib import Path
  9. # Add scripts/ to sys.path so hardware drivers (read_tag, scale_diag) are importable
  10. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
  11. from . import __version__
  12. from .api_client import APIClient
  13. from .config import Config
  14. from .display_control import DisplayControl
  15. from .nfc_reader import NFCReader, NFCState
  16. from .scale_reader import ScaleReader
  17. logging.basicConfig(
  18. level=logging.INFO,
  19. format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
  20. datefmt="%H:%M:%S",
  21. )
  22. logger = logging.getLogger("spoolbuddy")
  23. def _get_ip() -> str:
  24. try:
  25. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  26. s.connect(("8.8.8.8", 80))
  27. ip = s.getsockname()[0]
  28. s.close()
  29. return ip
  30. except Exception:
  31. return "unknown"
  32. async def nfc_poll_loop(config: Config, api: APIClient, shared: dict):
  33. """Continuous NFC polling loop — runs in asyncio with blocking reads offloaded."""
  34. nfc: NFCReader = shared["nfc"]
  35. display: DisplayControl = shared["display"]
  36. if not nfc.ok:
  37. logger.warning("NFC reader not available, skipping NFC polling")
  38. return
  39. try:
  40. while True:
  41. event_type, event_data = await asyncio.to_thread(nfc.poll)
  42. if event_type == "tag_detected":
  43. display.wake()
  44. await api.tag_scanned(
  45. device_id=config.device_id,
  46. tag_uid=event_data["tag_uid"],
  47. tray_uuid=event_data.get("tray_uuid"),
  48. sak=event_data.get("sak"),
  49. tag_type=event_data.get("tag_type"),
  50. )
  51. elif event_type == "tag_removed":
  52. await api.tag_removed(
  53. device_id=config.device_id,
  54. tag_uid=event_data["tag_uid"],
  55. )
  56. # Check for pending write command
  57. pending = shared.get("pending_write")
  58. if pending and nfc.state == NFCState.TAG_PRESENT and nfc.current_sak == 0x00:
  59. logger.info("Executing pending tag write for spool %d", pending["spool_id"])
  60. success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
  61. await api.write_tag_result(
  62. device_id=config.device_id,
  63. spool_id=pending["spool_id"],
  64. tag_uid=nfc.current_uid or "",
  65. success=success,
  66. message=msg,
  67. )
  68. shared.pop("pending_write", None)
  69. await asyncio.sleep(config.nfc_poll_interval)
  70. finally:
  71. nfc.close()
  72. async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
  73. """Continuous scale reading loop — reads at 100ms, reports at 1s intervals."""
  74. scale: ScaleReader = shared["scale"]
  75. display: DisplayControl = shared["display"]
  76. if not scale.ok:
  77. logger.warning("Scale not available, skipping scale polling")
  78. return
  79. last_report = 0.0
  80. last_reported_grams: float | None = None
  81. REPORT_THRESHOLD = 2.0 # Only report if weight changed by more than this (grams)
  82. try:
  83. while True:
  84. result = await asyncio.to_thread(scale.read)
  85. if result is not None:
  86. grams, stable, raw_adc = result
  87. now = time.monotonic()
  88. if now - last_report >= config.scale_report_interval:
  89. # Only send when weight changed meaningfully
  90. weight_changed = last_reported_grams is None or abs(grams - last_reported_grams) >= REPORT_THRESHOLD
  91. if weight_changed:
  92. display.wake()
  93. await api.scale_reading(
  94. device_id=config.device_id,
  95. weight_grams=grams,
  96. stable=stable,
  97. raw_adc=raw_adc,
  98. )
  99. last_reported_grams = grams
  100. last_report = now
  101. await asyncio.sleep(config.scale_read_interval)
  102. finally:
  103. scale.close()
  104. async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
  105. """Periodic heartbeat to keep device registered and pick up commands."""
  106. display: DisplayControl = shared["display"]
  107. ip = _get_ip()
  108. while True:
  109. await asyncio.sleep(config.heartbeat_interval)
  110. nfc = shared.get("nfc")
  111. scale = shared.get("scale")
  112. uptime = int(time.monotonic() - start_time)
  113. result = await api.heartbeat(
  114. device_id=config.device_id,
  115. nfc_ok=nfc.ok if nfc else False,
  116. scale_ok=scale.ok if scale else False,
  117. uptime_s=uptime,
  118. ip_address=ip,
  119. firmware_version=__version__,
  120. nfc_reader_type=nfc.reader_type if nfc else None,
  121. nfc_connection=nfc.connection if nfc else None,
  122. )
  123. if result:
  124. cmd = result.get("pending_command")
  125. if cmd == "tare":
  126. scale = shared.get("scale")
  127. if scale and scale.ok:
  128. new_offset = await asyncio.to_thread(scale.tare)
  129. logger.info("Tare executed: offset=%d", new_offset)
  130. await api.update_tare(config.device_id, new_offset)
  131. config.tare_offset = new_offset
  132. else:
  133. logger.warning("Tare command received but scale not available")
  134. # Skip calibration sync — this heartbeat response predates the tare
  135. continue
  136. elif cmd == "write_tag":
  137. write_payload = result.get("pending_write_payload")
  138. if write_payload:
  139. shared["pending_write"] = {
  140. "spool_id": write_payload["spool_id"],
  141. "ndef_data": bytes.fromhex(write_payload["ndef_data_hex"]),
  142. }
  143. logger.info("Write tag command received for spool %d", write_payload["spool_id"])
  144. tare = result.get("tare_offset", config.tare_offset)
  145. cal = result.get("calibration_factor", config.calibration_factor)
  146. if tare != config.tare_offset or cal != config.calibration_factor:
  147. config.tare_offset = tare
  148. config.calibration_factor = cal
  149. scale = shared.get("scale")
  150. if scale:
  151. scale.update_calibration(tare, cal)
  152. logger.info("Calibration updated from backend: tare=%d, factor=%.6f", tare, cal)
  153. # Apply display settings from backend
  154. brightness = result.get("display_brightness")
  155. blank_timeout = result.get("display_blank_timeout")
  156. if brightness is not None:
  157. display.set_brightness(brightness)
  158. if blank_timeout is not None:
  159. display.set_blank_timeout(blank_timeout)
  160. display.tick()
  161. async def main():
  162. config = Config.load()
  163. logger.info(
  164. "SpoolBuddy daemon v%s starting (device=%s, backend=%s)", __version__, config.device_id, config.backend_url
  165. )
  166. api = APIClient(config.backend_url, config.api_key)
  167. ip = _get_ip()
  168. start_time = time.monotonic()
  169. # Initialize hardware before registration so we can report capabilities
  170. nfc = NFCReader()
  171. scale = ScaleReader(
  172. tare_offset=config.tare_offset,
  173. calibration_factor=config.calibration_factor,
  174. )
  175. display = DisplayControl()
  176. # Register with backend (retries until success)
  177. reg = await api.register_device(
  178. device_id=config.device_id,
  179. hostname=config.hostname,
  180. ip_address=ip,
  181. firmware_version=__version__,
  182. has_nfc=True,
  183. has_scale=True,
  184. tare_offset=config.tare_offset,
  185. calibration_factor=config.calibration_factor,
  186. nfc_reader_type=nfc.reader_type,
  187. nfc_connection=nfc.connection,
  188. has_backlight=display.has_backlight,
  189. )
  190. # Use server-side calibration if available
  191. if reg:
  192. config.tare_offset = reg.get("tare_offset", config.tare_offset)
  193. config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
  194. scale.update_calibration(config.tare_offset, config.calibration_factor)
  195. logger.info("Device registered, starting poll loops")
  196. shared: dict = {"nfc": nfc, "scale": scale, "display": display}
  197. try:
  198. await asyncio.gather(
  199. nfc_poll_loop(config, api, shared),
  200. scale_poll_loop(config, api, shared),
  201. heartbeat_loop(config, api, start_time, shared),
  202. )
  203. except KeyboardInterrupt:
  204. logger.info("Shutting down")
  205. finally:
  206. await api.close()
  207. if __name__ == "__main__":
  208. asyncio.run(main())