main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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__, system_stats
  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. logging.getLogger("daemon.pn5180").setLevel(logging.DEBUG)
  24. def _spoolbuddy_env_path() -> Path:
  25. # installer writes this at <install>/spoolbuddy/.env; allow override for custom setups/tests
  26. override = os.environ.get("SPOOLBUDDY_ENV_FILE", "").strip()
  27. if override:
  28. return Path(override)
  29. return Path(__file__).resolve().parent.parent / ".env"
  30. def _set_env_value(path: Path, key: str, value: str):
  31. lines: list[str] = []
  32. if path.exists():
  33. lines = path.read_text(encoding="utf-8").splitlines()
  34. updated = False
  35. new_lines: list[str] = []
  36. for line in lines:
  37. if line.startswith(f"{key}="):
  38. new_lines.append(f"{key}={value}")
  39. updated = True
  40. else:
  41. new_lines.append(line)
  42. if not updated:
  43. new_lines.append(f"{key}={value}")
  44. path.parent.mkdir(parents=True, exist_ok=True)
  45. path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
  46. def _get_ip() -> str:
  47. try:
  48. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  49. s.connect(("8.8.8.8", 80))
  50. ip = s.getsockname()[0]
  51. s.close()
  52. return ip
  53. except Exception:
  54. return "unknown"
  55. SSH_KEY_TAG = "bambuddy-spoolbuddy"
  56. def _deploy_ssh_key(public_key: str) -> None:
  57. """Sync Bambuddy's SSH public key into authorized_keys.
  58. Replaces any prior key tagged ``bambuddy-spoolbuddy`` so the file always
  59. reflects Bambuddy's *current* keypair. Without this, every Bambuddy key
  60. rotation (data dir wipe, container recreate, etc.) leaves a stale entry
  61. behind and the file grows unbounded.
  62. """
  63. target = public_key.strip()
  64. home = Path.home()
  65. ssh_dir = home / ".ssh"
  66. auth_keys = ssh_dir / "authorized_keys"
  67. try:
  68. ssh_dir.mkdir(mode=0o700, exist_ok=True)
  69. existing_lines: list[str] = []
  70. if auth_keys.exists():
  71. existing_lines = auth_keys.read_text().splitlines()
  72. kept = [line for line in existing_lines if SSH_KEY_TAG not in line]
  73. new_lines = kept + [target]
  74. # Already in sync — current key present and no stale Bambuddy entries.
  75. if existing_lines == new_lines:
  76. return
  77. auth_keys.write_text("\n".join(new_lines) + "\n")
  78. auth_keys.chmod(0o600)
  79. removed = len(existing_lines) - len(kept)
  80. if removed:
  81. logger.info("SSH public key updated in %s (replaced %d stale entries)", auth_keys, removed)
  82. else:
  83. logger.info("SSH public key deployed to %s", auth_keys)
  84. except Exception as e:
  85. logger.warning("Failed to deploy SSH key: %s", e)
  86. async def nfc_poll_loop(config: Config, api: APIClient, shared: dict):
  87. """Continuous NFC polling loop — runs in asyncio with blocking reads offloaded."""
  88. display: DisplayControl = shared["display"]
  89. try:
  90. while True:
  91. if shared.get("nfc_scan_paused", False):
  92. await asyncio.sleep(config.nfc_poll_interval)
  93. continue
  94. nfc: NFCReader | None = shared.get("nfc")
  95. if not nfc or not nfc.ok:
  96. await asyncio.sleep(config.nfc_poll_interval)
  97. continue
  98. event_type, event_data = await asyncio.to_thread(nfc.poll)
  99. if event_type == "tag_detected":
  100. display.wake()
  101. await api.tag_scanned(
  102. device_id=config.device_id,
  103. tag_uid=event_data["tag_uid"],
  104. tray_uuid=event_data.get("tray_uuid"),
  105. sak=event_data.get("sak"),
  106. tag_type=event_data.get("tag_type"),
  107. raw_blocks=event_data.get("raw_blocks"),
  108. )
  109. elif event_type == "tag_removed":
  110. await api.tag_removed(
  111. device_id=config.device_id,
  112. tag_uid=event_data["tag_uid"],
  113. )
  114. # Check for pending write command
  115. pending = shared.get("pending_write")
  116. if pending and nfc.state == NFCState.TAG_PRESENT:
  117. if nfc.current_sak in (0x00, 0x04):
  118. logger.info("Executing pending tag write for spool %d", pending["spool_id"])
  119. success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
  120. await api.write_tag_result(
  121. device_id=config.device_id,
  122. spool_id=pending["spool_id"],
  123. tag_uid=nfc.current_uid or "",
  124. success=success,
  125. message=msg,
  126. )
  127. shared.pop("pending_write", None)
  128. else:
  129. # Fail fast when a non-NTAG is presented during write mode.
  130. # Without this, UI can appear stuck on "waiting for SpoolBuddy".
  131. sak = nfc.current_sak
  132. await api.write_tag_result(
  133. device_id=config.device_id,
  134. spool_id=pending["spool_id"],
  135. tag_uid=nfc.current_uid or "",
  136. success=False,
  137. message=f"Incompatible tag type (SAK=0x{sak:02X}). Place an NTAG tag to write.",
  138. )
  139. logger.warning(
  140. "Write aborted for spool %d: incompatible tag type SAK=0x%02X",
  141. pending["spool_id"],
  142. sak,
  143. )
  144. shared.pop("pending_write", None)
  145. await asyncio.sleep(config.nfc_poll_interval)
  146. finally:
  147. nfc: NFCReader | None = shared.get("nfc")
  148. if nfc:
  149. nfc.close()
  150. async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
  151. """Continuous scale reading loop — reads at 100ms, reports at 1s intervals."""
  152. scale: ScaleReader = shared["scale"]
  153. display: DisplayControl = shared["display"]
  154. if not scale.ok:
  155. logger.warning("Scale not available, skipping scale polling")
  156. return
  157. last_report = 0.0
  158. last_reported_grams: float | None = None
  159. last_wake_grams: float | None = None
  160. REPORT_THRESHOLD = 2.0 # Only report if weight changed by more than this (grams)
  161. WAKE_THRESHOLD = 50.0 # Only wake display on large changes (spool placed/removed, not sensor bounce)
  162. try:
  163. while True:
  164. result = await asyncio.to_thread(scale.read)
  165. if result is not None:
  166. grams, stable, raw_adc = result
  167. now = time.monotonic()
  168. if now - last_report >= config.scale_report_interval:
  169. # Only send when weight changed meaningfully
  170. weight_changed = last_reported_grams is None or abs(grams - last_reported_grams) >= REPORT_THRESHOLD
  171. if weight_changed:
  172. # Wake display only on STABLE large weight changes (spool
  173. # placed/removed). Without the stability gate, a noisy load
  174. # cell that bounces ≥50g around a midpoint repeatedly trips
  175. # the threshold AND advances last_wake_grams to the noisy
  176. # value, so the next bounce back also exceeds the threshold
  177. # — wake fires every few seconds forever and the kiosk
  178. # screen never stays blanked. The `stable` flag is True
  179. # only when readings agree within 2g over a 1s window, so
  180. # gating on it ensures last_wake_grams only advances to
  181. # settled values.
  182. wake_changed = stable and (
  183. last_wake_grams is None or abs(grams - last_wake_grams) >= WAKE_THRESHOLD
  184. )
  185. if wake_changed:
  186. display.wake()
  187. last_wake_grams = grams
  188. await api.scale_reading(
  189. device_id=config.device_id,
  190. weight_grams=grams,
  191. stable=stable,
  192. raw_adc=raw_adc,
  193. )
  194. last_reported_grams = grams
  195. last_report = now
  196. await asyncio.sleep(config.scale_read_interval)
  197. finally:
  198. scale.close()
  199. async def _register(config: Config, api: APIClient, nfc, scale, display, ip: str) -> None:
  200. """Register with the backend (retries until it answers) and take its
  201. calibration. At startup, and again when the device was unregistered."""
  202. reg = await api.register_device(
  203. device_id=config.device_id,
  204. hostname=config.hostname,
  205. ip_address=ip,
  206. firmware_version=__version__,
  207. has_nfc=True,
  208. has_scale=True,
  209. tare_offset=config.tare_offset,
  210. calibration_factor=config.calibration_factor,
  211. nfc_reader_type=nfc.reader_type if nfc else None,
  212. nfc_connection=nfc.connection if nfc else None,
  213. backend_url=config.backend_url,
  214. has_backlight=display.has_backlight,
  215. )
  216. # Use server-side calibration if available
  217. if reg:
  218. config.tare_offset = reg.get("tare_offset", config.tare_offset)
  219. config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
  220. if scale:
  221. scale.update_calibration(config.tare_offset, config.calibration_factor)
  222. # Auto-deploy Bambuddy's SSH public key for remote updates
  223. ssh_key = reg.get("ssh_public_key")
  224. if ssh_key:
  225. _deploy_ssh_key(ssh_key)
  226. async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
  227. """Periodic heartbeat to keep device registered and pick up commands."""
  228. display: DisplayControl = shared["display"]
  229. ip = _get_ip()
  230. while True:
  231. await asyncio.sleep(config.heartbeat_interval)
  232. nfc = shared.get("nfc")
  233. scale = shared.get("scale")
  234. uptime = int(time.monotonic() - start_time)
  235. stats = await asyncio.to_thread(system_stats.collect)
  236. result = await api.heartbeat(
  237. device_id=config.device_id,
  238. nfc_ok=nfc.ok if nfc else False,
  239. scale_ok=scale.ok if scale else False,
  240. uptime_s=uptime,
  241. ip_address=ip,
  242. firmware_version=__version__,
  243. nfc_reader_type=nfc.reader_type if nfc else None,
  244. nfc_connection=nfc.connection if nfc else None,
  245. backend_url=config.backend_url,
  246. system_stats=stats,
  247. )
  248. if api.unregistered is True:
  249. # An admin removed the device while it kept running: register again
  250. # so it reappears (the route's documented behaviour).
  251. logger.info("Backend no longer knows this device, registering again")
  252. api.unregistered = False
  253. await _register(config, api, nfc, scale, display, ip)
  254. continue
  255. if result:
  256. ssh_key = result.get("ssh_public_key")
  257. if ssh_key:
  258. _deploy_ssh_key(ssh_key)
  259. cmd = result.get("pending_command")
  260. if cmd == "tare":
  261. scale = shared.get("scale")
  262. if scale and scale.ok:
  263. new_offset = await asyncio.to_thread(scale.tare)
  264. logger.info("Tare executed: offset=%d", new_offset)
  265. await api.update_tare(config.device_id, new_offset)
  266. config.tare_offset = new_offset
  267. else:
  268. logger.warning("Tare command received but scale not available")
  269. # Skip calibration sync — this heartbeat response predates the tare
  270. continue
  271. elif cmd == "apply_system_config":
  272. payload = result.get("pending_system_payload") or {}
  273. backend_url = str(payload.get("backend_url", "")).strip()
  274. api_key_value = payload.get("api_key")
  275. api_key = str(api_key_value).strip() if api_key_value is not None else ""
  276. if not backend_url:
  277. await api.system_command_result(
  278. config.device_id,
  279. "apply_system_config",
  280. False,
  281. "Missing backend_url payload",
  282. )
  283. continue
  284. try:
  285. env_path = _spoolbuddy_env_path()
  286. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_BACKEND_URL", backend_url)
  287. if api_key:
  288. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_API_KEY", api_key)
  289. await api.system_command_result(
  290. config.device_id,
  291. "apply_system_config",
  292. True,
  293. f"Updated {env_path}",
  294. )
  295. logger.info("Applied system config update")
  296. except Exception as e:
  297. logger.exception("Failed to apply system config")
  298. await api.system_command_result(
  299. config.device_id,
  300. "apply_system_config",
  301. False,
  302. str(e),
  303. )
  304. continue
  305. elif cmd in ("run_nfc_diag", "run_scale_diag", "run_read_tag_diag"):
  306. if cmd == "run_scale_diag":
  307. diagnostic = "scale"
  308. script_name = "scale_diag.py"
  309. elif cmd == "run_read_tag_diag":
  310. diagnostic = "read_tag"
  311. script_name = "read_tag.py"
  312. else:
  313. diagnostic = "nfc"
  314. script_name = "pn5180_diag.py"
  315. script_path = Path(__file__).resolve().parent.parent / "scripts" / script_name
  316. if diagnostic in ("nfc", "read_tag"):
  317. logger.info("Pausing NFC continuous scan for diagnostic")
  318. shared["nfc_scan_paused"] = True
  319. nfc_for_diag = shared.get("nfc")
  320. if nfc_for_diag:
  321. await asyncio.to_thread(nfc_for_diag.close)
  322. shared["nfc"] = None
  323. logger.info("Running %s diagnostic via %s", diagnostic, script_path)
  324. try:
  325. proc = await asyncio.to_thread(
  326. subprocess.run,
  327. [sys.executable, str(script_path)],
  328. capture_output=True,
  329. text=True,
  330. timeout=45,
  331. )
  332. output = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
  333. await api.diagnostic_result(
  334. config.device_id,
  335. diagnostic,
  336. proc.returncode == 0,
  337. output,
  338. proc.returncode,
  339. )
  340. except subprocess.TimeoutExpired:
  341. await api.diagnostic_result(
  342. config.device_id,
  343. diagnostic,
  344. False,
  345. "Diagnostic timed out after 45 seconds",
  346. -1,
  347. )
  348. except Exception as e:
  349. await api.diagnostic_result(
  350. config.device_id,
  351. diagnostic,
  352. False,
  353. f"Diagnostic execution failed: {e}",
  354. -1,
  355. )
  356. finally:
  357. if diagnostic in ("nfc", "read_tag"):
  358. logger.info("Reinitializing NFC continuous scan after diagnostic")
  359. shared["nfc"] = NFCReader()
  360. shared["nfc_scan_paused"] = False
  361. continue
  362. elif cmd == "write_tag":
  363. write_payload = result.get("pending_write_payload")
  364. if write_payload:
  365. shared["pending_write"] = {
  366. "spool_id": write_payload["spool_id"],
  367. "ndef_data": bytes.fromhex(write_payload["ndef_data_hex"]),
  368. }
  369. logger.info("Write tag command received for spool %d", write_payload["spool_id"])
  370. elif cmd in ("reboot", "shutdown", "restart_daemon", "restart_browser"):
  371. logger.info("System command received: %s", cmd)
  372. try:
  373. await api.system_command_result(config.device_id, cmd, True, f"Executing {cmd}")
  374. except Exception:
  375. pass # Best effort — we're about to restart/shutdown anyway
  376. if cmd == "reboot":
  377. await asyncio.to_thread(subprocess.run, ["sudo", "reboot"], check=False)
  378. elif cmd == "shutdown":
  379. await asyncio.to_thread(subprocess.run, ["sudo", "shutdown", "-h", "now"], check=False)
  380. elif cmd == "restart_daemon":
  381. await asyncio.to_thread(
  382. subprocess.run, ["sudo", "systemctl", "restart", "spoolbuddy.service"], check=False
  383. )
  384. elif cmd == "restart_browser":
  385. await asyncio.to_thread(
  386. subprocess.run, ["sudo", "systemctl", "restart", "getty@tty1.service"], check=False
  387. )
  388. continue
  389. tare = result.get("tare_offset", config.tare_offset)
  390. cal = result.get("calibration_factor", config.calibration_factor)
  391. if tare != config.tare_offset or cal != config.calibration_factor:
  392. config.tare_offset = tare
  393. config.calibration_factor = cal
  394. scale = shared.get("scale")
  395. if scale:
  396. scale.update_calibration(tare, cal)
  397. logger.info("Calibration updated from backend: tare=%d, factor=%.6f", tare, cal)
  398. # Apply display settings from backend
  399. brightness = result.get("display_brightness")
  400. blank_timeout = result.get("display_blank_timeout")
  401. if brightness is not None:
  402. display.set_brightness(brightness)
  403. if blank_timeout is not None:
  404. display.set_blank_timeout(blank_timeout)
  405. display.tick()
  406. async def main():
  407. config = Config.load()
  408. logger.info(
  409. "SpoolBuddy daemon v%s starting (device=%s, backend=%s)", __version__, config.device_id, config.backend_url
  410. )
  411. api = APIClient(config.backend_url, config.api_key)
  412. ip = _get_ip()
  413. start_time = time.monotonic()
  414. # Initialize hardware before registration so we can report capabilities
  415. nfc = NFCReader()
  416. scale = ScaleReader(
  417. tare_offset=config.tare_offset,
  418. calibration_factor=config.calibration_factor,
  419. )
  420. display = DisplayControl()
  421. # Register with backend (retries until success)
  422. await _register(config, api, nfc, scale, display, ip)
  423. logger.info("Device registered, starting poll loops")
  424. shared: dict = {"nfc": nfc, "scale": scale, "display": display, "nfc_scan_paused": False}
  425. try:
  426. await asyncio.gather(
  427. nfc_poll_loop(config, api, shared),
  428. scale_poll_loop(config, api, shared),
  429. heartbeat_loop(config, api, start_time, shared),
  430. )
  431. except KeyboardInterrupt:
  432. logger.info("Shutting down")
  433. finally:
  434. await api.close()
  435. if __name__ == "__main__":
  436. asyncio.run(main())