spoolbuddy.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. """SpoolBuddy device management API routes."""
  2. import asyncio
  3. import contextlib
  4. import json
  5. import logging
  6. import time
  7. from datetime import datetime, timedelta, timezone
  8. from urllib.parse import urlparse
  9. import httpx
  10. from fastapi import APIRouter, Depends, HTTPException
  11. from sqlalchemy import select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.core.websocket import ws_manager
  17. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  18. from backend.app.models.user import User
  19. from backend.app.schemas.spoolbuddy import (
  20. CalibrationResponse,
  21. DeviceRegisterRequest,
  22. DeviceResponse,
  23. DiagnosticResultRequest,
  24. DisplaySettingsRequest,
  25. HeartbeatRequest,
  26. HeartbeatResponse,
  27. ScaleReadingRequest,
  28. SetCalibrationFactorRequest,
  29. SetTareRequest,
  30. SystemCommandRequest,
  31. SystemCommandResultRequest,
  32. SystemConfigRequest,
  33. TagRemovedRequest,
  34. TagScannedRequest,
  35. UpdateSpoolWeightRequest,
  36. UpdateStatusRequest,
  37. WriteTagRequest,
  38. WriteTagResultRequest,
  39. )
  40. from backend.app.services.spool_tag_matcher import get_spool_by_tag
  41. from backend.app.services.spoolman import SpoolmanClientError, SpoolmanNotFoundError, SpoolmanUnavailableError
  42. logger = logging.getLogger(__name__)
  43. router = APIRouter(prefix="/spoolbuddy", tags=["spoolbuddy"])
  44. OFFLINE_THRESHOLD_SECONDS = 30
  45. ONLINE_BROADCAST_INTERVAL_SECONDS = 10
  46. _SSRF_WARN_THROTTLE_SECONDS = 60
  47. _spoolbuddy_online_last_broadcast: dict[str, float] = {}
  48. _ssrf_warn_last_broadcast: dict[str, float] = {}
  49. _diagnostic_results: dict[tuple[str, str], dict] = {}
  50. @contextlib.asynccontextmanager
  51. async def _translate_spoolbuddy_errors():
  52. """Translate Spoolman typed exceptions to HTTP for SpoolBuddy endpoints."""
  53. try:
  54. yield
  55. except SpoolmanNotFoundError as exc:
  56. raise HTTPException(status_code=404, detail="Spool not found in Spoolman") from exc
  57. except SpoolmanClientError as exc:
  58. raise HTTPException(status_code=502, detail="Spoolman rejected the request") from exc
  59. except SpoolmanUnavailableError as exc:
  60. raise HTTPException(status_code=503, detail="Spoolman server is not reachable") from exc
  61. async def _get_spoolman_client_or_none(db: AsyncSession):
  62. """Return a SpoolmanClient if Spoolman is enabled with a safe URL, else None."""
  63. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  64. from backend.app.models.settings import Settings
  65. from backend.app.services.spoolman import get_spoolman_client, init_spoolman_client
  66. settings_result = await db.execute(select(Settings))
  67. settings_dict = {s.key: s.value for s in settings_result.scalars().all()}
  68. spoolman_url = settings_dict.get("spoolman_url", "").strip()
  69. spoolman_enabled = settings_dict.get("spoolman_enabled", "false").lower() == "true" and bool(spoolman_url)
  70. if not spoolman_enabled:
  71. return None
  72. # SSRF guard: reject dangerous schemes, cloud-metadata IPs (169.254.169.254, 100.100.100.200,
  73. # fd00:ec2::254), multicast and unspecified addresses — loopback and RFC-1918 ranges are
  74. # intentionally permitted (Spoolman commonly runs on the same host or home LAN).
  75. try:
  76. assert_safe_spoolman_url(spoolman_url)
  77. except ValueError as exc:
  78. logger.warning(
  79. "Spoolman integration disabled: URL %r rejected by SSRF guard: %s",
  80. spoolman_url,
  81. exc,
  82. )
  83. now = time.monotonic()
  84. if now - _ssrf_warn_last_broadcast.get(spoolman_url, 0) > _SSRF_WARN_THROTTLE_SECONDS:
  85. _ssrf_warn_last_broadcast[spoolman_url] = now
  86. await ws_manager.broadcast(
  87. {
  88. "type": "spoolman_ssrf_blocked",
  89. "detail": "Spoolman URL was rejected by the SSRF guard",
  90. }
  91. )
  92. return None
  93. client = await get_spoolman_client()
  94. if not client or client.base_url != spoolman_url.rstrip("/"):
  95. try:
  96. client = await init_spoolman_client(spoolman_url)
  97. except ValueError as exc:
  98. logger.warning(
  99. "Spoolman integration disabled: URL %r rejected on re-initialisation: %s",
  100. spoolman_url,
  101. exc,
  102. )
  103. return None
  104. return client
  105. def _is_online(device: SpoolBuddyDevice) -> bool:
  106. if not device.last_seen:
  107. return False
  108. return (
  109. datetime.now(timezone.utc) - device.last_seen.replace(tzinfo=timezone.utc)
  110. ).total_seconds() < OFFLINE_THRESHOLD_SECONDS
  111. def _device_to_response(device: SpoolBuddyDevice) -> DeviceResponse:
  112. return DeviceResponse(
  113. id=device.id,
  114. device_id=device.device_id,
  115. hostname=device.hostname,
  116. ip_address=device.ip_address,
  117. firmware_version=device.firmware_version,
  118. has_nfc=device.has_nfc,
  119. has_scale=device.has_scale,
  120. tare_offset=device.tare_offset,
  121. calibration_factor=device.calibration_factor,
  122. nfc_reader_type=device.nfc_reader_type,
  123. nfc_connection=device.nfc_connection,
  124. backend_url=device.backend_url,
  125. display_brightness=device.display_brightness,
  126. display_blank_timeout=device.display_blank_timeout,
  127. has_backlight=device.has_backlight,
  128. last_calibrated_at=device.last_calibrated_at,
  129. last_seen=device.last_seen,
  130. pending_command=device.pending_command,
  131. nfc_ok=device.nfc_ok,
  132. scale_ok=device.scale_ok,
  133. uptime_s=device.uptime_s,
  134. update_status=device.update_status,
  135. update_message=device.update_message,
  136. system_stats=json.loads(device.system_stats) if device.system_stats else None,
  137. online=_is_online(device),
  138. created_at=device.created_at,
  139. updated_at=device.updated_at,
  140. )
  141. def _should_broadcast_online(device_id: str, force: bool = False) -> bool:
  142. if force:
  143. _spoolbuddy_online_last_broadcast[device_id] = time.time()
  144. return True
  145. now_ts = time.time()
  146. last_ts = _spoolbuddy_online_last_broadcast.get(device_id, 0.0)
  147. if now_ts - last_ts >= ONLINE_BROADCAST_INTERVAL_SECONDS:
  148. _spoolbuddy_online_last_broadcast[device_id] = now_ts
  149. return True
  150. return False
  151. # --- Device endpoints ---
  152. @router.post("/devices/register", response_model=DeviceResponse)
  153. async def register_device(
  154. req: DeviceRegisterRequest,
  155. db: AsyncSession = Depends(get_db),
  156. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  157. ):
  158. """Register or re-register a SpoolBuddy device."""
  159. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  160. device = result.scalar_one_or_none()
  161. now = datetime.now(timezone.utc)
  162. if device:
  163. device.hostname = req.hostname
  164. device.ip_address = req.ip_address
  165. device.firmware_version = req.firmware_version
  166. device.has_nfc = req.has_nfc
  167. device.has_scale = req.has_scale
  168. device.nfc_reader_type = req.nfc_reader_type
  169. device.nfc_connection = req.nfc_connection
  170. if req.backend_url:
  171. device.backend_url = req.backend_url
  172. device.has_backlight = req.has_backlight
  173. device.last_seen = now
  174. # Clear stale update status on re-registration (daemon restarted after update)
  175. if device.update_status in ("pending", "updating", "complete", "error"):
  176. device.update_status = None
  177. device.update_message = None
  178. logger.info("SpoolBuddy device re-registered: %s (%s)", req.device_id, req.hostname)
  179. else:
  180. device = SpoolBuddyDevice(
  181. device_id=req.device_id,
  182. hostname=req.hostname,
  183. ip_address=req.ip_address,
  184. firmware_version=req.firmware_version,
  185. has_nfc=req.has_nfc,
  186. has_scale=req.has_scale,
  187. tare_offset=req.tare_offset,
  188. calibration_factor=req.calibration_factor,
  189. nfc_reader_type=req.nfc_reader_type,
  190. nfc_connection=req.nfc_connection,
  191. has_backlight=req.has_backlight,
  192. backend_url=req.backend_url,
  193. last_seen=now,
  194. )
  195. db.add(device)
  196. logger.info("SpoolBuddy device registered: %s (%s)", req.device_id, req.hostname)
  197. await db.commit()
  198. await db.refresh(device)
  199. _spoolbuddy_online_last_broadcast[device.device_id] = time.time()
  200. await ws_manager.broadcast(
  201. {
  202. "type": "spoolbuddy_online",
  203. "device_id": device.device_id,
  204. "hostname": device.hostname,
  205. }
  206. )
  207. response = _device_to_response(device)
  208. # Include SSH public key so the daemon can auto-deploy it
  209. try:
  210. from backend.app.services.spoolbuddy_ssh import get_public_key
  211. response.ssh_public_key = await get_public_key()
  212. except Exception as exc:
  213. logger.warning("Could not attach SSH public key to heartbeat response: %s", exc)
  214. return response
  215. @router.get("/devices", response_model=list[DeviceResponse])
  216. async def list_devices(
  217. db: AsyncSession = Depends(get_db),
  218. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  219. ):
  220. """List all registered SpoolBuddy devices."""
  221. result = await db.execute(select(SpoolBuddyDevice).order_by(SpoolBuddyDevice.hostname))
  222. devices = list(result.scalars().all())
  223. return [_device_to_response(d) for d in devices]
  224. @router.delete("/devices/{device_id}")
  225. async def unregister_device(
  226. device_id: str,
  227. db: AsyncSession = Depends(get_db),
  228. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_DELETE),
  229. ):
  230. """Unregister a SpoolBuddy device. The daemon can re-register via heartbeat later."""
  231. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  232. device = result.scalar_one_or_none()
  233. if not device:
  234. raise HTTPException(status_code=404, detail="Device not registered")
  235. await db.delete(device)
  236. await db.commit()
  237. _spoolbuddy_online_last_broadcast.pop(device_id, None)
  238. logger.info("SpoolBuddy device unregistered: %s (%s)", device_id, device.hostname)
  239. await ws_manager.broadcast({"type": "spoolbuddy_unregistered", "device_id": device_id})
  240. return {"status": "deleted", "device_id": device_id}
  241. @router.post("/devices/{device_id}/heartbeat", response_model=HeartbeatResponse)
  242. async def device_heartbeat(
  243. device_id: str,
  244. req: HeartbeatRequest,
  245. db: AsyncSession = Depends(get_db),
  246. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  247. ):
  248. """Daemon heartbeat — updates status and returns pending commands."""
  249. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  250. device = result.scalar_one_or_none()
  251. if not device:
  252. raise HTTPException(status_code=404, detail="Device not registered")
  253. was_offline = not _is_online(device)
  254. now = datetime.now(timezone.utc)
  255. device.last_seen = now
  256. device.nfc_ok = req.nfc_ok
  257. device.scale_ok = req.scale_ok
  258. device.uptime_s = req.uptime_s
  259. if req.firmware_version:
  260. device.firmware_version = req.firmware_version
  261. if req.ip_address:
  262. device.ip_address = req.ip_address
  263. if req.nfc_reader_type:
  264. device.nfc_reader_type = req.nfc_reader_type
  265. if req.nfc_connection:
  266. device.nfc_connection = req.nfc_connection
  267. if req.backend_url:
  268. device.backend_url = req.backend_url
  269. if req.system_stats is not None:
  270. device.system_stats = json.dumps(req.system_stats)
  271. # Return and clear pending command
  272. pending = device.pending_command
  273. pending_write = None
  274. pending_system = None
  275. if pending == "write_tag" and device.pending_write_payload:
  276. # Parse the stored JSON payload to include in response
  277. try:
  278. pending_write = json.loads(device.pending_write_payload)
  279. except (json.JSONDecodeError, TypeError):
  280. pending_write = None
  281. # Don't clear write_tag command — it gets cleared by write-result
  282. elif pending == "apply_system_config" and device.pending_system_payload:
  283. try:
  284. pending_system = json.loads(device.pending_system_payload)
  285. except (json.JSONDecodeError, TypeError):
  286. pending_system = None
  287. # Don't clear config command — it gets cleared by daemon command-result callback
  288. elif pending and pending.startswith("run_") and pending.endswith("_diag"):
  289. # Don't clear diagnostic commands — they get cleared by the device reporting results
  290. pass
  291. else:
  292. device.pending_command = None
  293. await db.commit()
  294. # Emit online presence on offline->online transitions immediately, and
  295. # periodically while online so newly connected UIs can bootstrap state.
  296. if _should_broadcast_online(device.device_id, force=was_offline):
  297. await ws_manager.broadcast(
  298. {
  299. "type": "spoolbuddy_online",
  300. "device_id": device.device_id,
  301. "hostname": device.hostname,
  302. }
  303. )
  304. if was_offline:
  305. logger.info("SpoolBuddy device back online: %s", device.device_id)
  306. # Include current SSH public key so the daemon can re-deploy it whenever
  307. # Bambuddy's keypair rotates (data dir wiped, container recreated, etc.) —
  308. # otherwise SSH updates fail until the daemon restarts.
  309. ssh_public_key: str | None = None
  310. try:
  311. from backend.app.services.spoolbuddy_ssh import get_public_key
  312. ssh_public_key = await get_public_key()
  313. except Exception:
  314. pass
  315. return HeartbeatResponse(
  316. pending_command=pending,
  317. pending_write_payload=pending_write,
  318. pending_system_payload=pending_system,
  319. tare_offset=device.tare_offset,
  320. calibration_factor=device.calibration_factor,
  321. display_brightness=device.display_brightness,
  322. display_blank_timeout=device.display_blank_timeout,
  323. ssh_public_key=ssh_public_key,
  324. )
  325. # --- NFC endpoints ---
  326. @router.post("/nfc/tag-scanned")
  327. async def nfc_tag_scanned(
  328. req: TagScannedRequest,
  329. db: AsyncSession = Depends(get_db),
  330. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  331. ):
  332. """RPi reports NFC tag detected — lookup spool and broadcast."""
  333. spool = await get_spool_by_tag(db, req.tag_uid, req.tray_uuid or "")
  334. if spool:
  335. await ws_manager.broadcast(
  336. {
  337. "type": "spoolbuddy_tag_matched",
  338. "device_id": req.device_id,
  339. "tag_uid": req.tag_uid,
  340. "tray_uuid": req.tray_uuid,
  341. "spool": {
  342. "id": spool.id,
  343. "material": spool.material,
  344. "subtype": spool.subtype,
  345. "color_name": spool.color_name,
  346. "rgba": spool.rgba,
  347. "brand": spool.brand,
  348. "label_weight": spool.label_weight,
  349. "core_weight": spool.core_weight,
  350. "weight_used": spool.weight_used,
  351. },
  352. }
  353. )
  354. logger.info("SpoolBuddy tag matched (local): %s -> spool %d", req.tag_uid, spool.id)
  355. return {"status": "ok", "matched": True, "spool_id": spool.id}
  356. # Local DB miss — fall back to Spoolman when enabled
  357. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  358. client = await _get_spoolman_client_or_none(db)
  359. if client is not None:
  360. try:
  361. cached_spools = await client.get_spools()
  362. sm_spool: dict | None = None
  363. if req.tray_uuid:
  364. sm_spool = await client.find_spool_by_tag(req.tray_uuid, cached_spools=cached_spools)
  365. if sm_spool is None and req.tag_uid:
  366. sm_spool = await client.find_spool_by_tag(req.tag_uid, cached_spools=cached_spools)
  367. if sm_spool is not None:
  368. mapped = _map_spoolman_spool(sm_spool)
  369. await ws_manager.broadcast(
  370. {
  371. "type": "spoolbuddy_tag_matched",
  372. "device_id": req.device_id,
  373. "tag_uid": req.tag_uid,
  374. "tray_uuid": req.tray_uuid,
  375. "spool": {
  376. "id": mapped["id"],
  377. "material": mapped["material"],
  378. "subtype": mapped["subtype"],
  379. "color_name": mapped["color_name"],
  380. "rgba": mapped["rgba"],
  381. "brand": mapped["brand"],
  382. "label_weight": mapped["label_weight"],
  383. "core_weight": mapped["core_weight"],
  384. "weight_used": mapped["weight_used"],
  385. },
  386. }
  387. )
  388. logger.info("SpoolBuddy tag matched (Spoolman): %s -> spool %d", req.tag_uid, mapped["id"])
  389. return {"status": "ok", "matched": True, "spool_id": mapped["id"]}
  390. except ValueError as exc:
  391. logger.error(
  392. "Spoolman returned malformed spool data during tag lookup for %s: %s",
  393. req.tag_uid,
  394. exc,
  395. )
  396. return {"status": "ok", "matched": False, "spool_id": None}
  397. except (httpx.RequestError, httpx.HTTPStatusError, SpoolmanUnavailableError):
  398. logger.warning(
  399. "Spoolman unreachable during tag lookup for %s",
  400. req.tag_uid,
  401. )
  402. # Broadcast a diagnostic event so the UI can surface "Spoolman down" to the user.
  403. # Use a distinct type from spoolbuddy_unknown_tag — Spoolman outage != unregistered spool.
  404. await ws_manager.broadcast(
  405. {
  406. "type": "spoolman_unavailable",
  407. "device_id": req.device_id,
  408. "context": "nfc_tag_scanned",
  409. }
  410. )
  411. return {"status": "ok", "matched": False, "spool_id": None}
  412. except Exception as exc:
  413. logger.error(
  414. "Spoolman tag lookup failed unexpectedly for %s: %s",
  415. req.tag_uid,
  416. exc,
  417. )
  418. # Broadcast a distinct error event so operators can distinguish
  419. # "unexpected backend error" from "unregistered tag".
  420. await ws_manager.broadcast(
  421. {
  422. "type": "spoolbuddy_lookup_error",
  423. "device_id": req.device_id,
  424. }
  425. )
  426. # Same silent-return policy: an unexpected error must not break device operation
  427. # or trigger spurious duplicate-registration flows in the UI.
  428. return {"status": "ok", "matched": False, "spool_id": None}
  429. await ws_manager.broadcast(
  430. {
  431. "type": "spoolbuddy_unknown_tag",
  432. "device_id": req.device_id,
  433. "tag_uid": req.tag_uid,
  434. "tray_uuid": req.tray_uuid,
  435. "sak": req.sak,
  436. "tag_type": req.tag_type,
  437. }
  438. )
  439. logger.info(
  440. "SpoolBuddy unknown tag: uid=%s (len=%d), tray_uuid=%s (len=%d), type=%s, sak=%s",
  441. req.tag_uid,
  442. len(req.tag_uid or ""),
  443. req.tray_uuid,
  444. len(req.tray_uuid or ""),
  445. req.tag_type,
  446. req.sak,
  447. )
  448. return {"status": "ok", "matched": False, "spool_id": None}
  449. @router.post("/nfc/tag-removed")
  450. async def nfc_tag_removed(
  451. req: TagRemovedRequest,
  452. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  453. ):
  454. """RPi reports NFC tag removed — broadcast event."""
  455. await ws_manager.broadcast(
  456. {
  457. "type": "spoolbuddy_tag_removed",
  458. "device_id": req.device_id,
  459. "tag_uid": req.tag_uid,
  460. }
  461. )
  462. return {"status": "ok"}
  463. @router.post("/nfc/write-tag")
  464. async def nfc_write_tag(
  465. req: WriteTagRequest,
  466. db: AsyncSession = Depends(get_db),
  467. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  468. ):
  469. """Queue an NFC tag write command for a SpoolBuddy device."""
  470. from backend.app.models.spool import Spool
  471. from backend.app.services.opentag3d import encode_opentag3d, encode_opentag3d_from_mapped
  472. # Find the device first (required regardless of spool source)
  473. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  474. device = result.scalar_one_or_none()
  475. if not device:
  476. raise HTTPException(status_code=404, detail="Device not registered")
  477. # Try local DB first
  478. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  479. spool = result.scalar_one_or_none()
  480. nfc_warnings: list[str] = []
  481. if spool:
  482. ndef_data = encode_opentag3d(spool)
  483. data_origin = "local"
  484. else:
  485. # Local DB miss — fall back to Spoolman when enabled
  486. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  487. sm_client = await _get_spoolman_client_or_none(db)
  488. if sm_client is None:
  489. raise HTTPException(status_code=404, detail="Spool not found")
  490. async with _translate_spoolbuddy_errors():
  491. sm_spool = await sm_client.get_spool(req.spool_id)
  492. try:
  493. mapped = _map_spoolman_spool(sm_spool)
  494. except ValueError as exc:
  495. logger.warning("Spoolman returned invalid spool for write-tag: %s", exc)
  496. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data")
  497. if not mapped.get("material"):
  498. raise HTTPException(
  499. status_code=400,
  500. detail="Spoolman spool has no material set — cannot encode NFC tag",
  501. )
  502. ndef_data = encode_opentag3d_from_mapped(mapped)
  503. data_origin = "spoolman"
  504. # Warn when fields that drive NFC content are absent in Spoolman.
  505. if not mapped.get("color_name"):
  506. nfc_warnings.append("color_name not set in Spoolman — tag encodes empty color name")
  507. if not mapped.get("nozzle_temp_min"):
  508. nfc_warnings.append("nozzle_temp_min not set in Spoolman — tag encodes 0 °C")
  509. if not mapped.get("subtype"):
  510. nfc_warnings.append("subtype not set in Spoolman — tag encodes empty subtype")
  511. if not mapped.get("brand"):
  512. nfc_warnings.append("brand/vendor not set in Spoolman — tag encodes empty brand")
  513. if not mapped.get("rgba"):
  514. nfc_warnings.append("rgba not set in Spoolman — tag encodes default colour")
  515. if not mapped.get("label_weight"):
  516. nfc_warnings.append("label_weight not set in Spoolman — tag encodes 0 g")
  517. if nfc_warnings:
  518. logger.warning(
  519. "NFC encode for Spoolman spool %d has incomplete data: %s",
  520. req.spool_id,
  521. "; ".join(nfc_warnings),
  522. )
  523. # Store write payload and set pending command
  524. device.pending_write_payload = json.dumps(
  525. {
  526. "spool_id": req.spool_id,
  527. "ndef_data_hex": ndef_data.hex(),
  528. "data_origin": data_origin,
  529. }
  530. )
  531. device.pending_command = "write_tag"
  532. await db.commit()
  533. logger.info(
  534. "Write tag queued for device %s, spool %d (%s, %d bytes)",
  535. req.device_id,
  536. req.spool_id,
  537. data_origin,
  538. len(ndef_data),
  539. )
  540. result: dict = {"status": "queued"}
  541. if nfc_warnings:
  542. result["warnings"] = nfc_warnings
  543. return result
  544. @router.post("/nfc/write-result")
  545. async def nfc_write_result(
  546. req: WriteTagResultRequest,
  547. db: AsyncSession = Depends(get_db),
  548. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  549. ):
  550. """Handle NFC tag write result from SpoolBuddy daemon."""
  551. # Find the device
  552. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  553. device = result.scalar_one_or_none()
  554. if not device:
  555. raise HTTPException(status_code=404, detail="Device not registered")
  556. # Capture data_origin before clearing the payload
  557. try:
  558. payload_dict = json.loads(device.pending_write_payload or "{}")
  559. except (json.JSONDecodeError, TypeError):
  560. payload_dict = {}
  561. logger.warning("Malformed pending_write_payload for device %s — treating as local", req.device_id)
  562. data_origin = payload_dict.get("data_origin", "local")
  563. device.pending_command = None
  564. device.pending_write_payload = None
  565. if req.success:
  566. if data_origin == "spoolman":
  567. # Update Spoolman extra.tag with the written NFC UID using a safe merge
  568. # (fetches current extra first to avoid overwriting other custom fields).
  569. sm_client = await _get_spoolman_client_or_none(db)
  570. if sm_client is None:
  571. logger.warning("Spoolman not configured; cannot persist tag link for spool %d", req.spool_id)
  572. await db.commit()
  573. await ws_manager.broadcast(
  574. {
  575. "type": "spoolbuddy_tag_link_failed",
  576. "device_id": req.device_id,
  577. "spool_id": req.spool_id,
  578. "tag_uid": req.tag_uid,
  579. "message": "Spoolman not configured",
  580. }
  581. )
  582. raise HTTPException(
  583. status_code=502,
  584. detail="Tag written to NFC but Spoolman is not configured; link not persisted",
  585. )
  586. _tag_link_ok = False
  587. try:
  588. tag_value = json.dumps(req.tag_uid.upper())
  589. await sm_client.merge_spool_extra(req.spool_id, {"tag": tag_value})
  590. logger.info(
  591. "Spoolman tag written and linked: spool %d -> tag %s",
  592. req.spool_id,
  593. req.tag_uid,
  594. )
  595. _tag_link_ok = True
  596. except (SpoolmanNotFoundError, SpoolmanUnavailableError, SpoolmanClientError) as exc:
  597. logger.error(
  598. "Spoolman error during tag write-back for spool %d (type=%s, status=%s): %s",
  599. req.spool_id,
  600. type(exc).__name__,
  601. getattr(exc, "status_code", "N/A"),
  602. exc,
  603. )
  604. # fall through to broadcast + raise 502 below
  605. except Exception:
  606. logger.exception(
  607. "Unexpected error during Spoolman tag write-back for spool %d",
  608. req.spool_id,
  609. )
  610. # fall through to broadcast + raise 502 below
  611. await db.commit()
  612. if _tag_link_ok:
  613. await ws_manager.broadcast(
  614. {
  615. "type": "spoolbuddy_tag_written",
  616. "device_id": req.device_id,
  617. "spool_id": req.spool_id,
  618. "tag_uid": req.tag_uid,
  619. }
  620. )
  621. else:
  622. await ws_manager.broadcast(
  623. {
  624. "type": "spoolbuddy_tag_link_failed",
  625. "device_id": req.device_id,
  626. "spool_id": req.spool_id,
  627. "tag_uid": req.tag_uid,
  628. # Generic message — full exception (may contain internal URLs/hostnames)
  629. # is logged server-side only to prevent information leakage via WebSocket.
  630. "message": "Spoolman link failed",
  631. }
  632. )
  633. raise HTTPException(
  634. status_code=502,
  635. detail="Tag written to NFC but Spoolman link failed",
  636. )
  637. else:
  638. # Link the tag to the local DB spool
  639. from backend.app.models.spool import Spool
  640. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  641. spool = result.scalar_one_or_none()
  642. if spool is None:
  643. logger.warning(
  644. "NFC tag written for spool %d but it no longer exists in local DB; tag is orphaned",
  645. req.spool_id,
  646. )
  647. await db.commit()
  648. await ws_manager.broadcast(
  649. {
  650. "type": "spoolbuddy_tag_link_failed",
  651. "device_id": req.device_id,
  652. "spool_id": req.spool_id,
  653. "message": "Spool not found",
  654. }
  655. )
  656. return {"status": "ok", "linked": False, "message": "Spool not found"}
  657. spool.tag_uid = req.tag_uid.upper()
  658. spool.tag_type = "ntag"
  659. spool.data_origin = "opentag3d"
  660. spool.encode_time = datetime.now(timezone.utc)
  661. logger.info("Tag written and linked: spool %d -> tag %s", spool.id, req.tag_uid)
  662. await db.commit()
  663. await ws_manager.broadcast(
  664. {
  665. "type": "spoolbuddy_tag_written",
  666. "device_id": req.device_id,
  667. "spool_id": req.spool_id,
  668. "tag_uid": req.tag_uid,
  669. }
  670. )
  671. else:
  672. await db.commit()
  673. await ws_manager.broadcast(
  674. {
  675. "type": "spoolbuddy_tag_write_failed",
  676. "device_id": req.device_id,
  677. "spool_id": req.spool_id,
  678. "message": req.message,
  679. }
  680. )
  681. logger.warning("Tag write failed for device %s: %s", req.device_id, req.message)
  682. return {"status": "ok"}
  683. @router.post("/devices/{device_id}/cancel-write")
  684. async def cancel_write(
  685. device_id: str,
  686. db: AsyncSession = Depends(get_db),
  687. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  688. ):
  689. """Cancel a pending write-tag command."""
  690. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  691. device = result.scalar_one_or_none()
  692. if not device:
  693. raise HTTPException(status_code=404, detail="Device not registered")
  694. if device.pending_command == "write_tag":
  695. device.pending_command = None
  696. device.pending_write_payload = None
  697. await db.commit()
  698. logger.info("Write tag cancelled for device %s", device_id)
  699. return {"status": "ok"}
  700. # --- Scale endpoints ---
  701. @router.post("/scale/reading")
  702. async def scale_reading(
  703. req: ScaleReadingRequest,
  704. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  705. ):
  706. """RPi reports scale weight — broadcast to all clients."""
  707. await ws_manager.broadcast(
  708. {
  709. "type": "spoolbuddy_weight",
  710. "device_id": req.device_id,
  711. "weight_grams": req.weight_grams,
  712. "stable": req.stable,
  713. "raw_adc": req.raw_adc,
  714. }
  715. )
  716. return {"status": "ok"}
  717. @router.post("/scale/update-spool-weight")
  718. async def update_spool_weight(
  719. req: UpdateSpoolWeightRequest,
  720. db: AsyncSession = Depends(get_db),
  721. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  722. ):
  723. """Update spool's used weight from scale reading."""
  724. from backend.app.api.routes._spoolman_helpers import _safe_float
  725. from backend.app.models.spool import Spool
  726. # Try local DB first — local spool IDs must not be forwarded to Spoolman.
  727. db_result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  728. spool = db_result.scalar_one_or_none()
  729. if spool:
  730. net_filament = max(0, req.weight_grams - spool.core_weight)
  731. spool.weight_used = max(0, spool.label_weight - net_filament)
  732. spool.last_scale_weight = req.weight_grams
  733. spool.last_weighed_at = datetime.now(timezone.utc)
  734. await db.commit()
  735. logger.info(
  736. "SpoolBuddy updated spool %d weight: %.1fg on scale, %.1fg used",
  737. spool.id,
  738. req.weight_grams,
  739. spool.weight_used,
  740. )
  741. return {"status": "ok", "weight_used": spool.weight_used}
  742. # Local miss — fall back to Spoolman when enabled.
  743. sm_client = await _get_spoolman_client_or_none(db)
  744. if sm_client is None:
  745. raise HTTPException(status_code=404, detail="Spool not found")
  746. async with _translate_spoolbuddy_errors():
  747. sm_spool = await sm_client.get_spool(req.spool_id)
  748. filament = sm_spool.get("filament") or {}
  749. spool_tare = sm_spool.get("spool_weight")
  750. raw_tare = spool_tare if spool_tare is not None else filament.get("spool_weight")
  751. spool_weight_warning: str | None = None
  752. if raw_tare is None:
  753. logger.warning(
  754. "Spoolman spool %d has no spool_weight set; using 250g fallback for tare",
  755. req.spool_id,
  756. )
  757. spool_weight_warning = (
  758. "spool_weight_not_set: Spoolman filament has no spool_weight configured; weight estimate uses 250g fallback"
  759. )
  760. core_weight = _safe_float(raw_tare, 250.0)
  761. label_weight = _safe_float(filament.get("weight"), 1000.0)
  762. remaining_weight = max(0.0, req.weight_grams - core_weight)
  763. async with _translate_spoolbuddy_errors():
  764. await sm_client.update_spool(spool_id=req.spool_id, remaining_weight=remaining_weight)
  765. weight_used = max(0.0, label_weight - remaining_weight)
  766. logger.info(
  767. "SpoolBuddy updated Spoolman spool %d: %.1fg on scale, core=%.1fg → %.1fg remaining",
  768. req.spool_id,
  769. req.weight_grams,
  770. core_weight,
  771. remaining_weight,
  772. )
  773. result: dict = {"status": "ok", "weight_used": weight_used}
  774. if spool_weight_warning:
  775. result["warnings"] = [spool_weight_warning]
  776. return result
  777. # --- Calibration endpoints ---
  778. @router.post("/devices/{device_id}/calibration/tare")
  779. async def tare_scale(
  780. device_id: str,
  781. db: AsyncSession = Depends(get_db),
  782. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  783. ):
  784. """Set pending tare command for the device to pick up."""
  785. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  786. device = result.scalar_one_or_none()
  787. if not device:
  788. raise HTTPException(status_code=404, detail="Device not registered")
  789. device.pending_command = "tare"
  790. await db.commit()
  791. return {"status": "ok", "message": "Tare command queued"}
  792. @router.post("/devices/{device_id}/calibration/set-tare")
  793. async def set_tare_offset(
  794. device_id: str,
  795. req: SetTareRequest,
  796. db: AsyncSession = Depends(get_db),
  797. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  798. ):
  799. """Store tare offset reported by the daemon after executing a tare."""
  800. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  801. device = result.scalar_one_or_none()
  802. if not device:
  803. raise HTTPException(status_code=404, detail="Device not registered")
  804. device.tare_offset = req.tare_offset
  805. device.last_calibrated_at = datetime.now(timezone.utc)
  806. await db.commit()
  807. logger.info("SpoolBuddy %s tare offset set to %d", device_id, req.tare_offset)
  808. return CalibrationResponse(
  809. tare_offset=device.tare_offset,
  810. calibration_factor=device.calibration_factor,
  811. )
  812. @router.post("/devices/{device_id}/calibration/set-factor")
  813. async def set_calibration_factor(
  814. device_id: str,
  815. req: SetCalibrationFactorRequest,
  816. db: AsyncSession = Depends(get_db),
  817. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  818. ):
  819. """Calculate and store calibration factor from a known weight."""
  820. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  821. device = result.scalar_one_or_none()
  822. if not device:
  823. raise HTTPException(status_code=404, detail="Device not registered")
  824. tare = req.tare_raw_adc if req.tare_raw_adc is not None else device.tare_offset
  825. raw_delta = req.raw_adc - tare
  826. if raw_delta == 0:
  827. raise HTTPException(status_code=400, detail="Raw ADC value equals tare offset — place weight on scale")
  828. device.calibration_factor = req.known_weight_grams / raw_delta
  829. if req.tare_raw_adc is not None:
  830. device.tare_offset = tare
  831. device.last_calibrated_at = datetime.now(timezone.utc)
  832. await db.commit()
  833. logger.info(
  834. "SpoolBuddy %s calibration factor set to %.6f (known=%.1fg, raw=%d, tare=%d)",
  835. device_id,
  836. device.calibration_factor,
  837. req.known_weight_grams,
  838. req.raw_adc,
  839. tare,
  840. )
  841. return CalibrationResponse(
  842. tare_offset=device.tare_offset,
  843. calibration_factor=device.calibration_factor,
  844. )
  845. @router.get("/devices/{device_id}/calibration", response_model=CalibrationResponse)
  846. async def get_calibration(
  847. device_id: str,
  848. db: AsyncSession = Depends(get_db),
  849. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  850. ):
  851. """Get current calibration values for a device."""
  852. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  853. device = result.scalar_one_or_none()
  854. if not device:
  855. raise HTTPException(status_code=404, detail="Device not registered")
  856. return CalibrationResponse(
  857. tare_offset=device.tare_offset,
  858. calibration_factor=device.calibration_factor,
  859. )
  860. # --- Display settings ---
  861. @router.get("/devices/{device_id}/display")
  862. async def get_display_settings(
  863. device_id: str,
  864. db: AsyncSession = Depends(get_db),
  865. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  866. ):
  867. """Read current display brightness and screen blank timeout for a device.
  868. Used by the SpoolBuddy kiosk idle watchdog on autostart to configure
  869. swayidle with the same timeout the user picked in the UI, without having
  870. to wait for the daemon heartbeat to arrive first.
  871. """
  872. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  873. device = result.scalar_one_or_none()
  874. if not device:
  875. raise HTTPException(status_code=404, detail="Device not registered")
  876. return {
  877. "brightness": device.display_brightness,
  878. "blank_timeout": device.display_blank_timeout,
  879. }
  880. @router.put("/devices/{device_id}/display")
  881. async def update_display_settings(
  882. device_id: str,
  883. req: DisplaySettingsRequest,
  884. db: AsyncSession = Depends(get_db),
  885. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  886. ):
  887. """Update display brightness and screen blank timeout for a device."""
  888. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  889. device = result.scalar_one_or_none()
  890. if not device:
  891. raise HTTPException(status_code=404, detail="Device not registered")
  892. device.display_brightness = req.brightness
  893. device.display_blank_timeout = req.blank_timeout
  894. await db.commit()
  895. logger.info(
  896. "SpoolBuddy %s display updated: brightness=%d%%, blank_timeout=%ds",
  897. device_id,
  898. req.brightness,
  899. req.blank_timeout,
  900. )
  901. return {"status": "ok", "brightness": req.brightness, "blank_timeout": req.blank_timeout}
  902. @router.post("/devices/{device_id}/system/config")
  903. async def queue_system_config_update(
  904. device_id: str,
  905. req: SystemConfigRequest,
  906. db: AsyncSession = Depends(get_db),
  907. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  908. ):
  909. """Queue update of SpoolBuddy .env config on the device."""
  910. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  911. device = result.scalar_one_or_none()
  912. if not device:
  913. raise HTTPException(status_code=404, detail="Device not registered")
  914. parsed = urlparse(req.backend_url.strip())
  915. if parsed.scheme not in ("http", "https") or not parsed.netloc:
  916. raise HTTPException(
  917. status_code=400,
  918. detail="backend_url must be a full URL with scheme, e.g. http://192.168.1.100:5000 or http://bambuddy.local",
  919. )
  920. payload = {
  921. "backend_url": req.backend_url.strip(),
  922. }
  923. if req.api_key is not None and req.api_key.strip():
  924. payload["api_key"] = req.api_key.strip()
  925. device.pending_system_payload = json.dumps(payload)
  926. device.pending_command = "apply_system_config"
  927. await db.commit()
  928. logger.info("Queued system config update for device %s", device_id)
  929. return {"status": "queued", "message": "System config update queued"}
  930. VALID_SYSTEM_COMMANDS = {"reboot", "shutdown", "restart_daemon", "restart_browser"}
  931. @router.post("/devices/{device_id}/system/command")
  932. async def queue_system_command(
  933. device_id: str,
  934. req: SystemCommandRequest,
  935. db: AsyncSession = Depends(get_db),
  936. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  937. ):
  938. """Queue a system command (reboot, shutdown, restart_daemon, restart_browser) for the SpoolBuddy device."""
  939. if req.command not in VALID_SYSTEM_COMMANDS:
  940. raise HTTPException(
  941. status_code=400,
  942. detail=f"Invalid command. Must be one of: {', '.join(sorted(VALID_SYSTEM_COMMANDS))}",
  943. )
  944. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  945. device = result.scalar_one_or_none()
  946. if not device:
  947. raise HTTPException(status_code=404, detail="Device not registered")
  948. if not _is_online(device):
  949. raise HTTPException(status_code=409, detail="Device is offline")
  950. device.pending_command = req.command
  951. await db.commit()
  952. logger.info("System command queued for device %s: %s", device_id, req.command)
  953. return {"status": "queued", "command": req.command}
  954. @router.post("/devices/{device_id}/system/command-result")
  955. async def system_command_result(
  956. device_id: str,
  957. req: SystemCommandResultRequest,
  958. db: AsyncSession = Depends(get_db),
  959. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  960. ):
  961. """Receive completion status for queued system command from daemon."""
  962. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  963. device = result.scalar_one_or_none()
  964. if not device:
  965. raise HTTPException(status_code=404, detail="Device not registered")
  966. if not device.pending_command:
  967. logger.info("System command result from %s with no pending command: %s", device_id, req.command)
  968. return {"status": "ok", "message": "No pending command"}
  969. if req.command != device.pending_command:
  970. raise HTTPException(
  971. status_code=409,
  972. detail=f"Command mismatch: pending '{device.pending_command}', got '{req.command}'",
  973. )
  974. if req.command == "apply_system_config":
  975. device.pending_system_payload = None
  976. device.pending_command = None
  977. await db.commit()
  978. logger.info(
  979. "System command result from %s: %s success=%s message=%s",
  980. device_id,
  981. req.command,
  982. req.success,
  983. req.message,
  984. )
  985. return {"status": "ok"}
  986. # --- Diagnostics ---
  987. @router.post("/diagnostics/{device_id}/run")
  988. async def queue_diagnostic(
  989. device_id: str,
  990. diagnostic: str,
  991. db: AsyncSession = Depends(get_db),
  992. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  993. ):
  994. """Queue a hardware diagnostic to run on the SpoolBuddy device.
  995. Args:
  996. device_id: The device ID
  997. diagnostic: 'scale' or 'nfc' to select which diagnostic to run
  998. Returns:
  999. Status message indicating diagnostic was queued
  1000. """
  1001. if diagnostic not in ("scale", "nfc", "read_tag"):
  1002. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1003. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1004. device = result.scalar_one_or_none()
  1005. if not device:
  1006. raise HTTPException(status_code=404, detail="Device not registered")
  1007. device.pending_command = f"run_{diagnostic}_diag"
  1008. _diagnostic_results.pop((device_id, diagnostic), None)
  1009. await db.commit()
  1010. logger.info("Diagnostic queued for device %s: %s", device_id, diagnostic)
  1011. return {"status": "queued", "diagnostic": diagnostic, "message": f"Diagnostic '{diagnostic}' queued for device"}
  1012. @router.get("/diagnostics/{device_id}/result")
  1013. async def get_diagnostic_result(
  1014. device_id: str,
  1015. diagnostic: str,
  1016. db: AsyncSession = Depends(get_db),
  1017. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1018. ):
  1019. """Get the latest diagnostic result for a device.
  1020. Args:
  1021. device_id: The device ID
  1022. diagnostic: 'scale' or 'nfc'
  1023. Returns:
  1024. Diagnostic result or 404 if not found
  1025. """
  1026. if diagnostic not in ("scale", "nfc", "read_tag"):
  1027. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1028. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1029. device = result.scalar_one_or_none()
  1030. if not device:
  1031. raise HTTPException(status_code=404, detail="Device not registered")
  1032. diag_result = _diagnostic_results.get((device_id, diagnostic))
  1033. if not diag_result:
  1034. raise HTTPException(status_code=404, detail=f"No {diagnostic} diagnostic results available yet")
  1035. return diag_result
  1036. @router.post("/diagnostics/{device_id}/result")
  1037. async def report_diagnostic_result(
  1038. device_id: str,
  1039. req: DiagnosticResultRequest,
  1040. db: AsyncSession = Depends(get_db),
  1041. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1042. ):
  1043. """Report diagnostic result from SpoolBuddy device."""
  1044. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1045. device = result.scalar_one_or_none()
  1046. if not device:
  1047. raise HTTPException(status_code=404, detail="Device not registered")
  1048. if req.diagnostic not in ("nfc", "scale", "read_tag"):
  1049. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1050. _diagnostic_results[(device_id, req.diagnostic)] = {
  1051. "diagnostic": req.diagnostic,
  1052. "success": req.success,
  1053. "output": req.output,
  1054. "exit_code": req.exit_code,
  1055. }
  1056. device.pending_command = None
  1057. await db.commit()
  1058. logger.info("Diagnostic result received for device %s: %s (success=%s)", device_id, req.diagnostic, req.success)
  1059. return {"status": "ok", "message": "Diagnostic result recorded"}
  1060. # --- Update check ---
  1061. @router.get("/devices/{device_id}/update-check")
  1062. async def check_daemon_update(
  1063. device_id: str,
  1064. db: AsyncSession = Depends(get_db),
  1065. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1066. ):
  1067. """Check if the SpoolBuddy daemon needs updating to match the Bambuddy backend version."""
  1068. from backend.app.api.routes.updates import is_newer_version
  1069. from backend.app.core.config import APP_VERSION
  1070. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1071. device = result.scalar_one_or_none()
  1072. if not device:
  1073. raise HTTPException(status_code=404, detail="Device not registered")
  1074. current = device.firmware_version or "0.0.0"
  1075. return {
  1076. "current_version": current,
  1077. "latest_version": APP_VERSION,
  1078. "update_available": is_newer_version(APP_VERSION, current),
  1079. }
  1080. @router.post("/devices/{device_id}/update")
  1081. async def trigger_daemon_update(
  1082. device_id: str,
  1083. req: dict | None = None,
  1084. db: AsyncSession = Depends(get_db),
  1085. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1086. ):
  1087. """Trigger a SpoolBuddy update over SSH.
  1088. Bambuddy SSHes into the device, pulls the matching branch, installs deps,
  1089. and restarts the daemon. Progress is broadcast via WebSocket.
  1090. """
  1091. from backend.app.services.spoolbuddy_ssh import perform_ssh_update
  1092. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1093. device = result.scalar_one_or_none()
  1094. if not device:
  1095. raise HTTPException(status_code=404, detail="Device not registered")
  1096. if not _is_online(device):
  1097. raise HTTPException(status_code=409, detail="Device is offline")
  1098. if device.update_status == "updating":
  1099. return {"status": "already_updating", "message": "Update already in progress"}
  1100. device.update_status = "pending"
  1101. device.update_message = "Starting SSH update..."
  1102. await db.commit()
  1103. logger.info("SpoolBuddy %s: SSH update triggered (ip=%s)", device_id, device.ip_address)
  1104. await ws_manager.broadcast(
  1105. {
  1106. "type": "spoolbuddy_update",
  1107. "device_id": device_id,
  1108. "update_status": "pending",
  1109. }
  1110. )
  1111. # Run the SSH update in the background — hold reference to prevent GC cancellation
  1112. _ssh_update_task = asyncio.create_task(perform_ssh_update(device_id, device.ip_address))
  1113. _ssh_update_task.add_done_callback(
  1114. lambda t: logger.error(
  1115. "SSH update task for device %s ended unexpectedly (cancelled=%s)",
  1116. device_id,
  1117. t.cancelled(),
  1118. )
  1119. if (t.cancelled() or t.exception() is not None)
  1120. else None
  1121. )
  1122. return {"status": "ok", "message": "SSH update started"}
  1123. @router.get("/ssh/public-key")
  1124. async def get_ssh_public_key(
  1125. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1126. ):
  1127. """Return the SSH public key for SpoolBuddy pairing."""
  1128. from backend.app.services.spoolbuddy_ssh import get_public_key
  1129. try:
  1130. key = await get_public_key()
  1131. return {"public_key": key}
  1132. except Exception as e:
  1133. logger.error("Failed to get SSH public key: %s", e)
  1134. raise HTTPException(status_code=500, detail="Failed to retrieve SSH public key") from e
  1135. @router.post("/devices/{device_id}/update-status")
  1136. async def report_update_status(
  1137. device_id: str,
  1138. req: UpdateStatusRequest,
  1139. db: AsyncSession = Depends(get_db),
  1140. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1141. ):
  1142. """Daemon reports update progress back to the backend."""
  1143. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1144. device = result.scalar_one_or_none()
  1145. if not device:
  1146. raise HTTPException(status_code=404, detail="Device not registered")
  1147. device.update_status = req.status
  1148. device.update_message = req.message
  1149. # Only "complete" clears pending_command here. "error" leaves it set so the user can retry
  1150. # via the UI. The SSH service's own _update_progress clears on both "complete" and "error"
  1151. # because it owns the full update lifecycle end-to-end.
  1152. if req.status == "complete":
  1153. device.pending_command = None
  1154. await db.commit()
  1155. logger.info("SpoolBuddy %s: update status=%s msg=%s", device_id, req.status, req.message)
  1156. await ws_manager.broadcast(
  1157. {
  1158. "type": "spoolbuddy_update",
  1159. "device_id": device_id,
  1160. "update_status": req.status,
  1161. "update_message": req.message,
  1162. }
  1163. )
  1164. return {"status": "ok"}
  1165. # --- Background watchdog ---
  1166. async def spoolbuddy_watchdog():
  1167. """Check for devices that have gone offline (no heartbeat for 30s).
  1168. Called periodically from the main app's background task loop.
  1169. """
  1170. from backend.app.core.database import async_session
  1171. async with async_session() as db:
  1172. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.last_seen.isnot(None)))
  1173. devices = list(result.scalars().all())
  1174. threshold = datetime.now(timezone.utc) - timedelta(seconds=OFFLINE_THRESHOLD_SECONDS)
  1175. for device in devices:
  1176. last_seen = device.last_seen.replace(tzinfo=timezone.utc) if device.last_seen else None
  1177. if last_seen and last_seen < threshold:
  1178. # Only broadcast once — clear last_seen after marking offline
  1179. await ws_manager.broadcast(
  1180. {
  1181. "type": "spoolbuddy_offline",
  1182. "device_id": device.device_id,
  1183. }
  1184. )
  1185. device.last_seen = None
  1186. logger.info("SpoolBuddy device offline: %s", device.device_id)
  1187. await db.commit()