spoolbuddy.py 72 KB

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