main.py 18 KB

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