spoolbuddy.py 64 KB

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