spoolbuddy.py 33 KB

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