main.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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
  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. await asyncio.sleep(config.nfc_poll_interval)
  57. finally:
  58. nfc.close()
  59. async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
  60. """Continuous scale reading loop — reads at 100ms, reports at 1s intervals."""
  61. scale: ScaleReader = shared["scale"]
  62. display: DisplayControl = shared["display"]
  63. if not scale.ok:
  64. logger.warning("Scale not available, skipping scale polling")
  65. return
  66. last_report = 0.0
  67. last_reported_grams: float | None = None
  68. REPORT_THRESHOLD = 2.0 # Only report if weight changed by more than this (grams)
  69. try:
  70. while True:
  71. result = await asyncio.to_thread(scale.read)
  72. if result is not None:
  73. grams, stable, raw_adc = result
  74. now = time.monotonic()
  75. if now - last_report >= config.scale_report_interval:
  76. # Only send when weight changed meaningfully
  77. weight_changed = last_reported_grams is None or abs(grams - last_reported_grams) >= REPORT_THRESHOLD
  78. if weight_changed:
  79. display.wake()
  80. await api.scale_reading(
  81. device_id=config.device_id,
  82. weight_grams=grams,
  83. stable=stable,
  84. raw_adc=raw_adc,
  85. )
  86. last_reported_grams = grams
  87. last_report = now
  88. await asyncio.sleep(config.scale_read_interval)
  89. finally:
  90. scale.close()
  91. async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
  92. """Periodic heartbeat to keep device registered and pick up commands."""
  93. display: DisplayControl = shared["display"]
  94. ip = _get_ip()
  95. while True:
  96. await asyncio.sleep(config.heartbeat_interval)
  97. nfc = shared.get("nfc")
  98. scale = shared.get("scale")
  99. uptime = int(time.monotonic() - start_time)
  100. result = await api.heartbeat(
  101. device_id=config.device_id,
  102. nfc_ok=nfc.ok if nfc else False,
  103. scale_ok=scale.ok if scale else False,
  104. uptime_s=uptime,
  105. ip_address=ip,
  106. firmware_version=__version__,
  107. nfc_reader_type=nfc.reader_type if nfc else None,
  108. nfc_connection=nfc.connection if nfc else None,
  109. )
  110. if result:
  111. cmd = result.get("pending_command")
  112. if cmd == "tare":
  113. scale = shared.get("scale")
  114. if scale and scale.ok:
  115. new_offset = await asyncio.to_thread(scale.tare)
  116. logger.info("Tare executed: offset=%d", new_offset)
  117. await api.update_tare(config.device_id, new_offset)
  118. config.tare_offset = new_offset
  119. else:
  120. logger.warning("Tare command received but scale not available")
  121. # Skip calibration sync — this heartbeat response predates the tare
  122. continue
  123. tare = result.get("tare_offset", config.tare_offset)
  124. cal = result.get("calibration_factor", config.calibration_factor)
  125. if tare != config.tare_offset or cal != config.calibration_factor:
  126. config.tare_offset = tare
  127. config.calibration_factor = cal
  128. scale = shared.get("scale")
  129. if scale:
  130. scale.update_calibration(tare, cal)
  131. logger.info("Calibration updated from backend: tare=%d, factor=%.6f", tare, cal)
  132. # Apply display settings from backend
  133. brightness = result.get("display_brightness")
  134. blank_timeout = result.get("display_blank_timeout")
  135. if brightness is not None:
  136. display.set_brightness(brightness)
  137. if blank_timeout is not None:
  138. display.set_blank_timeout(blank_timeout)
  139. display.tick()
  140. async def main():
  141. config = Config.load()
  142. logger.info(
  143. "SpoolBuddy daemon v%s starting (device=%s, backend=%s)", __version__, config.device_id, config.backend_url
  144. )
  145. api = APIClient(config.backend_url, config.api_key)
  146. ip = _get_ip()
  147. start_time = time.monotonic()
  148. # Initialize hardware before registration so we can report capabilities
  149. nfc = NFCReader()
  150. scale = ScaleReader(
  151. tare_offset=config.tare_offset,
  152. calibration_factor=config.calibration_factor,
  153. )
  154. display = DisplayControl()
  155. # Register with backend (retries until success)
  156. reg = await api.register_device(
  157. device_id=config.device_id,
  158. hostname=config.hostname,
  159. ip_address=ip,
  160. firmware_version=__version__,
  161. has_nfc=True,
  162. has_scale=True,
  163. tare_offset=config.tare_offset,
  164. calibration_factor=config.calibration_factor,
  165. nfc_reader_type=nfc.reader_type,
  166. nfc_connection=nfc.connection,
  167. has_backlight=display.has_backlight,
  168. )
  169. # Use server-side calibration if available
  170. if reg:
  171. config.tare_offset = reg.get("tare_offset", config.tare_offset)
  172. config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
  173. scale.update_calibration(config.tare_offset, config.calibration_factor)
  174. logger.info("Device registered, starting poll loops")
  175. shared: dict = {"nfc": nfc, "scale": scale, "display": display}
  176. try:
  177. await asyncio.gather(
  178. nfc_poll_loop(config, api, shared),
  179. scale_poll_loop(config, api, shared),
  180. heartbeat_loop(config, api, start_time, shared),
  181. )
  182. except KeyboardInterrupt:
  183. logger.info("Shutting down")
  184. finally:
  185. await api.close()
  186. if __name__ == "__main__":
  187. asyncio.run(main())