main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 os
  6. import socket
  7. import subprocess
  8. import sys
  9. import time
  10. from pathlib import Path
  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 _spoolbuddy_env_path() -> Path:
  24. # installer writes this at <install>/spoolbuddy/.env; allow override for custom setups/tests
  25. override = os.environ.get("SPOOLBUDDY_ENV_FILE", "").strip()
  26. if override:
  27. return Path(override)
  28. return Path(__file__).resolve().parent.parent / ".env"
  29. def _set_env_value(path: Path, key: str, value: str):
  30. lines: list[str] = []
  31. if path.exists():
  32. lines = path.read_text(encoding="utf-8").splitlines()
  33. updated = False
  34. new_lines: list[str] = []
  35. for line in lines:
  36. if line.startswith(f"{key}="):
  37. new_lines.append(f"{key}={value}")
  38. updated = True
  39. else:
  40. new_lines.append(line)
  41. if not updated:
  42. new_lines.append(f"{key}={value}")
  43. path.parent.mkdir(parents=True, exist_ok=True)
  44. path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
  45. def _get_ip() -> str:
  46. try:
  47. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  48. s.connect(("8.8.8.8", 80))
  49. ip = s.getsockname()[0]
  50. s.close()
  51. return ip
  52. except Exception:
  53. return "unknown"
  54. def _deploy_ssh_key(public_key: str) -> None:
  55. """Write Bambuddy's SSH public key to authorized_keys if not already present."""
  56. home = Path.home()
  57. ssh_dir = home / ".ssh"
  58. auth_keys = ssh_dir / "authorized_keys"
  59. try:
  60. ssh_dir.mkdir(mode=0o700, exist_ok=True)
  61. # Check if key already deployed
  62. if auth_keys.exists():
  63. existing = auth_keys.read_text()
  64. if public_key.strip() in existing:
  65. return
  66. # Append key
  67. with auth_keys.open("a") as f:
  68. f.write(public_key.strip() + "\n")
  69. auth_keys.chmod(0o600)
  70. logger.info("SSH public key deployed to %s", auth_keys)
  71. except Exception as e:
  72. logger.warning("Failed to deploy SSH key: %s", e)
  73. async def nfc_poll_loop(config: Config, api: APIClient, shared: dict):
  74. """Continuous NFC polling loop — runs in asyncio with blocking reads offloaded."""
  75. display: DisplayControl = shared["display"]
  76. try:
  77. while True:
  78. if shared.get("nfc_scan_paused", False):
  79. await asyncio.sleep(config.nfc_poll_interval)
  80. continue
  81. nfc: NFCReader | None = shared.get("nfc")
  82. if not nfc or not nfc.ok:
  83. await asyncio.sleep(config.nfc_poll_interval)
  84. continue
  85. event_type, event_data = await asyncio.to_thread(nfc.poll)
  86. if event_type == "tag_detected":
  87. display.wake()
  88. await api.tag_scanned(
  89. device_id=config.device_id,
  90. tag_uid=event_data["tag_uid"],
  91. tray_uuid=event_data.get("tray_uuid"),
  92. sak=event_data.get("sak"),
  93. tag_type=event_data.get("tag_type"),
  94. )
  95. elif event_type == "tag_removed":
  96. await api.tag_removed(
  97. device_id=config.device_id,
  98. tag_uid=event_data["tag_uid"],
  99. )
  100. # Check for pending write command
  101. pending = shared.get("pending_write")
  102. if pending and nfc.state == NFCState.TAG_PRESENT:
  103. if nfc.current_sak == 0x00:
  104. logger.info("Executing pending tag write for spool %d", pending["spool_id"])
  105. success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
  106. await api.write_tag_result(
  107. device_id=config.device_id,
  108. spool_id=pending["spool_id"],
  109. tag_uid=nfc.current_uid or "",
  110. success=success,
  111. message=msg,
  112. )
  113. shared.pop("pending_write", None)
  114. else:
  115. # Fail fast when a non-NTAG is presented during write mode.
  116. # Without this, UI can appear stuck on "waiting for SpoolBuddy".
  117. sak = nfc.current_sak
  118. await api.write_tag_result(
  119. device_id=config.device_id,
  120. spool_id=pending["spool_id"],
  121. tag_uid=nfc.current_uid or "",
  122. success=False,
  123. message=f"Incompatible tag type (SAK=0x{sak:02X}). Place an NTAG tag to write.",
  124. )
  125. logger.warning(
  126. "Write aborted for spool %d: incompatible tag type SAK=0x%02X",
  127. pending["spool_id"],
  128. sak,
  129. )
  130. shared.pop("pending_write", None)
  131. await asyncio.sleep(config.nfc_poll_interval)
  132. finally:
  133. nfc: NFCReader | None = shared.get("nfc")
  134. if nfc:
  135. nfc.close()
  136. async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
  137. """Continuous scale reading loop — reads at 100ms, reports at 1s intervals."""
  138. scale: ScaleReader = shared["scale"]
  139. display: DisplayControl = shared["display"]
  140. if not scale.ok:
  141. logger.warning("Scale not available, skipping scale polling")
  142. return
  143. last_report = 0.0
  144. last_reported_grams: float | None = None
  145. REPORT_THRESHOLD = 2.0 # Only report if weight changed by more than this (grams)
  146. try:
  147. while True:
  148. result = await asyncio.to_thread(scale.read)
  149. if result is not None:
  150. grams, stable, raw_adc = result
  151. now = time.monotonic()
  152. if now - last_report >= config.scale_report_interval:
  153. # Only send when weight changed meaningfully
  154. weight_changed = last_reported_grams is None or abs(grams - last_reported_grams) >= REPORT_THRESHOLD
  155. if weight_changed:
  156. display.wake()
  157. await api.scale_reading(
  158. device_id=config.device_id,
  159. weight_grams=grams,
  160. stable=stable,
  161. raw_adc=raw_adc,
  162. )
  163. last_reported_grams = grams
  164. last_report = now
  165. await asyncio.sleep(config.scale_read_interval)
  166. finally:
  167. scale.close()
  168. async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
  169. """Periodic heartbeat to keep device registered and pick up commands."""
  170. display: DisplayControl = shared["display"]
  171. ip = _get_ip()
  172. while True:
  173. await asyncio.sleep(config.heartbeat_interval)
  174. nfc = shared.get("nfc")
  175. scale = shared.get("scale")
  176. uptime = int(time.monotonic() - start_time)
  177. result = await api.heartbeat(
  178. device_id=config.device_id,
  179. nfc_ok=nfc.ok if nfc else False,
  180. scale_ok=scale.ok if scale else False,
  181. uptime_s=uptime,
  182. ip_address=ip,
  183. firmware_version=__version__,
  184. nfc_reader_type=nfc.reader_type if nfc else None,
  185. nfc_connection=nfc.connection if nfc else None,
  186. backend_url=config.backend_url,
  187. )
  188. if result:
  189. cmd = result.get("pending_command")
  190. if cmd == "tare":
  191. scale = shared.get("scale")
  192. if scale and scale.ok:
  193. new_offset = await asyncio.to_thread(scale.tare)
  194. logger.info("Tare executed: offset=%d", new_offset)
  195. await api.update_tare(config.device_id, new_offset)
  196. config.tare_offset = new_offset
  197. else:
  198. logger.warning("Tare command received but scale not available")
  199. # Skip calibration sync — this heartbeat response predates the tare
  200. continue
  201. elif cmd == "apply_system_config":
  202. payload = result.get("pending_system_payload") or {}
  203. backend_url = str(payload.get("backend_url", "")).strip()
  204. api_key_value = payload.get("api_key")
  205. api_key = str(api_key_value).strip() if api_key_value is not None else ""
  206. if not backend_url:
  207. await api.system_command_result(
  208. config.device_id,
  209. "apply_system_config",
  210. False,
  211. "Missing backend_url payload",
  212. )
  213. continue
  214. try:
  215. env_path = _spoolbuddy_env_path()
  216. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_BACKEND_URL", backend_url)
  217. if api_key:
  218. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_API_KEY", api_key)
  219. await api.system_command_result(
  220. config.device_id,
  221. "apply_system_config",
  222. True,
  223. f"Updated {env_path}",
  224. )
  225. logger.info("Applied system config update")
  226. except Exception as e:
  227. logger.exception("Failed to apply system config")
  228. await api.system_command_result(
  229. config.device_id,
  230. "apply_system_config",
  231. False,
  232. str(e),
  233. )
  234. continue
  235. elif cmd in ("run_nfc_diag", "run_scale_diag", "run_read_tag_diag"):
  236. if cmd == "run_scale_diag":
  237. diagnostic = "scale"
  238. script_name = "scale_diag.py"
  239. elif cmd == "run_read_tag_diag":
  240. diagnostic = "read_tag"
  241. script_name = "read_tag.py"
  242. else:
  243. diagnostic = "nfc"
  244. script_name = "pn5180_diag.py"
  245. script_path = Path(__file__).resolve().parent.parent / "scripts" / script_name
  246. if diagnostic in ("nfc", "read_tag"):
  247. logger.info("Pausing NFC continuous scan for diagnostic")
  248. shared["nfc_scan_paused"] = True
  249. nfc_for_diag = shared.get("nfc")
  250. if nfc_for_diag:
  251. await asyncio.to_thread(nfc_for_diag.close)
  252. shared["nfc"] = None
  253. logger.info("Running %s diagnostic via %s", diagnostic, script_path)
  254. try:
  255. proc = await asyncio.to_thread(
  256. subprocess.run,
  257. [sys.executable, str(script_path)],
  258. capture_output=True,
  259. text=True,
  260. timeout=45,
  261. )
  262. output = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
  263. await api.diagnostic_result(
  264. config.device_id,
  265. diagnostic,
  266. proc.returncode == 0,
  267. output,
  268. proc.returncode,
  269. )
  270. except subprocess.TimeoutExpired:
  271. await api.diagnostic_result(
  272. config.device_id,
  273. diagnostic,
  274. False,
  275. "Diagnostic timed out after 45 seconds",
  276. -1,
  277. )
  278. except Exception as e:
  279. await api.diagnostic_result(
  280. config.device_id,
  281. diagnostic,
  282. False,
  283. f"Diagnostic execution failed: {e}",
  284. -1,
  285. )
  286. finally:
  287. if diagnostic in ("nfc", "read_tag"):
  288. logger.info("Reinitializing NFC continuous scan after diagnostic")
  289. shared["nfc"] = NFCReader()
  290. shared["nfc_scan_paused"] = False
  291. continue
  292. elif cmd == "write_tag":
  293. write_payload = result.get("pending_write_payload")
  294. if write_payload:
  295. shared["pending_write"] = {
  296. "spool_id": write_payload["spool_id"],
  297. "ndef_data": bytes.fromhex(write_payload["ndef_data_hex"]),
  298. }
  299. logger.info("Write tag command received for spool %d", write_payload["spool_id"])
  300. tare = result.get("tare_offset", config.tare_offset)
  301. cal = result.get("calibration_factor", config.calibration_factor)
  302. if tare != config.tare_offset or cal != config.calibration_factor:
  303. config.tare_offset = tare
  304. config.calibration_factor = cal
  305. scale = shared.get("scale")
  306. if scale:
  307. scale.update_calibration(tare, cal)
  308. logger.info("Calibration updated from backend: tare=%d, factor=%.6f", tare, cal)
  309. # Apply display settings from backend
  310. brightness = result.get("display_brightness")
  311. blank_timeout = result.get("display_blank_timeout")
  312. if brightness is not None:
  313. display.set_brightness(brightness)
  314. if blank_timeout is not None:
  315. display.set_blank_timeout(blank_timeout)
  316. display.tick()
  317. async def main():
  318. config = Config.load()
  319. logger.info(
  320. "SpoolBuddy daemon v%s starting (device=%s, backend=%s)", __version__, config.device_id, config.backend_url
  321. )
  322. api = APIClient(config.backend_url, config.api_key)
  323. ip = _get_ip()
  324. start_time = time.monotonic()
  325. # Initialize hardware before registration so we can report capabilities
  326. nfc = NFCReader()
  327. scale = ScaleReader(
  328. tare_offset=config.tare_offset,
  329. calibration_factor=config.calibration_factor,
  330. )
  331. display = DisplayControl()
  332. # Register with backend (retries until success)
  333. reg = await api.register_device(
  334. device_id=config.device_id,
  335. hostname=config.hostname,
  336. ip_address=ip,
  337. firmware_version=__version__,
  338. has_nfc=True,
  339. has_scale=True,
  340. tare_offset=config.tare_offset,
  341. calibration_factor=config.calibration_factor,
  342. nfc_reader_type=nfc.reader_type,
  343. nfc_connection=nfc.connection,
  344. backend_url=config.backend_url,
  345. has_backlight=display.has_backlight,
  346. )
  347. # Use server-side calibration if available
  348. if reg:
  349. config.tare_offset = reg.get("tare_offset", config.tare_offset)
  350. config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
  351. scale.update_calibration(config.tare_offset, config.calibration_factor)
  352. # Auto-deploy Bambuddy's SSH public key for remote updates
  353. ssh_key = reg.get("ssh_public_key")
  354. if ssh_key:
  355. _deploy_ssh_key(ssh_key)
  356. logger.info("Device registered, starting poll loops")
  357. shared: dict = {"nfc": nfc, "scale": scale, "display": display, "nfc_scan_paused": False}
  358. try:
  359. await asyncio.gather(
  360. nfc_poll_loop(config, api, shared),
  361. scale_poll_loop(config, api, shared),
  362. heartbeat_loop(config, api, start_time, shared),
  363. )
  364. except KeyboardInterrupt:
  365. logger.info("Shutting down")
  366. finally:
  367. await api.close()
  368. if __name__ == "__main__":
  369. asyncio.run(main())