main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. )
  108. elif event_type == "tag_removed":
  109. await api.tag_removed(
  110. device_id=config.device_id,
  111. tag_uid=event_data["tag_uid"],
  112. )
  113. # Check for pending write command
  114. pending = shared.get("pending_write")
  115. if pending and nfc.state == NFCState.TAG_PRESENT:
  116. if nfc.current_sak in (0x00, 0x04):
  117. logger.info("Executing pending tag write for spool %d", pending["spool_id"])
  118. success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
  119. await api.write_tag_result(
  120. device_id=config.device_id,
  121. spool_id=pending["spool_id"],
  122. tag_uid=nfc.current_uid or "",
  123. success=success,
  124. message=msg,
  125. )
  126. shared.pop("pending_write", None)
  127. else:
  128. # Fail fast when a non-NTAG is presented during write mode.
  129. # Without this, UI can appear stuck on "waiting for SpoolBuddy".
  130. sak = nfc.current_sak
  131. await api.write_tag_result(
  132. device_id=config.device_id,
  133. spool_id=pending["spool_id"],
  134. tag_uid=nfc.current_uid or "",
  135. success=False,
  136. message=f"Incompatible tag type (SAK=0x{sak:02X}). Place an NTAG tag to write.",
  137. )
  138. logger.warning(
  139. "Write aborted for spool %d: incompatible tag type SAK=0x%02X",
  140. pending["spool_id"],
  141. sak,
  142. )
  143. shared.pop("pending_write", None)
  144. await asyncio.sleep(config.nfc_poll_interval)
  145. finally:
  146. nfc: NFCReader | None = shared.get("nfc")
  147. if nfc:
  148. nfc.close()
  149. async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
  150. """Continuous scale reading loop — reads at 100ms, reports at 1s intervals."""
  151. scale: ScaleReader = shared["scale"]
  152. display: DisplayControl = shared["display"]
  153. if not scale.ok:
  154. logger.warning("Scale not available, skipping scale polling")
  155. return
  156. last_report = 0.0
  157. last_reported_grams: float | None = None
  158. last_wake_grams: float | None = None
  159. REPORT_THRESHOLD = 2.0 # Only report if weight changed by more than this (grams)
  160. WAKE_THRESHOLD = 50.0 # Only wake display on large changes (spool placed/removed, not sensor bounce)
  161. try:
  162. while True:
  163. result = await asyncio.to_thread(scale.read)
  164. if result is not None:
  165. grams, stable, raw_adc = result
  166. now = time.monotonic()
  167. if now - last_report >= config.scale_report_interval:
  168. # Only send when weight changed meaningfully
  169. weight_changed = last_reported_grams is None or abs(grams - last_reported_grams) >= REPORT_THRESHOLD
  170. if weight_changed:
  171. # Wake display only on large weight changes (spool placed/removed)
  172. # to avoid sensor bounce keeping the screen on forever.
  173. wake_changed = last_wake_grams is None or abs(grams - last_wake_grams) >= WAKE_THRESHOLD
  174. if wake_changed:
  175. display.wake()
  176. last_wake_grams = grams
  177. await api.scale_reading(
  178. device_id=config.device_id,
  179. weight_grams=grams,
  180. stable=stable,
  181. raw_adc=raw_adc,
  182. )
  183. last_reported_grams = grams
  184. last_report = now
  185. await asyncio.sleep(config.scale_read_interval)
  186. finally:
  187. scale.close()
  188. async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
  189. """Periodic heartbeat to keep device registered and pick up commands."""
  190. display: DisplayControl = shared["display"]
  191. ip = _get_ip()
  192. while True:
  193. await asyncio.sleep(config.heartbeat_interval)
  194. nfc = shared.get("nfc")
  195. scale = shared.get("scale")
  196. uptime = int(time.monotonic() - start_time)
  197. stats = await asyncio.to_thread(system_stats.collect)
  198. result = await api.heartbeat(
  199. device_id=config.device_id,
  200. nfc_ok=nfc.ok if nfc else False,
  201. scale_ok=scale.ok if scale else False,
  202. uptime_s=uptime,
  203. ip_address=ip,
  204. firmware_version=__version__,
  205. nfc_reader_type=nfc.reader_type if nfc else None,
  206. nfc_connection=nfc.connection if nfc else None,
  207. backend_url=config.backend_url,
  208. system_stats=stats,
  209. )
  210. if result:
  211. ssh_key = result.get("ssh_public_key")
  212. if ssh_key:
  213. _deploy_ssh_key(ssh_key)
  214. cmd = result.get("pending_command")
  215. if cmd == "tare":
  216. scale = shared.get("scale")
  217. if scale and scale.ok:
  218. new_offset = await asyncio.to_thread(scale.tare)
  219. logger.info("Tare executed: offset=%d", new_offset)
  220. await api.update_tare(config.device_id, new_offset)
  221. config.tare_offset = new_offset
  222. else:
  223. logger.warning("Tare command received but scale not available")
  224. # Skip calibration sync — this heartbeat response predates the tare
  225. continue
  226. elif cmd == "apply_system_config":
  227. payload = result.get("pending_system_payload") or {}
  228. backend_url = str(payload.get("backend_url", "")).strip()
  229. api_key_value = payload.get("api_key")
  230. api_key = str(api_key_value).strip() if api_key_value is not None else ""
  231. if not backend_url:
  232. await api.system_command_result(
  233. config.device_id,
  234. "apply_system_config",
  235. False,
  236. "Missing backend_url payload",
  237. )
  238. continue
  239. try:
  240. env_path = _spoolbuddy_env_path()
  241. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_BACKEND_URL", backend_url)
  242. if api_key:
  243. await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_API_KEY", api_key)
  244. await api.system_command_result(
  245. config.device_id,
  246. "apply_system_config",
  247. True,
  248. f"Updated {env_path}",
  249. )
  250. logger.info("Applied system config update")
  251. except Exception as e:
  252. logger.exception("Failed to apply system config")
  253. await api.system_command_result(
  254. config.device_id,
  255. "apply_system_config",
  256. False,
  257. str(e),
  258. )
  259. continue
  260. elif cmd in ("run_nfc_diag", "run_scale_diag", "run_read_tag_diag"):
  261. if cmd == "run_scale_diag":
  262. diagnostic = "scale"
  263. script_name = "scale_diag.py"
  264. elif cmd == "run_read_tag_diag":
  265. diagnostic = "read_tag"
  266. script_name = "read_tag.py"
  267. else:
  268. diagnostic = "nfc"
  269. script_name = "pn5180_diag.py"
  270. script_path = Path(__file__).resolve().parent.parent / "scripts" / script_name
  271. if diagnostic in ("nfc", "read_tag"):
  272. logger.info("Pausing NFC continuous scan for diagnostic")
  273. shared["nfc_scan_paused"] = True
  274. nfc_for_diag = shared.get("nfc")
  275. if nfc_for_diag:
  276. await asyncio.to_thread(nfc_for_diag.close)
  277. shared["nfc"] = None
  278. logger.info("Running %s diagnostic via %s", diagnostic, script_path)
  279. try:
  280. proc = await asyncio.to_thread(
  281. subprocess.run,
  282. [sys.executable, str(script_path)],
  283. capture_output=True,
  284. text=True,
  285. timeout=45,
  286. )
  287. output = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
  288. await api.diagnostic_result(
  289. config.device_id,
  290. diagnostic,
  291. proc.returncode == 0,
  292. output,
  293. proc.returncode,
  294. )
  295. except subprocess.TimeoutExpired:
  296. await api.diagnostic_result(
  297. config.device_id,
  298. diagnostic,
  299. False,
  300. "Diagnostic timed out after 45 seconds",
  301. -1,
  302. )
  303. except Exception as e:
  304. await api.diagnostic_result(
  305. config.device_id,
  306. diagnostic,
  307. False,
  308. f"Diagnostic execution failed: {e}",
  309. -1,
  310. )
  311. finally:
  312. if diagnostic in ("nfc", "read_tag"):
  313. logger.info("Reinitializing NFC continuous scan after diagnostic")
  314. shared["nfc"] = NFCReader()
  315. shared["nfc_scan_paused"] = False
  316. continue
  317. elif cmd == "write_tag":
  318. write_payload = result.get("pending_write_payload")
  319. if write_payload:
  320. shared["pending_write"] = {
  321. "spool_id": write_payload["spool_id"],
  322. "ndef_data": bytes.fromhex(write_payload["ndef_data_hex"]),
  323. }
  324. logger.info("Write tag command received for spool %d", write_payload["spool_id"])
  325. elif cmd in ("reboot", "shutdown", "restart_daemon", "restart_browser"):
  326. logger.info("System command received: %s", cmd)
  327. try:
  328. await api.system_command_result(config.device_id, cmd, True, f"Executing {cmd}")
  329. except Exception:
  330. pass # Best effort — we're about to restart/shutdown anyway
  331. if cmd == "reboot":
  332. await asyncio.to_thread(subprocess.run, ["sudo", "reboot"], check=False)
  333. elif cmd == "shutdown":
  334. await asyncio.to_thread(subprocess.run, ["sudo", "shutdown", "-h", "now"], check=False)
  335. elif cmd == "restart_daemon":
  336. await asyncio.to_thread(
  337. subprocess.run, ["sudo", "systemctl", "restart", "spoolbuddy.service"], check=False
  338. )
  339. elif cmd == "restart_browser":
  340. await asyncio.to_thread(
  341. subprocess.run, ["sudo", "systemctl", "restart", "getty@tty1.service"], check=False
  342. )
  343. continue
  344. tare = result.get("tare_offset", config.tare_offset)
  345. cal = result.get("calibration_factor", config.calibration_factor)
  346. if tare != config.tare_offset or cal != config.calibration_factor:
  347. config.tare_offset = tare
  348. config.calibration_factor = cal
  349. scale = shared.get("scale")
  350. if scale:
  351. scale.update_calibration(tare, cal)
  352. logger.info("Calibration updated from backend: tare=%d, factor=%.6f", tare, cal)
  353. # Apply display settings from backend
  354. brightness = result.get("display_brightness")
  355. blank_timeout = result.get("display_blank_timeout")
  356. if brightness is not None:
  357. display.set_brightness(brightness)
  358. if blank_timeout is not None:
  359. display.set_blank_timeout(blank_timeout)
  360. display.tick()
  361. async def main():
  362. config = Config.load()
  363. logger.info(
  364. "SpoolBuddy daemon v%s starting (device=%s, backend=%s)", __version__, config.device_id, config.backend_url
  365. )
  366. api = APIClient(config.backend_url, config.api_key)
  367. ip = _get_ip()
  368. start_time = time.monotonic()
  369. # Initialize hardware before registration so we can report capabilities
  370. nfc = NFCReader()
  371. scale = ScaleReader(
  372. tare_offset=config.tare_offset,
  373. calibration_factor=config.calibration_factor,
  374. )
  375. display = DisplayControl()
  376. # Register with backend (retries until success)
  377. reg = await api.register_device(
  378. device_id=config.device_id,
  379. hostname=config.hostname,
  380. ip_address=ip,
  381. firmware_version=__version__,
  382. has_nfc=True,
  383. has_scale=True,
  384. tare_offset=config.tare_offset,
  385. calibration_factor=config.calibration_factor,
  386. nfc_reader_type=nfc.reader_type,
  387. nfc_connection=nfc.connection,
  388. backend_url=config.backend_url,
  389. has_backlight=display.has_backlight,
  390. )
  391. # Use server-side calibration if available
  392. if reg:
  393. config.tare_offset = reg.get("tare_offset", config.tare_offset)
  394. config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
  395. scale.update_calibration(config.tare_offset, config.calibration_factor)
  396. # Auto-deploy Bambuddy's SSH public key for remote updates
  397. ssh_key = reg.get("ssh_public_key")
  398. if ssh_key:
  399. _deploy_ssh_key(ssh_key)
  400. logger.info("Device registered, starting poll loops")
  401. shared: dict = {"nfc": nfc, "scale": scale, "display": display, "nfc_scan_paused": False}
  402. try:
  403. await asyncio.gather(
  404. nfc_poll_loop(config, api, shared),
  405. scale_poll_loop(config, api, shared),
  406. heartbeat_loop(config, api, start_time, shared),
  407. )
  408. except KeyboardInterrupt:
  409. logger.info("Shutting down")
  410. finally:
  411. await api.close()
  412. if __name__ == "__main__":
  413. asyncio.run(main())