spoolbuddy.py 61 KB

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