spoolbuddy.py 66 KB

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