spoolbuddy.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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 _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. ndef_data = encode_opentag3d_from_mapped(mapped)
  633. data_origin = "spoolman"
  634. # Warn when fields that drive NFC content are absent in Spoolman.
  635. # color_name specifically must check the raw filament field, not the
  636. # mapped value — _map_spoolman_spool falls back to the filament's
  637. # subtype when color_name is unset (so LinkSpoolModal stops showing
  638. # "Unknown color"), but the NFC tag should still warn when Spoolman
  639. # has no genuine color_name on file. Without this, the fallback
  640. # silently masks a real missing-data condition.
  641. raw_filament: dict = sm_spool.get("filament") or {}
  642. if not raw_filament.get("color_name"):
  643. nfc_warnings.append("color_name not set in Spoolman — tag encodes empty color name")
  644. if not mapped.get("nozzle_temp_min"):
  645. nfc_warnings.append("nozzle_temp_min not set in Spoolman — tag encodes 0 °C")
  646. if not mapped.get("subtype"):
  647. nfc_warnings.append("subtype not set in Spoolman — tag encodes empty subtype")
  648. if not mapped.get("brand"):
  649. nfc_warnings.append("brand/vendor not set in Spoolman — tag encodes empty brand")
  650. if not mapped.get("rgba"):
  651. nfc_warnings.append("rgba not set in Spoolman — tag encodes default colour")
  652. if not mapped.get("label_weight"):
  653. nfc_warnings.append("label_weight not set in Spoolman — tag encodes 0 g")
  654. if nfc_warnings:
  655. logger.warning(
  656. "NFC encode for Spoolman spool %d has incomplete data: %s",
  657. req.spool_id,
  658. "; ".join(nfc_warnings),
  659. )
  660. # Store write payload and set pending command
  661. device.pending_write_payload = json.dumps(
  662. {
  663. "spool_id": req.spool_id,
  664. "ndef_data_hex": ndef_data.hex(),
  665. "data_origin": data_origin,
  666. }
  667. )
  668. device.pending_command = "write_tag"
  669. await db.commit()
  670. logger.info(
  671. "Write tag queued for device %s, spool %d (%s, %d bytes)",
  672. req.device_id,
  673. req.spool_id,
  674. data_origin,
  675. len(ndef_data),
  676. )
  677. result: dict = {"status": "queued"}
  678. if nfc_warnings:
  679. result["warnings"] = nfc_warnings
  680. return result
  681. @router.post("/nfc/write-result")
  682. async def nfc_write_result(
  683. req: WriteTagResultRequest,
  684. db: AsyncSession = Depends(get_db),
  685. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  686. ):
  687. """Handle NFC tag write result from SpoolBuddy daemon."""
  688. # Find the device
  689. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == req.device_id))
  690. device = result.scalar_one_or_none()
  691. if not device:
  692. raise HTTPException(status_code=404, detail="Device not registered")
  693. # Capture data_origin before clearing the payload
  694. try:
  695. payload_dict = json.loads(device.pending_write_payload or "{}")
  696. except (json.JSONDecodeError, TypeError):
  697. payload_dict = {}
  698. logger.warning("Malformed pending_write_payload for device %s — treating as local", req.device_id)
  699. data_origin = payload_dict.get("data_origin", "local")
  700. device.pending_command = None
  701. device.pending_write_payload = None
  702. if req.success:
  703. if data_origin == "spoolman":
  704. # Update Spoolman extra.tag with the written NFC UID using a safe merge
  705. # (fetches current extra first to avoid overwriting other custom fields).
  706. sm_client = await _get_spoolman_client_or_none(db)
  707. if sm_client is None:
  708. logger.warning("Spoolman not configured; cannot persist tag link for spool %d", req.spool_id)
  709. await db.commit()
  710. await ws_manager.broadcast(
  711. {
  712. "type": "spoolbuddy_tag_link_failed",
  713. "device_id": req.device_id,
  714. "spool_id": req.spool_id,
  715. "tag_uid": req.tag_uid,
  716. "message": "Spoolman not configured",
  717. "reason": "spoolman_not_configured",
  718. }
  719. )
  720. raise HTTPException(
  721. status_code=502,
  722. detail="Tag written to NFC but Spoolman is not configured; link not persisted",
  723. )
  724. _tag_link_ok = False
  725. try:
  726. tag_value = json.dumps(req.tag_uid.upper())
  727. # Tag uniqueness: a single physical NFC UID must map to at most
  728. # one Spoolman spool, otherwise find_spool_by_tag returns
  729. # whichever spool comes first in the cached list (usually the
  730. # older one) and the dashboard shows the wrong spool when the
  731. # tag is scanned. Before binding the new owner, clear the tag
  732. # from any other spool that currently has it. Best-effort:
  733. # cleanup failure does not block the write itself, but the
  734. # warning surfaces in logs so a stale duplicate can be tracked
  735. # down manually.
  736. try:
  737. cached_spools = await sm_client.get_spools()
  738. duplicate = await sm_client.find_spool_by_tag(req.tag_uid, cached_spools=cached_spools)
  739. if duplicate is not None and duplicate.get("id") != req.spool_id:
  740. await sm_client.merge_spool_extra(int(duplicate["id"]), {"tag": ""})
  741. logger.info(
  742. "Spoolman: cleared tag %s from previous holder spool %d before binding to spool %d",
  743. req.tag_uid,
  744. duplicate["id"],
  745. req.spool_id,
  746. )
  747. except (SpoolmanNotFoundError, SpoolmanUnavailableError, SpoolmanClientError) as cleanup_exc:
  748. logger.warning(
  749. "Spoolman: failed to clear duplicate tag %s before binding to spool %d (proceeding anyway): %s",
  750. req.tag_uid,
  751. req.spool_id,
  752. cleanup_exc,
  753. )
  754. except Exception:
  755. logger.exception(
  756. "Spoolman: unexpected error clearing duplicate tag %s before binding to spool %d (proceeding anyway)",
  757. req.tag_uid,
  758. req.spool_id,
  759. )
  760. # Spoolman 0.27+: the same tag as a native one. It was just written onto
  761. # this spool, so a previous holder gives it up here too. Linked before
  762. # extra.tag, as the step Spoolman can refuse; a failed extra.tag write
  763. # takes back what was added.
  764. uid = req.tag_uid.upper()
  765. added_native = False
  766. if await sm_client.has_tag_api():
  767. before = await sm_client.get_spool(req.spool_id)
  768. had = any(t.get("uid") == uid for t in before.get("tags") or [])
  769. # A spool that already holds the tag has nothing to link or move.
  770. if not had:
  771. holder = await sm_client.link_native_tag(req.spool_id, uid)
  772. if holder is not None and holder > 0:
  773. previous = holder
  774. await sm_client.unlink_native_tag(previous, uid)
  775. holder = await sm_client.link_native_tag(req.spool_id, uid)
  776. logger.info(
  777. "Spoolman: native tag %s moved from spool %d to %d", uid, previous, req.spool_id
  778. )
  779. if holder is not None:
  780. logger.warning("Native tag %s belongs to a filament or location, not linked", uid)
  781. added_native = holder is None
  782. try:
  783. await sm_client.merge_spool_extra(req.spool_id, {"tag": tag_value})
  784. except Exception:
  785. if added_native:
  786. try:
  787. await sm_client.unlink_native_tag(req.spool_id, uid)
  788. except (SpoolmanClientError, SpoolmanUnavailableError) as undo_exc:
  789. logger.warning(
  790. "Could not take back native tag %s from spool %d: %s", uid, req.spool_id, undo_exc
  791. )
  792. raise
  793. logger.info(
  794. "Spoolman tag written and linked: spool %d -> tag %s",
  795. req.spool_id,
  796. req.tag_uid,
  797. )
  798. _tag_link_ok = True
  799. except (SpoolmanNotFoundError, SpoolmanUnavailableError, SpoolmanClientError) as exc:
  800. logger.error(
  801. "Spoolman error during tag write-back for spool %d (type=%s, status=%s): %s",
  802. req.spool_id,
  803. type(exc).__name__,
  804. getattr(exc, "status_code", "N/A"),
  805. exc,
  806. )
  807. # fall through to broadcast + raise 502 below
  808. except Exception:
  809. logger.exception(
  810. "Unexpected error during Spoolman tag write-back for spool %d",
  811. req.spool_id,
  812. )
  813. # fall through to broadcast + raise 502 below
  814. await db.commit()
  815. if _tag_link_ok:
  816. await ws_manager.broadcast(
  817. {
  818. "type": "spoolbuddy_tag_written",
  819. "device_id": req.device_id,
  820. "spool_id": req.spool_id,
  821. "tag_uid": req.tag_uid,
  822. }
  823. )
  824. else:
  825. await ws_manager.broadcast(
  826. {
  827. "type": "spoolbuddy_tag_link_failed",
  828. "device_id": req.device_id,
  829. "spool_id": req.spool_id,
  830. "tag_uid": req.tag_uid,
  831. # Generic message — full exception (may contain internal URLs/hostnames)
  832. # is logged server-side only to prevent information leakage via WebSocket.
  833. "message": "Spoolman link failed",
  834. "reason": "spoolman_link_failed",
  835. }
  836. )
  837. raise HTTPException(
  838. status_code=502,
  839. detail="Tag written to NFC but Spoolman link failed",
  840. )
  841. else:
  842. # Link the tag to the local DB spool
  843. from backend.app.models.spool import Spool
  844. result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  845. spool = result.scalar_one_or_none()
  846. if spool is None:
  847. logger.warning(
  848. "NFC tag written for spool %d but it no longer exists in local DB; tag is orphaned",
  849. req.spool_id,
  850. )
  851. await db.commit()
  852. await ws_manager.broadcast(
  853. {
  854. "type": "spoolbuddy_tag_link_failed",
  855. "device_id": req.device_id,
  856. "spool_id": req.spool_id,
  857. "message": "Spool not found",
  858. "reason": "spool_not_found",
  859. }
  860. )
  861. return {"status": "ok", "linked": False, "message": "Spool not found"}
  862. spool.tag_uid = req.tag_uid.upper()
  863. spool.tag_type = "ntag"
  864. spool.data_origin = "opentag3d"
  865. spool.encode_time = datetime.now(timezone.utc)
  866. logger.info("Tag written and linked: spool %d -> tag %s", spool.id, req.tag_uid)
  867. await db.commit()
  868. await ws_manager.broadcast(
  869. {
  870. "type": "spoolbuddy_tag_written",
  871. "device_id": req.device_id,
  872. "spool_id": req.spool_id,
  873. "tag_uid": req.tag_uid,
  874. }
  875. )
  876. else:
  877. await db.commit()
  878. await ws_manager.broadcast(
  879. {
  880. "type": "spoolbuddy_tag_write_failed",
  881. "device_id": req.device_id,
  882. "spool_id": req.spool_id,
  883. "message": req.message,
  884. }
  885. )
  886. logger.warning("Tag write failed for device %s: %s", req.device_id, req.message)
  887. return {"status": "ok"}
  888. @router.post("/devices/{device_id}/cancel-write")
  889. async def cancel_write(
  890. device_id: str,
  891. db: AsyncSession = Depends(get_db),
  892. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  893. ):
  894. """Cancel a pending write-tag command."""
  895. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  896. device = result.scalar_one_or_none()
  897. if not device:
  898. raise HTTPException(status_code=404, detail="Device not registered")
  899. if device.pending_command == "write_tag":
  900. device.pending_command = None
  901. device.pending_write_payload = None
  902. await db.commit()
  903. logger.info("Write tag cancelled for device %s", device_id)
  904. return {"status": "ok"}
  905. # --- Scale endpoints ---
  906. @router.post("/scale/reading")
  907. async def scale_reading(
  908. req: ScaleReadingRequest,
  909. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  910. ):
  911. """RPi reports scale weight — broadcast to all clients."""
  912. await ws_manager.broadcast(
  913. {
  914. "type": "spoolbuddy_weight",
  915. "device_id": req.device_id,
  916. "weight_grams": req.weight_grams,
  917. "stable": req.stable,
  918. "raw_adc": req.raw_adc,
  919. }
  920. )
  921. return {"status": "ok"}
  922. @router.post("/scale/update-spool-weight")
  923. async def update_spool_weight(
  924. req: UpdateSpoolWeightRequest,
  925. db: AsyncSession = Depends(get_db),
  926. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  927. ):
  928. """Update spool's used weight from scale reading.
  929. Routes the update to whichever inventory backend Bambuddy is configured
  930. for: Spoolman exclusively when ``spoolman_enabled`` is true, local DB
  931. exclusively otherwise. The previous implementation tried local first and
  932. only consulted Spoolman on a local-DB miss, which meant a stale local row
  933. sharing a numeric id with a Spoolman spool would silently absorb the
  934. update while the Spoolman row the user is actually looking at stayed
  935. unchanged (#1530). Mirrors the routing already used by ``nfc/tag-scanned``.
  936. """
  937. from backend.app.api.routes._spoolman_helpers import _safe_float, spoolman_net_weight, spoolman_tare
  938. from backend.app.models.spool import Spool
  939. sm_client = await _get_spoolman_client_or_none(db)
  940. if sm_client is None and await _spoolman_mode(db):
  941. raise HTTPException(status_code=503, detail="Spoolman is unavailable")
  942. if sm_client is None:
  943. # Local mode — exclusive update, no Spoolman fallback.
  944. db_result = await db.execute(select(Spool).where(Spool.id == req.spool_id))
  945. spool = db_result.scalar_one_or_none()
  946. if not spool:
  947. raise HTTPException(status_code=404, detail="Spool not found")
  948. net_filament = max(0, req.weight_grams - spool.core_weight)
  949. spool.weight_used = max(0, spool.label_weight - net_filament)
  950. spool.last_scale_weight = req.weight_grams
  951. spool.last_weighed_at = datetime.now(timezone.utc)
  952. # A measured figure, which the AMS remain% sync must not overwrite
  953. # (as a hand-set one, see update_spool).
  954. spool.weight_locked = True
  955. await db.commit()
  956. logger.info(
  957. "SpoolBuddy updated spool %d weight: %.1fg on scale, %.1fg used",
  958. spool.id,
  959. req.weight_grams,
  960. spool.weight_used,
  961. )
  962. return {"status": "ok", "weight_used": spool.weight_used}
  963. # Spoolman mode — exclusive update, never touch local DB.
  964. async with _translate_spoolbuddy_errors():
  965. sm_spool = await sm_client.get_spool(req.spool_id)
  966. core_weight, tare_source = spoolman_tare(sm_spool)
  967. spool_weight_warning: str | None = None
  968. if tare_source == "fallback":
  969. logger.warning(
  970. "Spoolman spool %d has no spool_weight or vendor empty_spool_weight set; using 250g fallback for tare",
  971. req.spool_id,
  972. )
  973. spool_weight_warning = (
  974. "spool_weight_not_set: Spoolman spool, filament and vendor have no empty-spool weight configured; "
  975. "weight estimate uses 250g fallback"
  976. )
  977. label_weight = _safe_float(spoolman_net_weight(sm_spool), 1000.0)
  978. remaining_weight = max(0.0, req.weight_grams - core_weight)
  979. async with _translate_spoolbuddy_errors():
  980. await sm_client.update_spool(spool_id=req.spool_id, remaining_weight=remaining_weight)
  981. weight_used = max(0.0, label_weight - remaining_weight)
  982. logger.info(
  983. "SpoolBuddy updated Spoolman spool %d: %.1fg on scale, core=%.1fg → %.1fg remaining",
  984. req.spool_id,
  985. req.weight_grams,
  986. core_weight,
  987. remaining_weight,
  988. )
  989. result: dict = {"status": "ok", "weight_used": weight_used}
  990. if spool_weight_warning:
  991. result["warnings"] = [spool_weight_warning]
  992. return result
  993. # --- Calibration endpoints ---
  994. @router.post("/devices/{device_id}/calibration/tare")
  995. async def tare_scale(
  996. device_id: str,
  997. db: AsyncSession = Depends(get_db),
  998. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  999. ):
  1000. """Set pending tare command for the device to pick up."""
  1001. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1002. device = result.scalar_one_or_none()
  1003. if not device:
  1004. raise HTTPException(status_code=404, detail="Device not registered")
  1005. device.pending_command = "tare"
  1006. await db.commit()
  1007. return {"status": "ok", "message": "Tare command queued"}
  1008. @router.post("/devices/{device_id}/calibration/set-tare")
  1009. async def set_tare_offset(
  1010. device_id: str,
  1011. req: SetTareRequest,
  1012. db: AsyncSession = Depends(get_db),
  1013. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1014. ):
  1015. """Store tare offset reported by the daemon after executing a tare."""
  1016. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1017. device = result.scalar_one_or_none()
  1018. if not device:
  1019. raise HTTPException(status_code=404, detail="Device not registered")
  1020. device.tare_offset = req.tare_offset
  1021. device.last_calibrated_at = datetime.now(timezone.utc)
  1022. await db.commit()
  1023. logger.info("SpoolBuddy %s tare offset set to %d", device_id, req.tare_offset)
  1024. return CalibrationResponse(
  1025. tare_offset=device.tare_offset,
  1026. calibration_factor=device.calibration_factor,
  1027. )
  1028. @router.post("/devices/{device_id}/calibration/set-factor")
  1029. async def set_calibration_factor(
  1030. device_id: str,
  1031. req: SetCalibrationFactorRequest,
  1032. db: AsyncSession = Depends(get_db),
  1033. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1034. ):
  1035. """Calculate and store calibration factor from a known weight."""
  1036. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1037. device = result.scalar_one_or_none()
  1038. if not device:
  1039. raise HTTPException(status_code=404, detail="Device not registered")
  1040. tare = req.tare_raw_adc if req.tare_raw_adc is not None else device.tare_offset
  1041. raw_delta = req.raw_adc - tare
  1042. if raw_delta == 0:
  1043. raise HTTPException(status_code=400, detail="Raw ADC value equals tare offset — place weight on scale")
  1044. device.calibration_factor = req.known_weight_grams / raw_delta
  1045. if req.tare_raw_adc is not None:
  1046. device.tare_offset = tare
  1047. device.last_calibrated_at = datetime.now(timezone.utc)
  1048. await db.commit()
  1049. logger.info(
  1050. "SpoolBuddy %s calibration factor set to %.6f (known=%.1fg, raw=%d, tare=%d)",
  1051. device_id,
  1052. device.calibration_factor,
  1053. req.known_weight_grams,
  1054. req.raw_adc,
  1055. tare,
  1056. )
  1057. return CalibrationResponse(
  1058. tare_offset=device.tare_offset,
  1059. calibration_factor=device.calibration_factor,
  1060. )
  1061. @router.get("/devices/{device_id}/calibration", response_model=CalibrationResponse)
  1062. async def get_calibration(
  1063. device_id: str,
  1064. db: AsyncSession = Depends(get_db),
  1065. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1066. ):
  1067. """Get current calibration values for a device."""
  1068. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1069. device = result.scalar_one_or_none()
  1070. if not device:
  1071. raise HTTPException(status_code=404, detail="Device not registered")
  1072. return CalibrationResponse(
  1073. tare_offset=device.tare_offset,
  1074. calibration_factor=device.calibration_factor,
  1075. )
  1076. # --- Display settings ---
  1077. @router.get("/devices/{device_id}/display")
  1078. async def get_display_settings(
  1079. device_id: str,
  1080. db: AsyncSession = Depends(get_db),
  1081. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1082. ):
  1083. """Read current display brightness and screen blank timeout for a device.
  1084. Used by the SpoolBuddy kiosk idle watchdog on autostart to configure
  1085. swayidle with the same timeout the user picked in the UI, without having
  1086. to wait for the daemon heartbeat to arrive first.
  1087. """
  1088. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1089. device = result.scalar_one_or_none()
  1090. if not device:
  1091. raise HTTPException(status_code=404, detail="Device not registered")
  1092. return {
  1093. "brightness": device.display_brightness,
  1094. "blank_timeout": device.display_blank_timeout,
  1095. }
  1096. @router.put("/devices/{device_id}/display")
  1097. async def update_display_settings(
  1098. device_id: str,
  1099. req: DisplaySettingsRequest,
  1100. db: AsyncSession = Depends(get_db),
  1101. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1102. ):
  1103. """Update display brightness and screen blank timeout for a device."""
  1104. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1105. device = result.scalar_one_or_none()
  1106. if not device:
  1107. raise HTTPException(status_code=404, detail="Device not registered")
  1108. device.display_brightness = req.brightness
  1109. device.display_blank_timeout = req.blank_timeout
  1110. await db.commit()
  1111. logger.info(
  1112. "SpoolBuddy %s display updated: brightness=%d%%, blank_timeout=%ds",
  1113. device_id,
  1114. req.brightness,
  1115. req.blank_timeout,
  1116. )
  1117. return {"status": "ok", "brightness": req.brightness, "blank_timeout": req.blank_timeout}
  1118. @router.post("/devices/{device_id}/system/config")
  1119. async def queue_system_config_update(
  1120. device_id: str,
  1121. req: SystemConfigRequest,
  1122. db: AsyncSession = Depends(get_db),
  1123. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1124. ):
  1125. """Queue update of SpoolBuddy .env config on the device."""
  1126. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1127. device = result.scalar_one_or_none()
  1128. if not device:
  1129. raise HTTPException(status_code=404, detail="Device not registered")
  1130. parsed = urlparse(req.backend_url.strip())
  1131. if parsed.scheme not in ("http", "https") or not parsed.netloc:
  1132. raise HTTPException(
  1133. status_code=400,
  1134. detail="backend_url must be a full URL with scheme, e.g. http://192.168.1.100:5000 or http://bambuddy.local",
  1135. )
  1136. payload = {
  1137. "backend_url": req.backend_url.strip(),
  1138. }
  1139. if req.api_key is not None and req.api_key.strip():
  1140. payload["api_key"] = req.api_key.strip()
  1141. device.pending_system_payload = json.dumps(payload)
  1142. device.pending_command = "apply_system_config"
  1143. await db.commit()
  1144. logger.info("Queued system config update for device %s", device_id)
  1145. return {"status": "queued", "message": "System config update queued"}
  1146. VALID_SYSTEM_COMMANDS = {"reboot", "shutdown", "restart_daemon", "restart_browser"}
  1147. @router.post("/devices/{device_id}/system/command")
  1148. async def queue_system_command(
  1149. device_id: str,
  1150. req: SystemCommandRequest,
  1151. db: AsyncSession = Depends(get_db),
  1152. # Aligns with the rest of the kiosk-scoped device routes (calibration,
  1153. # display, cancel-write, command-result — all INVENTORY_UPDATE). The
  1154. # previous SETTINGS_UPDATE gate locked operators out of the QuickMenu's
  1155. # Restart-Daemon / Restart-Browser / Reboot / Shutdown buttons even
  1156. # though they had access to every other operation on the same device.
  1157. # Reboot and shutdown remain recoverable via physical access — the
  1158. # operator already has the kiosk in front of them.
  1159. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1160. ):
  1161. """Queue a system command (reboot, shutdown, restart_daemon, restart_browser) for the SpoolBuddy device."""
  1162. if req.command not in VALID_SYSTEM_COMMANDS:
  1163. raise HTTPException(
  1164. status_code=400,
  1165. detail=f"Invalid command. Must be one of: {', '.join(sorted(VALID_SYSTEM_COMMANDS))}",
  1166. )
  1167. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1168. device = result.scalar_one_or_none()
  1169. if not device:
  1170. raise HTTPException(status_code=404, detail="Device not registered")
  1171. if not _is_online(device):
  1172. raise HTTPException(status_code=409, detail="Device is offline")
  1173. device.pending_command = req.command
  1174. await db.commit()
  1175. logger.info("System command queued for device %s: %s", device_id, req.command)
  1176. return {"status": "queued", "command": req.command}
  1177. @router.post("/devices/{device_id}/system/command-result")
  1178. async def system_command_result(
  1179. device_id: str,
  1180. req: SystemCommandResultRequest,
  1181. db: AsyncSession = Depends(get_db),
  1182. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1183. ):
  1184. """Receive completion status for queued system command from daemon."""
  1185. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1186. device = result.scalar_one_or_none()
  1187. if not device:
  1188. raise HTTPException(status_code=404, detail="Device not registered")
  1189. if not device.pending_command:
  1190. logger.info("System command result from %s with no pending command: %s", device_id, req.command)
  1191. return {"status": "ok", "message": "No pending command"}
  1192. if req.command != device.pending_command:
  1193. raise HTTPException(
  1194. status_code=409,
  1195. detail=f"Command mismatch: pending '{device.pending_command}', got '{req.command}'",
  1196. )
  1197. if req.command == "apply_system_config":
  1198. device.pending_system_payload = None
  1199. device.pending_command = None
  1200. await db.commit()
  1201. logger.info(
  1202. "System command result from %s: %s success=%s message=%s",
  1203. device_id,
  1204. req.command,
  1205. req.success,
  1206. req.message,
  1207. )
  1208. return {"status": "ok"}
  1209. # --- Diagnostics ---
  1210. @router.post("/diagnostics/{device_id}/run")
  1211. async def queue_diagnostic(
  1212. device_id: str,
  1213. diagnostic: str,
  1214. db: AsyncSession = Depends(get_db),
  1215. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1216. ):
  1217. """Queue a hardware diagnostic to run on the SpoolBuddy device.
  1218. Args:
  1219. device_id: The device ID
  1220. diagnostic: 'scale' or 'nfc' to select which diagnostic to run
  1221. Returns:
  1222. Status message indicating diagnostic was queued
  1223. """
  1224. if diagnostic not in ("scale", "nfc", "read_tag"):
  1225. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1226. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1227. device = result.scalar_one_or_none()
  1228. if not device:
  1229. raise HTTPException(status_code=404, detail="Device not registered")
  1230. device.pending_command = f"run_{diagnostic}_diag"
  1231. _diagnostic_results.pop((device_id, diagnostic), None)
  1232. await db.commit()
  1233. logger.info("Diagnostic queued for device %s: %s", device_id, diagnostic)
  1234. return {"status": "queued", "diagnostic": diagnostic, "message": f"Diagnostic '{diagnostic}' queued for device"}
  1235. @router.get("/diagnostics/{device_id}/result")
  1236. async def get_diagnostic_result(
  1237. device_id: str,
  1238. diagnostic: str,
  1239. db: AsyncSession = Depends(get_db),
  1240. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1241. ):
  1242. """Get the latest diagnostic result for a device.
  1243. Args:
  1244. device_id: The device ID
  1245. diagnostic: 'scale' or 'nfc'
  1246. Returns:
  1247. Diagnostic result or 404 if not found
  1248. """
  1249. if diagnostic not in ("scale", "nfc", "read_tag"):
  1250. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1251. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1252. device = result.scalar_one_or_none()
  1253. if not device:
  1254. raise HTTPException(status_code=404, detail="Device not registered")
  1255. diag_result = _diagnostic_results.get((device_id, diagnostic))
  1256. if not diag_result:
  1257. raise HTTPException(status_code=404, detail=f"No {diagnostic} diagnostic results available yet")
  1258. return diag_result
  1259. @router.post("/diagnostics/{device_id}/result")
  1260. async def report_diagnostic_result(
  1261. device_id: str,
  1262. req: DiagnosticResultRequest,
  1263. db: AsyncSession = Depends(get_db),
  1264. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1265. ):
  1266. """Report diagnostic result from SpoolBuddy device."""
  1267. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1268. device = result.scalar_one_or_none()
  1269. if not device:
  1270. raise HTTPException(status_code=404, detail="Device not registered")
  1271. if req.diagnostic not in ("nfc", "scale", "read_tag"):
  1272. raise HTTPException(status_code=400, detail="Unknown diagnostic. Must be 'scale', 'nfc', or 'read_tag'")
  1273. _diagnostic_results[(device_id, req.diagnostic)] = {
  1274. "diagnostic": req.diagnostic,
  1275. "success": req.success,
  1276. "output": req.output,
  1277. "exit_code": req.exit_code,
  1278. }
  1279. device.pending_command = None
  1280. await db.commit()
  1281. logger.info("Diagnostic result received for device %s: %s (success=%s)", device_id, req.diagnostic, req.success)
  1282. return {"status": "ok", "message": "Diagnostic result recorded"}
  1283. # --- Update check ---
  1284. @router.get("/devices/{device_id}/update-check")
  1285. async def check_daemon_update(
  1286. device_id: str,
  1287. db: AsyncSession = Depends(get_db),
  1288. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1289. ):
  1290. """Check if the SpoolBuddy daemon needs updating to match the Bambuddy backend version."""
  1291. from backend.app.api.routes.updates import is_newer_version
  1292. from backend.app.core.config import APP_VERSION
  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. current = device.firmware_version or "0.0.0"
  1298. return {
  1299. "current_version": current,
  1300. "latest_version": APP_VERSION,
  1301. "update_available": is_newer_version(APP_VERSION, current),
  1302. }
  1303. @router.post("/devices/{device_id}/update")
  1304. async def trigger_daemon_update(
  1305. device_id: str,
  1306. req: dict | None = None,
  1307. db: AsyncSession = Depends(get_db),
  1308. # Aligns with the rest of the kiosk-scoped device routes (calibration,
  1309. # display, cancel-write, system/command — all INVENTORY_UPDATE).
  1310. # SETTINGS_UPDATE is on the API-key deny-list, which blocks the Update
  1311. # button from the kiosk's own Settings page even when the operator has
  1312. # physical access. Update only acts on the device the operator already
  1313. # controls (git fetch + pip install + systemctl restart on that one
  1314. # host) — same blast radius as the restart_daemon command.
  1315. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1316. ):
  1317. """Trigger a SpoolBuddy update over SSH.
  1318. Bambuddy SSHes into the device, pulls the matching branch, installs deps,
  1319. and restarts the daemon. Progress is broadcast via WebSocket.
  1320. """
  1321. from backend.app.services.spoolbuddy_ssh import perform_ssh_update
  1322. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1323. device = result.scalar_one_or_none()
  1324. if not device:
  1325. raise HTTPException(status_code=404, detail="Device not registered")
  1326. if not _is_online(device):
  1327. raise HTTPException(status_code=409, detail="Device is offline")
  1328. if device.update_status == "updating":
  1329. return {"status": "already_updating", "message": "Update already in progress"}
  1330. device.update_status = "pending"
  1331. device.update_message = "Starting SSH update..."
  1332. await db.commit()
  1333. logger.info("SpoolBuddy %s: SSH update triggered (ip=%s)", device_id, device.ip_address)
  1334. await ws_manager.broadcast(
  1335. {
  1336. "type": "spoolbuddy_update",
  1337. "device_id": device_id,
  1338. "update_status": "pending",
  1339. }
  1340. )
  1341. # Run the SSH update in the background — hold reference to prevent GC cancellation
  1342. _ssh_update_task = asyncio.create_task(perform_ssh_update(device_id, device.ip_address))
  1343. _ssh_update_task.add_done_callback(
  1344. lambda t: (
  1345. logger.error(
  1346. "SSH update task for device %s ended unexpectedly (cancelled=%s)",
  1347. device_id,
  1348. t.cancelled(),
  1349. )
  1350. if (t.cancelled() or t.exception() is not None)
  1351. else None
  1352. )
  1353. )
  1354. return {"status": "ok", "message": "SSH update started"}
  1355. @router.get("/ssh/public-key")
  1356. async def get_ssh_public_key(
  1357. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1358. ):
  1359. """Return the SSH public key for SpoolBuddy pairing."""
  1360. from backend.app.services.spoolbuddy_ssh import get_public_key
  1361. try:
  1362. key = await get_public_key()
  1363. return {"public_key": key}
  1364. except Exception as e:
  1365. logger.error("Failed to get SSH public key: %s", e)
  1366. raise HTTPException(status_code=500, detail="Failed to retrieve SSH public key") from e
  1367. @router.post("/devices/{device_id}/update-status")
  1368. async def report_update_status(
  1369. device_id: str,
  1370. req: UpdateStatusRequest,
  1371. db: AsyncSession = Depends(get_db),
  1372. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1373. ):
  1374. """Daemon reports update progress back to the backend."""
  1375. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.device_id == device_id))
  1376. device = result.scalar_one_or_none()
  1377. if not device:
  1378. raise HTTPException(status_code=404, detail="Device not registered")
  1379. device.update_status = req.status
  1380. device.update_message = req.message
  1381. # Only "complete" clears pending_command here. "error" leaves it set so the user can retry
  1382. # via the UI. The SSH service's own _update_progress clears on both "complete" and "error"
  1383. # because it owns the full update lifecycle end-to-end.
  1384. if req.status == "complete":
  1385. device.pending_command = None
  1386. await db.commit()
  1387. logger.info("SpoolBuddy %s: update status=%s msg=%s", device_id, req.status, req.message)
  1388. await ws_manager.broadcast(
  1389. {
  1390. "type": "spoolbuddy_update",
  1391. "device_id": device_id,
  1392. "update_status": req.status,
  1393. "update_message": req.message,
  1394. }
  1395. )
  1396. return {"status": "ok"}
  1397. # --- Background watchdog ---
  1398. async def spoolbuddy_watchdog():
  1399. """Check for devices that have gone offline (no heartbeat for 30s).
  1400. Called periodically from the main app's background task loop.
  1401. """
  1402. from backend.app.core.database import async_session
  1403. async with async_session() as db:
  1404. result = await db.execute(select(SpoolBuddyDevice).where(SpoolBuddyDevice.last_seen.isnot(None)))
  1405. devices = list(result.scalars().all())
  1406. threshold = datetime.now(timezone.utc) - timedelta(seconds=OFFLINE_THRESHOLD_SECONDS)
  1407. for device in devices:
  1408. last_seen = device.last_seen.replace(tzinfo=timezone.utc) if device.last_seen else None
  1409. if last_seen and last_seen < threshold:
  1410. # Only broadcast once — clear last_seen after marking offline
  1411. await ws_manager.broadcast(
  1412. {
  1413. "type": "spoolbuddy_offline",
  1414. "device_id": device.device_id,
  1415. }
  1416. )
  1417. device.last_seen = None
  1418. logger.info("SpoolBuddy device offline: %s", device.device_id)
  1419. await db.commit()