spoolbuddy.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. """SpoolBuddy device management API routes."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. from datetime import datetime, timedelta, timezone
  7. from urllib.parse import urlparse
  8. from fastapi import APIRouter, Depends, HTTPException
  9. from sqlalchemy import select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  12. from backend.app.core.database import get_db
  13. from backend.app.core.permissions import Permission
  14. from backend.app.core.websocket import ws_manager
  15. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  16. from backend.app.models.user import User
  17. from backend.app.schemas.spoolbuddy import (
  18. CalibrationResponse,
  19. DeviceRegisterRequest,
  20. DeviceResponse,
  21. DiagnosticResultRequest,
  22. DisplaySettingsRequest,
  23. HeartbeatRequest,
  24. HeartbeatResponse,
  25. ScaleReadingRequest,
  26. SetCalibrationFactorRequest,
  27. SetTareRequest,
  28. SystemCommandRequest,
  29. SystemCommandResultRequest,
  30. SystemConfigRequest,
  31. TagRemovedRequest,
  32. TagScannedRequest,
  33. UpdateSpoolWeightRequest,
  34. WriteTagRequest,
  35. WriteTagResultRequest,
  36. )
  37. from backend.app.services.spool_tag_matcher import get_spool_by_tag
  38. logger = logging.getLogger(__name__)
  39. router = APIRouter(prefix="/spoolbuddy", tags=["spoolbuddy"])
  40. OFFLINE_THRESHOLD_SECONDS = 30
  41. ONLINE_BROADCAST_INTERVAL_SECONDS = 10
  42. _spoolbuddy_online_last_broadcast: dict[str, float] = {}
  43. _diagnostic_results: dict[tuple[str, str], dict] = {}
  44. def _is_online(device: SpoolBuddyDevice) -> bool:
  45. if not device.last_seen:
  46. return False
  47. return (
  48. datetime.now(timezone.utc) - device.last_seen.replace(tzinfo=timezone.utc)
  49. ).total_seconds() < OFFLINE_THRESHOLD_SECONDS
  50. def _device_to_response(device: SpoolBuddyDevice) -> DeviceResponse:
  51. return DeviceResponse(
  52. id=device.id,
  53. device_id=device.device_id,
  54. hostname=device.hostname,
  55. ip_address=device.ip_address,
  56. firmware_version=device.firmware_version,
  57. has_nfc=device.has_nfc,
  58. has_scale=device.has_scale,
  59. tare_offset=device.tare_offset,
  60. calibration_factor=device.calibration_factor,
  61. nfc_reader_type=device.nfc_reader_type,
  62. nfc_connection=device.nfc_connection,
  63. backend_url=device.backend_url,
  64. display_brightness=device.display_brightness,
  65. display_blank_timeout=device.display_blank_timeout,
  66. has_backlight=device.has_backlight,
  67. last_calibrated_at=device.last_calibrated_at,
  68. last_seen=device.last_seen,
  69. pending_command=device.pending_command,
  70. nfc_ok=device.nfc_ok,
  71. scale_ok=device.scale_ok,
  72. uptime_s=device.uptime_s,
  73. update_status=device.update_status,
  74. update_message=device.update_message,
  75. system_stats=json.loads(device.system_stats) if device.system_stats else None,
  76. online=_is_online(device),
  77. created_at=device.created_at,
  78. updated_at=device.updated_at,
  79. )
  80. def _should_broadcast_online(device_id: str, force: bool = False) -> bool:
  81. if force:
  82. _spoolbuddy_online_last_broadcast[device_id] = time.time()
  83. return True
  84. now_ts = time.time()
  85. last_ts = _spoolbuddy_online_last_broadcast.get(device_id, 0.0)
  86. if now_ts - last_ts >= ONLINE_BROADCAST_INTERVAL_SECONDS:
  87. _spoolbuddy_online_last_broadcast[device_id] = now_ts
  88. return True
  89. return False
  90. # --- Device endpoints ---
  91. @router.post("/devices/register", response_model=DeviceResponse)
  92. async def register_device(
  93. req: DeviceRegisterRequest,
  94. db: AsyncSession = Depends(get_db),
  95. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  96. ):
  97. """Register or re-register a SpoolBuddy device."""
  98. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  99. device = result.scalar_one_or_none()
  100. now = datetime.now(timezone.utc)
  101. if device:
  102. device.hostname = req.hostname
  103. device.ip_address = req.ip_address
  104. device.firmware_version = req.firmware_version
  105. device.has_nfc = req.has_nfc
  106. device.has_scale = req.has_scale
  107. device.nfc_reader_type = req.nfc_reader_type
  108. device.nfc_connection = req.nfc_connection
  109. if req.backend_url:
  110. device.backend_url = req.backend_url
  111. device.has_backlight = req.has_backlight
  112. device.last_seen = now
  113. # Clear stale update status on re-registration (daemon restarted after update)
  114. if device.update_status in ("pending", "updating", "complete", "error"):
  115. device.update_status = None
  116. device.update_message = None
  117. logger.info("SpoolBuddy device re-registered: %s (%s)", req.device_id, req.hostname)
  118. else:
  119. device = SpoolBuddyDevice(
  120. device_id=req.device_id,
  121. hostname=req.hostname,
  122. ip_address=req.ip_address,
  123. firmware_version=req.firmware_version,
  124. has_nfc=req.has_nfc,
  125. has_scale=req.has_scale,
  126. tare_offset=req.tare_offset,
  127. calibration_factor=req.calibration_factor,
  128. nfc_reader_type=req.nfc_reader_type,
  129. nfc_connection=req.nfc_connection,
  130. has_backlight=req.has_backlight,
  131. backend_url=req.backend_url,
  132. last_seen=now,
  133. )
  134. db.add(device)
  135. logger.info("SpoolBuddy device registered: %s (%s)", req.device_id, req.hostname)
  136. await db.commit()
  137. await db.refresh(device)
  138. _spoolbuddy_online_last_broadcast[device.device_id] = time.time()
  139. await ws_manager.broadcast(
  140. {
  141. "type": "spoolbuddy_online",
  142. "device_id": device.device_id,
  143. "hostname": device.hostname,
  144. }
  145. )
  146. response = _device_to_response(device)
  147. # Include SSH public key so the daemon can auto-deploy it
  148. try:
  149. from backend.app.services.spoolbuddy_ssh import get_public_key
  150. response.ssh_public_key = await get_public_key()
  151. except Exception:
  152. pass # Key not generated yet — daemon can still work without it
  153. return response
  154. @router.get("/devices", response_model=list[DeviceResponse])
  155. async def list_devices(
  156. db: AsyncSession = Depends(get_db),
  157. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  158. ):
  159. """List all registered SpoolBuddy devices."""
  160. result = await db.execute(select(SpoolBuddyDevice).order_by(SpoolBuddyDevice.hostname))
  161. devices = list(result.scalars().all())
  162. return [_device_to_response(d) for d in devices]
  163. @router.post("/devices/{device_id}/heartbeat", response_model=HeartbeatResponse)
  164. async def device_heartbeat(
  165. device_id: str,
  166. req: HeartbeatRequest,
  167. db: AsyncSession = Depends(get_db),
  168. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  169. ):
  170. """Daemon heartbeat — updates status and returns pending commands."""
  171. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  172. device = result.scalar_one_or_none()
  173. if not device:
  174. raise HTTPException(status_code=404, detail="Device not registered")
  175. was_offline = not _is_online(device)
  176. now = datetime.now(timezone.utc)
  177. device.last_seen = now
  178. device.nfc_ok = req.nfc_ok
  179. device.scale_ok = req.scale_ok
  180. device.uptime_s = req.uptime_s
  181. if req.firmware_version:
  182. device.firmware_version = req.firmware_version
  183. if req.ip_address:
  184. device.ip_address = req.ip_address
  185. if req.nfc_reader_type:
  186. device.nfc_reader_type = req.nfc_reader_type
  187. if req.nfc_connection:
  188. device.nfc_connection = req.nfc_connection
  189. if req.backend_url:
  190. device.backend_url = req.backend_url
  191. if req.system_stats is not None:
  192. device.system_stats = json.dumps(req.system_stats)
  193. # Return and clear pending command
  194. pending = device.pending_command
  195. pending_write = None
  196. pending_system = None
  197. if pending == "write_tag" and device.pending_write_payload:
  198. # Parse the stored JSON payload to include in response
  199. try:
  200. pending_write = json.loads(device.pending_write_payload)
  201. except (json.JSONDecodeError, TypeError):
  202. pending_write = None
  203. # Don't clear write_tag command — it gets cleared by write-result
  204. elif pending == "apply_system_config" and device.pending_system_payload:
  205. try:
  206. pending_system = json.loads(device.pending_system_payload)
  207. except (json.JSONDecodeError, TypeError):
  208. pending_system = None
  209. # Don't clear config command — it gets cleared by daemon command-result callback
  210. elif pending and pending.startswith("run_") and pending.endswith("_diag"):
  211. # Don't clear diagnostic commands — they get cleared by the device reporting results
  212. pass
  213. else:
  214. device.pending_command = None
  215. await db.commit()
  216. # Emit online presence on offline->online transitions immediately, and
  217. # periodically while online so newly connected UIs can bootstrap state.
  218. if _should_broadcast_online(device.device_id, force=was_offline):
  219. await ws_manager.broadcast(
  220. {
  221. "type": "spoolbuddy_online",
  222. "device_id": device.device_id,
  223. "hostname": device.hostname,
  224. }
  225. )
  226. if was_offline:
  227. logger.info("SpoolBuddy device back online: %s", device.device_id)
  228. return HeartbeatResponse(
  229. pending_command=pending,
  230. pending_write_payload=pending_write,
  231. pending_system_payload=pending_system,
  232. tare_offset=device.tare_offset,
  233. calibration_factor=device.calibration_factor,
  234. display_brightness=device.display_brightness,
  235. display_blank_timeout=device.display_blank_timeout,
  236. )
  237. # --- NFC endpoints ---
  238. @router.post("/nfc/tag-scanned")
  239. async def nfc_tag_scanned(
  240. req: TagScannedRequest,
  241. db: AsyncSession = Depends(get_db),
  242. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  243. ):
  244. """RPi reports NFC tag detected — lookup spool and broadcast."""
  245. spool = await get_spool_by_tag(db, req.tag_uid, req.tray_uuid or "")
  246. if spool:
  247. await ws_manager.broadcast(
  248. {
  249. "type": "spoolbuddy_tag_matched",
  250. "device_id": req.device_id,
  251. "tag_uid": req.tag_uid,
  252. "spool": {
  253. "id": spool.id,
  254. "material": spool.material,
  255. "subtype": spool.subtype,
  256. "color_name": spool.color_name,
  257. "rgba": spool.rgba,
  258. "brand": spool.brand,
  259. "label_weight": spool.label_weight,
  260. "core_weight": spool.core_weight,
  261. "weight_used": spool.weight_used,
  262. },
  263. }
  264. )
  265. logger.info("SpoolBuddy tag matched: %s -> spool %d", req.tag_uid, spool.id)
  266. else:
  267. await ws_manager.broadcast(
  268. {
  269. "type": "spoolbuddy_unknown_tag",
  270. "device_id": req.device_id,
  271. "tag_uid": req.tag_uid,
  272. "sak": req.sak,
  273. "tag_type": req.tag_type,
  274. }
  275. )
  276. logger.info(
  277. "SpoolBuddy unknown tag: uid=%s (len=%d), tray_uuid=%s (len=%d), type=%s, sak=%s",
  278. req.tag_uid,
  279. len(req.tag_uid or ""),
  280. req.tray_uuid,
  281. len(req.tray_uuid or ""),
  282. req.tag_type,
  283. req.sak,
  284. )
  285. return {"status": "ok", "matched": spool is not None, "spool_id": spool.id if spool else None}
  286. @router.post("/nfc/tag-removed")
  287. async def nfc_tag_removed(
  288. req: TagRemovedRequest,
  289. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  290. ):
  291. """RPi reports NFC tag removed — broadcast event."""
  292. await ws_manager.broadcast(
  293. {
  294. "type": "spoolbuddy_tag_removed",
  295. "device_id": req.device_id,
  296. "tag_uid": req.tag_uid,
  297. }
  298. )
  299. return {"status": "ok"}
  300. @router.post("/nfc/write-tag")
  301. async def nfc_write_tag(
  302. req: WriteTagRequest,
  303. db: AsyncSession = Depends(get_db),
  304. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  305. ):
  306. """Queue an NFC tag write command for a SpoolBuddy device."""
  307. import json
  308. from backend.app.models.spool import Spool
  309. from backend.app.services.opentag3d import encode_opentag3d
  310. # Find the spool
  311. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  312. spool = result.scalar_one_or_none()
  313. if not spool:
  314. raise HTTPException(status_code=404, detail="Spool not found")
  315. # Find the device
  316. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  317. device = result.scalar_one_or_none()
  318. if not device:
  319. raise HTTPException(status_code=404, detail="Device not registered")
  320. # Encode OpenTag3D NDEF data
  321. ndef_data = encode_opentag3d(spool)
  322. # Store write payload and set pending command
  323. device.pending_write_payload = json.dumps(
  324. {
  325. "spool_id": spool.id,
  326. "ndef_data_hex": ndef_data.hex(),
  327. }
  328. )
  329. device.pending_command = "write_tag"
  330. await db.commit()
  331. logger.info("Write tag queued for device %s, spool %d (%d bytes)", req.device_id, spool.id, len(ndef_data))
  332. return {"status": "queued"}
  333. @router.post("/nfc/write-result")
  334. async def nfc_write_result(
  335. req: WriteTagResultRequest,
  336. db: AsyncSession = Depends(get_db),
  337. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  338. ):
  339. """Handle NFC tag write result from SpoolBuddy daemon."""
  340. # Find the device and clear pending state
  341. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  342. device = result.scalar_one_or_none()
  343. if not device:
  344. raise HTTPException(status_code=404, detail="Device not registered")
  345. device.pending_command = None
  346. device.pending_write_payload = None
  347. if req.success:
  348. # Link the tag to the spool
  349. from backend.app.models.spool import Spool
  350. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  351. spool = result.scalar_one_or_none()
  352. if spool:
  353. spool.tag_uid = req.tag_uid.upper()
  354. spool.tag_type = "ntag"
  355. spool.data_origin = "opentag3d"
  356. spool.encode_time = datetime.now(timezone.utc)
  357. logger.info("Tag written and linked: spool %d -> tag %s", spool.id, req.tag_uid)
  358. await db.commit()
  359. await ws_manager.broadcast(
  360. {
  361. "type": "spoolbuddy_tag_written",
  362. "device_id": req.device_id,
  363. "spool_id": req.spool_id,
  364. "tag_uid": req.tag_uid,
  365. }
  366. )
  367. else:
  368. await db.commit()
  369. await ws_manager.broadcast(
  370. {
  371. "type": "spoolbuddy_tag_write_failed",
  372. "device_id": req.device_id,
  373. "spool_id": req.spool_id,
  374. "message": req.message,
  375. }
  376. )
  377. logger.warning("Tag write failed for device %s: %s", req.device_id, req.message)
  378. return {"status": "ok"}
  379. @router.post("/devices/{device_id}/cancel-write")
  380. async def cancel_write(
  381. device_id: str,
  382. db: AsyncSession = Depends(get_db),
  383. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  384. ):
  385. """Cancel a pending write-tag command."""
  386. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  387. device = result.scalar_one_or_none()
  388. if not device:
  389. raise HTTPException(status_code=404, detail="Device not registered")
  390. if device.pending_command == "write_tag":
  391. device.pending_command = None
  392. device.pending_write_payload = None
  393. await db.commit()
  394. logger.info("Write tag cancelled for device %s", device_id)
  395. return {"status": "ok"}
  396. # --- Scale endpoints ---
  397. @router.post("/scale/reading")
  398. async def scale_reading(
  399. req: ScaleReadingRequest,
  400. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  401. ):
  402. """RPi reports scale weight — broadcast to all clients."""
  403. await ws_manager.broadcast(
  404. {
  405. "type": "spoolbuddy_weight",
  406. "device_id": req.device_id,
  407. "weight_grams": req.weight_grams,
  408. "stable": req.stable,
  409. "raw_adc": req.raw_adc,
  410. }
  411. )
  412. return {"status": "ok"}
  413. @router.post("/scale/update-spool-weight")
  414. async def update_spool_weight(
  415. req: UpdateSpoolWeightRequest,
  416. db: AsyncSession = Depends(get_db),
  417. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  418. ):
  419. """Update spool's used weight from scale reading."""
  420. from backend.app.models.spool import Spool
  421. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  422. spool = result.scalar_one_or_none()
  423. if not spool:
  424. raise HTTPException(status_code=404, detail="Spool not found")
  425. # net weight = total on scale minus empty spool core
  426. net_filament = max(0, req.weight_grams - spool.core_weight)
  427. spool.weight_used = max(0, spool.label_weight - net_filament)
  428. spool.last_scale_weight = req.weight_grams
  429. spool.last_weighed_at = datetime.now(timezone.utc)
  430. await db.commit()
  431. logger.info(
  432. "SpoolBuddy updated spool %d weight: %.1fg on scale, %.1fg used",
  433. spool.id,
  434. req.weight_grams,
  435. spool.weight_used,
  436. )
  437. return {"status": "ok", "weight_used": spool.weight_used}
  438. # --- Calibration endpoints ---
  439. @router.post("/devices/{device_id}/calibration/tare")
  440. async def tare_scale(
  441. device_id: str,
  442. db: AsyncSession = Depends(get_db),
  443. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  444. ):
  445. """Set pending tare command for the device to pick up."""
  446. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  447. device = result.scalar_one_or_none()
  448. if not device:
  449. raise HTTPException(status_code=404, detail="Device not registered")
  450. device.pending_command = "tare"
  451. await db.commit()
  452. return {"status": "ok", "message": "Tare command queued"}
  453. @router.post("/devices/{device_id}/calibration/set-tare")
  454. async def set_tare_offset(
  455. device_id: str,
  456. req: SetTareRequest,
  457. db: AsyncSession = Depends(get_db),
  458. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  459. ):
  460. """Store tare offset reported by the daemon after executing a tare."""
  461. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  462. device = result.scalar_one_or_none()
  463. if not device:
  464. raise HTTPException(status_code=404, detail="Device not registered")
  465. device.tare_offset = req.tare_offset
  466. device.last_calibrated_at = datetime.now(timezone.utc)
  467. await db.commit()
  468. logger.info("SpoolBuddy %s tare offset set to %d", device_id, req.tare_offset)
  469. return CalibrationResponse(
  470. tare_offset=device.tare_offset,
  471. calibration_factor=device.calibration_factor,
  472. )
  473. @router.post("/devices/{device_id}/calibration/set-factor")
  474. async def set_calibration_factor(
  475. device_id: str,
  476. req: SetCalibrationFactorRequest,
  477. db: AsyncSession = Depends(get_db),
  478. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  479. ):
  480. """Calculate and store calibration factor from a known weight."""
  481. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  482. device = result.scalar_one_or_none()
  483. if not device:
  484. raise HTTPException(status_code=404, detail="Device not registered")
  485. tare = req.tare_raw_adc if req.tare_raw_adc is not None else device.tare_offset
  486. raw_delta = req.raw_adc - tare
  487. if raw_delta == 0:
  488. raise HTTPException(status_code=400, detail="Raw ADC value equals tare offset — place weight on scale")
  489. device.calibration_factor = req.known_weight_grams / raw_delta
  490. if req.tare_raw_adc is not None:
  491. device.tare_offset = tare
  492. device.last_calibrated_at = datetime.now(timezone.utc)
  493. await db.commit()
  494. logger.info(
  495. "SpoolBuddy %s calibration factor set to %.6f (known=%.1fg, raw=%d, tare=%d)",
  496. device_id,
  497. device.calibration_factor,
  498. req.known_weight_grams,
  499. req.raw_adc,
  500. tare,
  501. )
  502. return CalibrationResponse(
  503. tare_offset=device.tare_offset,
  504. calibration_factor=device.calibration_factor,
  505. )
  506. @router.get("/devices/{device_id}/calibration", response_model=CalibrationResponse)
  507. async def get_calibration(
  508. device_id: str,
  509. db: AsyncSession = Depends(get_db),
  510. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  511. ):
  512. """Get current calibration values for a device."""
  513. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  514. device = result.scalar_one_or_none()
  515. if not device:
  516. raise HTTPException(status_code=404, detail="Device not registered")
  517. return CalibrationResponse(
  518. tare_offset=device.tare_offset,
  519. calibration_factor=device.calibration_factor,
  520. )
  521. # --- Display settings ---
  522. @router.put("/devices/{device_id}/display")
  523. async def update_display_settings(
  524. device_id: str,
  525. req: DisplaySettingsRequest,
  526. db: AsyncSession = Depends(get_db),
  527. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  528. ):
  529. """Update display brightness and screen blank timeout for a device."""
  530. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  531. device = result.scalar_one_or_none()
  532. if not device:
  533. raise HTTPException(status_code=404, detail="Device not registered")
  534. device.display_brightness = req.brightness
  535. device.display_blank_timeout = req.blank_timeout
  536. await db.commit()
  537. logger.info(
  538. "SpoolBuddy %s display updated: brightness=%d%%, blank_timeout=%ds",
  539. device_id,
  540. req.brightness,
  541. req.blank_timeout,
  542. )
  543. return {"status": "ok", "brightness": req.brightness, "blank_timeout": req.blank_timeout}
  544. @router.post("/devices/{device_id}/system/config")
  545. async def queue_system_config_update(
  546. device_id: str,
  547. req: SystemConfigRequest,
  548. db: AsyncSession = Depends(get_db),
  549. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  550. ):
  551. """Queue update of SpoolBuddy .env config on the device."""
  552. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  553. device = result.scalar_one_or_none()
  554. if not device:
  555. raise HTTPException(status_code=404, detail="Device not registered")
  556. parsed = urlparse(req.backend_url.strip())
  557. if parsed.scheme not in ("http", "https") or not parsed.netloc:
  558. raise HTTPException(
  559. status_code=400,
  560. detail="backend_url must be a full URL with scheme, e.g. http://192.168.1.100:5000 or http://bambuddy.local",
  561. )
  562. payload = {
  563. "backend_url": req.backend_url.strip(),
  564. }
  565. if req.api_key is not None and req.api_key.strip():
  566. payload["api_key"] = req.api_key.strip()
  567. device.pending_system_payload = json.dumps(payload)
  568. device.pending_command = "apply_system_config"
  569. await db.commit()
  570. logger.info("Queued system config update for device %s", device_id)
  571. return {"status": "queued", "message": "System config update queued"}
  572. VALID_SYSTEM_COMMANDS = {"reboot", "shutdown", "restart_daemon", "restart_browser"}
  573. @router.post("/devices/{device_id}/system/command")
  574. async def queue_system_command(
  575. device_id: str,
  576. req: SystemCommandRequest,
  577. db: AsyncSession = Depends(get_db),
  578. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  579. ):
  580. """Queue a system command (reboot, shutdown, restart_daemon, restart_browser) for the SpoolBuddy device."""
  581. if req.command not in VALID_SYSTEM_COMMANDS:
  582. raise HTTPException(
  583. status_code=400,
  584. detail=f"Invalid command. Must be one of: {', '.join(sorted(VALID_SYSTEM_COMMANDS))}",
  585. )
  586. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  587. device = result.scalar_one_or_none()
  588. if not device:
  589. raise HTTPException(status_code=404, detail="Device not registered")
  590. if not _is_online(device):
  591. raise HTTPException(status_code=409, detail="Device is offline")
  592. device.pending_command = req.command
  593. await db.commit()
  594. logger.info("System command queued for device %s: %s", device_id, req.command)
  595. return {"status": "queued", "command": req.command}
  596. @router.post("/devices/{device_id}/system/command-result")
  597. async def system_command_result(
  598. device_id: str,
  599. req: SystemCommandResultRequest,
  600. db: AsyncSession = Depends(get_db),
  601. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  602. ):
  603. """Receive completion status for queued system command from daemon."""
  604. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  605. device = result.scalar_one_or_none()
  606. if not device:
  607. raise HTTPException(status_code=404, detail="Device not registered")
  608. if not device.pending_command:
  609. logger.info("System command result from %s with no pending command: %s", device_id, req.command)
  610. return {"status": "ok", "message": "No pending command"}
  611. if req.command != device.pending_command:
  612. raise HTTPException(
  613. status_code=409,
  614. detail=f"Command mismatch: pending '{device.pending_command}', got '{req.command}'",
  615. )
  616. if req.command == "apply_system_config":
  617. device.pending_system_payload = None
  618. device.pending_command = None
  619. await db.commit()
  620. logger.info(
  621. "System command result from %s: %s success=%s message=%s",
  622. device_id,
  623. req.command,
  624. req.success,
  625. req.message,
  626. )
  627. return {"status": "ok"}
  628. # --- Diagnostics ---
  629. @router.post("/diagnostics/{device_id}/run")
  630. async def queue_diagnostic(
  631. device_id: str,
  632. diagnostic: str,
  633. db: AsyncSession = Depends(get_db),
  634. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  635. ):
  636. """Queue a hardware diagnostic to run on the SpoolBuddy device.
  637. Args:
  638. device_id: The device ID
  639. diagnostic: 'scale' or 'nfc' to select which diagnostic to run
  640. Returns:
  641. Status message indicating diagnostic was queued
  642. """
  643. if diagnostic not in ("scale", "nfc", "read_tag"):
  644. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  645. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  646. device = result.scalar_one_or_none()
  647. if not device:
  648. raise HTTPException(status_code=404, detail="Device not registered")
  649. device.pending_command = f"run_{diagnostic}_diag"
  650. _diagnostic_results.pop((device_id, diagnostic), None)
  651. await db.commit()
  652. logger.info("Diagnostic queued for device %s: %s", device_id, diagnostic)
  653. return {"status": "queued", "diagnostic": diagnostic, "message": f"Diagnostic '{diagnostic}' queued for device"}
  654. @router.get("/diagnostics/{device_id}/result")
  655. async def get_diagnostic_result(
  656. device_id: str,
  657. diagnostic: str,
  658. db: AsyncSession = Depends(get_db),
  659. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  660. ):
  661. """Get the latest diagnostic result for a device.
  662. Args:
  663. device_id: The device ID
  664. diagnostic: 'scale' or 'nfc'
  665. Returns:
  666. Diagnostic result or 404 if not found
  667. """
  668. if diagnostic not in ("scale", "nfc", "read_tag"):
  669. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  670. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  671. device = result.scalar_one_or_none()
  672. if not device:
  673. raise HTTPException(status_code=404, detail="Device not registered")
  674. diag_result = _diagnostic_results.get((device_id, diagnostic))
  675. if not diag_result:
  676. raise HTTPException(status_code=404, detail=f"No {diagnostic} diagnostic results available yet")
  677. return diag_result
  678. @router.post("/diagnostics/{device_id}/result")
  679. async def report_diagnostic_result(
  680. device_id: str,
  681. req: DiagnosticResultRequest,
  682. db: AsyncSession = Depends(get_db),
  683. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  684. ):
  685. """Report diagnostic result from SpoolBuddy device."""
  686. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  687. device = result.scalar_one_or_none()
  688. if not device:
  689. raise HTTPException(status_code=404, detail="Device not registered")
  690. if req.diagnostic not in ("nfc", "scale", "read_tag"):
  691. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  692. _diagnostic_results[(device_id, req.diagnostic)] = {
  693. "diagnostic": req.diagnostic,
  694. "success": req.success,
  695. "output": req.output,
  696. "exit_code": req.exit_code,
  697. }
  698. device.pending_command = None
  699. await db.commit()
  700. logger.info("Diagnostic result received for device %s: %s (success=%s)", device_id, req.diagnostic, req.success)
  701. return {"status": "ok", "message": "Diagnostic result recorded"}
  702. # --- Update check ---
  703. @router.get("/devices/{device_id}/update-check")
  704. async def check_daemon_update(
  705. device_id: str,
  706. db: AsyncSession = Depends(get_db),
  707. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  708. ):
  709. """Check if the SpoolBuddy daemon needs updating to match the Bambuddy backend version."""
  710. from backend.app.api.routes.updates import is_newer_version
  711. from backend.app.core.config import APP_VERSION
  712. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  713. device = result.scalar_one_or_none()
  714. if not device:
  715. raise HTTPException(status_code=404, detail="Device not registered")
  716. current = device.firmware_version or "0.0.0"
  717. return {
  718. "current_version": current,
  719. "latest_version": APP_VERSION,
  720. "update_available": is_newer_version(APP_VERSION, current),
  721. }
  722. @router.post("/devices/{device_id}/update")
  723. async def trigger_daemon_update(
  724. device_id: str,
  725. req: dict | None = None,
  726. db: AsyncSession = Depends(get_db),
  727. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  728. ):
  729. """Trigger a SpoolBuddy update over SSH.
  730. Bambuddy SSHes into the device, pulls the matching branch, installs deps,
  731. and restarts the daemon. Progress is broadcast via WebSocket.
  732. """
  733. from backend.app.services.spoolbuddy_ssh import perform_ssh_update
  734. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  735. device = result.scalar_one_or_none()
  736. if not device:
  737. raise HTTPException(status_code=404, detail="Device not registered")
  738. if not _is_online(device):
  739. raise HTTPException(status_code=409, detail="Device is offline")
  740. if device.update_status == "updating":
  741. return {"status": "already_updating", "message": "Update already in progress"}
  742. device.update_status = "pending"
  743. device.update_message = "Starting SSH update..."
  744. await db.commit()
  745. logger.info("SpoolBuddy %s: SSH update triggered (ip=%s)", device_id, device.ip_address)
  746. await ws_manager.broadcast(
  747. {
  748. "type": "spoolbuddy_update",
  749. "device_id": device_id,
  750. "update_status": "pending",
  751. }
  752. )
  753. # Run the SSH update in the background
  754. asyncio.create_task(perform_ssh_update(device_id, device.ip_address))
  755. return {"status": "ok", "message": "SSH update started"}
  756. @router.get("/ssh/public-key")
  757. async def get_ssh_public_key(
  758. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  759. ):
  760. """Return the SSH public key for SpoolBuddy pairing."""
  761. from backend.app.services.spoolbuddy_ssh import get_public_key
  762. try:
  763. key = await get_public_key()
  764. return {"public_key": key}
  765. except Exception as e:
  766. raise HTTPException(status_code=500, detail=f"Failed to get SSH key: {e}") from e
  767. @router.post("/devices/{device_id}/update-status")
  768. async def report_update_status(
  769. device_id: str,
  770. req: dict,
  771. db: AsyncSession = Depends(get_db),
  772. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  773. ):
  774. """Daemon reports update progress back to the backend."""
  775. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  776. device = result.scalar_one_or_none()
  777. if not device:
  778. raise HTTPException(status_code=404, detail="Device not registered")
  779. status = req.get("status", "")
  780. message = req.get("message", "")
  781. if status in ("updating", "complete", "error"):
  782. device.update_status = status
  783. device.update_message = message[:255] if message else None
  784. if status == "complete":
  785. device.pending_command = None
  786. await db.commit()
  787. logger.info("SpoolBuddy %s: update status=%s msg=%s", device_id, status, message)
  788. await ws_manager.broadcast(
  789. {
  790. "type": "spoolbuddy_update",
  791. "device_id": device_id,
  792. "update_status": status,
  793. "update_message": message,
  794. }
  795. )
  796. return {"status": "ok"}
  797. # --- Background watchdog ---
  798. async def spoolbuddy_watchdog():
  799. """Check for devices that have gone offline (no heartbeat for 30s).
  800. Called periodically from the main app's background task loop.
  801. """
  802. from backend.app.core.database import async_session
  803. async with async_session() as db:
  804. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.last_seen.isnot(None)))
  805. devices = list(result.scalars().all())
  806. threshold = datetime.now(timezone.utc) - timedelta(seconds=OFFLINE_THRESHOLD_SECONDS)
  807. for device in devices:
  808. last_seen = device.last_seen.replace(tzinfo=timezone.utc) if device.last_seen else None
  809. if last_seen and last_seen < threshold:
  810. # Only broadcast once — clear last_seen after marking offline
  811. await ws_manager.broadcast(
  812. {
  813. "type": "spoolbuddy_offline",
  814. "device_id": device.device_id,
  815. }
  816. )
  817. device.last_seen = None
  818. logger.info("SpoolBuddy device offline: %s", device.device_id)
  819. await db.commit()