spoolbuddy.py 67 KB

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