spoolbuddy.py 33 KB

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