spoolman.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. """Spoolman integration API routes."""
  2. import json
  3. import logging
  4. from typing import Literal
  5. from fastapi import APIRouter, Depends, HTTPException
  6. from pydantic import BaseModel
  7. from sqlalchemy import delete, select, text
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from sqlalchemy.orm import selectinload
  10. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  11. from backend.app.api.routes.spoolman_inventory import _clear_stale_tag_links
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.printer import Printer
  16. from backend.app.models.settings import Settings
  17. from backend.app.models.spool_assignment import SpoolAssignment
  18. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  19. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  20. from backend.app.models.user import User
  21. from backend.app.services.printer_manager import printer_manager
  22. from backend.app.services.spoolman import (
  23. SpoolmanClientError,
  24. SpoolmanNotFoundError,
  25. SpoolmanUnavailableError,
  26. close_spoolman_client,
  27. get_spoolman_client,
  28. init_spoolman_client,
  29. )
  30. from backend.app.utils.filament_ids import (
  31. GENERIC_FILAMENT_IDS,
  32. MATERIAL_TEMPS,
  33. normalize_slicer_filament,
  34. )
  35. from backend.app.utils.filament_types import printer_filament_type
  36. logger = logging.getLogger(__name__)
  37. router = APIRouter(prefix="/spoolman", tags=["spoolman"])
  38. class SpoolmanStatus(BaseModel):
  39. """Spoolman connection status."""
  40. enabled: bool
  41. connected: bool
  42. url: str | None
  43. class SkippedSpool(BaseModel):
  44. """Information about a skipped spool during sync."""
  45. location: str
  46. reason: Literal["No RFID tag and no slot assignment"]
  47. filament_type: str | None = None
  48. color: str | None = None
  49. class SyncResult(BaseModel):
  50. """Result of a Spoolman sync operation."""
  51. success: bool
  52. synced_count: int
  53. skipped_count: int = 0
  54. skipped: list[SkippedSpool] = []
  55. errors: list[str]
  56. async def get_spoolman_settings(db: AsyncSession) -> dict:
  57. """Get Spoolman settings from database.
  58. Returns:
  59. Dict with keys: enabled, url, sync_mode, disable_weight_sync
  60. """
  61. settings = {
  62. "enabled": False,
  63. "url": "",
  64. "sync_mode": "auto",
  65. "disable_weight_sync": False,
  66. }
  67. result = await db.execute(select(Settings))
  68. for setting in result.scalars().all():
  69. if setting.key == "spoolman_enabled":
  70. settings["enabled"] = setting.value.lower() == "true"
  71. elif setting.key == "spoolman_url":
  72. settings["url"] = setting.value
  73. elif setting.key == "spoolman_sync_mode":
  74. settings["sync_mode"] = setting.value
  75. elif setting.key == "spoolman_disable_weight_sync":
  76. settings["disable_weight_sync"] = setting.value.lower() == "true"
  77. return settings
  78. @router.get("/status", response_model=SpoolmanStatus)
  79. async def get_spoolman_status(
  80. db: AsyncSession = Depends(get_db),
  81. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  82. ):
  83. """Get Spoolman integration status.
  84. ``connected`` answers "does the configured Spoolman respond?", which means
  85. asking it. It used to answer "has some earlier request in this process left
  86. a client object lying around?" -- and roughly twenty call sites build one
  87. lazily, so the answer depended on which page happened to load first rather
  88. than on anything about Spoolman.
  89. That mattered because the UI reads this one flag twice: it offers Connect
  90. only while disconnected, and the AMS sync section only while connected.
  91. Saving the Settings page initialises a client as a side effect of syncing
  92. locations, so enabling Spoolman there reported "connected" without anything
  93. having been set up, hiding the Connect button and revealing a sync that then
  94. failed on every slot (issue #2903). Registration no longer depends on that
  95. button, but the flag was still describing Bambuddy's memory rather than the
  96. integration, so it is now resolved the same way every other route resolves
  97. it -- including the stale-URL check, so editing the URL is not reported
  98. against the old host.
  99. """
  100. sm = await get_spoolman_settings(db)
  101. enabled, url = sm["enabled"], sm["url"]
  102. connected = False
  103. if enabled and url:
  104. client = await get_spoolman_client()
  105. if not client or client.base_url != url.rstrip("/"):
  106. try:
  107. client = await init_spoolman_client(url)
  108. except ValueError as exc:
  109. logger.warning("Spoolman URL %r rejected by SSRF guard during status check: %s", url, exc)
  110. client = None
  111. except Exception as exc:
  112. # Every remaining way this can fail still answers the question:
  113. # replacing a client closes the previous one, and httpx's
  114. # aclose() is not guaranteed not to raise. A status poll that
  115. # 500s every 30 seconds is worse than one reporting what is
  116. # true either way -- that Spoolman could not be reached.
  117. logger.warning("Could not open a Spoolman client for %r during status check: %s", url, exc)
  118. client = None
  119. if client:
  120. connected = await client.health_check()
  121. return SpoolmanStatus(
  122. enabled=enabled,
  123. connected=connected,
  124. url=url if url else None,
  125. )
  126. @router.post("/connect")
  127. async def connect_spoolman(
  128. db: AsyncSession = Depends(get_db),
  129. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  130. ):
  131. """Connect to Spoolman server using configured URL."""
  132. sm = await get_spoolman_settings(db)
  133. enabled, url = sm["enabled"], sm["url"]
  134. if not enabled:
  135. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  136. if not url:
  137. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  138. try:
  139. client = await init_spoolman_client(url)
  140. connected = await client.health_check()
  141. if not connected:
  142. raise HTTPException(
  143. status_code=503,
  144. detail=f"Could not connect to Spoolman at {url}",
  145. )
  146. # Ensure the 'tag' extra field exists for RFID/UUID storage
  147. field_ok = await client.ensure_tag_extra_field()
  148. if not field_ok:
  149. logger.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  150. # Register slicer-preset extra fields (Spoolman rejects unknown extra keys).
  151. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  152. if not await client.ensure_extra_field(field_name):
  153. logger.warning(
  154. "Spoolman extra field %r registration failed — spool slicer-preset edits will return 502",
  155. field_name,
  156. )
  157. return {"success": True, "message": f"Connected to Spoolman at {url}"}
  158. except ValueError as exc:
  159. logger.warning("Spoolman URL rejected: %s", exc)
  160. raise HTTPException(status_code=400, detail=str(exc)) from exc
  161. except Exception as e:
  162. logger.error("Failed to connect to Spoolman: %s", e)
  163. raise HTTPException(status_code=503, detail=str(e))
  164. @router.post("/disconnect")
  165. async def disconnect_spoolman(
  166. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  167. ):
  168. """Disconnect from Spoolman server."""
  169. await close_spoolman_client()
  170. return {"success": True, "message": "Disconnected from Spoolman"}
  171. @router.post("/sync/{printer_id}", response_model=SyncResult)
  172. async def sync_printer_ams(
  173. printer_id: int,
  174. db: AsyncSession = Depends(get_db),
  175. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  176. ):
  177. """Sync AMS data from a specific printer to Spoolman."""
  178. # Check if Spoolman is enabled and connected
  179. # disable_weight_sync is deprecated (#1119); weight comes from per-print tracking.
  180. sm = await get_spoolman_settings(db)
  181. enabled, url = sm["enabled"], sm["url"]
  182. if not enabled:
  183. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  184. client = await get_spoolman_client()
  185. if not client:
  186. # Try to connect
  187. if url:
  188. client = await init_spoolman_client(url)
  189. else:
  190. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  191. if not await client.health_check():
  192. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  193. # Get printer info
  194. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  195. printer = result.scalar_one_or_none()
  196. if not printer:
  197. raise HTTPException(status_code=404, detail="Printer not found")
  198. # Get current printer state with AMS data
  199. state = printer_manager.get_status(printer_id)
  200. if not state:
  201. raise HTTPException(status_code=404, detail="Printer not connected")
  202. if not state.raw_data:
  203. raise HTTPException(status_code=400, detail="No AMS data available")
  204. ams_data = state.raw_data.get("ams")
  205. if not ams_data:
  206. raise HTTPException(
  207. status_code=400,
  208. detail="No AMS data in printer state. Try triggering a slot re-read on the printer.",
  209. )
  210. # Sync each AMS tray to Spoolman
  211. synced = 0
  212. skipped: list[SkippedSpool] = []
  213. errors = []
  214. from backend.app.api.routes.settings import get_setting
  215. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  216. auto_add_unknown_rfid = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  217. # Handle different AMS data structures
  218. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  219. # H2D/newer printers: dict with different structure
  220. ams_units = []
  221. if isinstance(ams_data, list):
  222. ams_units = ams_data
  223. elif isinstance(ams_data, dict):
  224. # H2D format: check for "ams" key containing list, or "tray" key directly
  225. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  226. ams_units = ams_data["ams"]
  227. elif "tray" in ams_data:
  228. # Single AMS unit format - wrap in list
  229. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  230. else:
  231. logger.info("AMS dict keys for debugging: %s", list(ams_data.keys()))
  232. if not ams_units:
  233. raise HTTPException(
  234. status_code=400,
  235. detail=(
  236. "AMS data format not supported. Keys: "
  237. f"{list(ams_data.keys()) if isinstance(ams_data, dict) else type(ams_data).__name__}"
  238. ),
  239. )
  240. # OPTIMIZATION: Fetch all spools once before processing trays
  241. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  242. logger.debug("[Printer %s] Fetching spools cache for sync...", printer.name)
  243. try:
  244. cached_spools = await client.get_spools()
  245. logger.debug("[Printer %s] Cached %d spools for batch sync", printer.name, len(cached_spools))
  246. except Exception as e:
  247. logger.error("[Printer %s] Failed to fetch spools cache after retries: %s", printer.name, e)
  248. raise HTTPException(
  249. status_code=503,
  250. detail=f"Failed to connect to Spoolman after multiple retries: {str(e)}",
  251. )
  252. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  253. inv_weights: dict[tuple[int, int], float] = {}
  254. try:
  255. assign_result = await db.execute(
  256. select(SpoolAssignment)
  257. .options(selectinload(SpoolAssignment.spool))
  258. .where(SpoolAssignment.printer_id == printer_id)
  259. )
  260. for assignment in assign_result.scalars().all():
  261. spool = assignment.spool
  262. if spool and spool.label_weight > 0:
  263. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  264. inv_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  265. except Exception as e:
  266. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  267. # Load existing Spoolman slot assignments for the no-RFID fallback path
  268. spoolman_slot_map: dict[tuple[int, int], int] = {}
  269. try:
  270. slot_result = await db.execute(
  271. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  272. )
  273. for slot in slot_result.scalars().all():
  274. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  275. except Exception as e:
  276. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  277. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id)
  278. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) now empty
  279. for ams_unit in ams_units:
  280. if not isinstance(ams_unit, dict):
  281. continue
  282. ams_id = int(ams_unit.get("id", 0))
  283. trays = ams_unit.get("tray", [])
  284. for tray_data in trays:
  285. if not isinstance(tray_data, dict):
  286. continue
  287. tray_id_raw = int(tray_data.get("id", 0))
  288. tray = client.parse_ams_tray(ams_id, tray_data)
  289. if not tray:
  290. empty_slots.append((ams_id, tray_id_raw))
  291. continue
  292. spool_tag = (
  293. tray.tray_uuid
  294. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  295. else tray.tag_uid
  296. )
  297. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  298. try:
  299. inv_remaining = inv_weights.get((ams_id, tray.tray_id))
  300. sync_result = await client.sync_ams_tray(
  301. tray,
  302. printer.name,
  303. # Per-print tracking owns weight updates (#1119); manual sync
  304. # only refreshes spool metadata + slot assignments here.
  305. disable_weight_sync=True,
  306. cached_spools=cached_spools,
  307. inventory_remaining=inv_remaining,
  308. spoolman_spool_id_hint=hint,
  309. auto_add_unknown_rfid=auto_add_unknown_rfid,
  310. )
  311. if sync_result:
  312. synced += 1
  313. if sync_result.get("id"):
  314. slot_changes.append((ams_id, tray.tray_id, sync_result["id"]))
  315. spool_exists = any(s.get("id") == sync_result["id"] for s in cached_spools)
  316. if not spool_exists:
  317. cached_spools.append(sync_result)
  318. logger.debug("Added newly created spool %s to cache", sync_result["id"])
  319. logger.info(
  320. "Synced %s from %s AMS %s tray %s", tray.tray_sub_brands, printer.name, ams_id, tray.tray_id
  321. )
  322. elif spool_tag and not auto_add_unknown_rfid:
  323. skipped.append(
  324. SkippedSpool(
  325. location=f"AMS {ams_id} T{tray.tray_id}",
  326. reason="Auto-add disabled; add to inventory manually",
  327. filament_type=tray.tray_type or None,
  328. color=tray.tray_color[:6] if tray.tray_color else None,
  329. )
  330. )
  331. elif spool_tag:
  332. errors.append(f"Spool not found in Spoolman: AMS {ams_id}:{tray.tray_id}")
  333. elif not hint:
  334. skipped.append(
  335. SkippedSpool(
  336. location=f"AMS {ams_id} T{tray.tray_id}",
  337. reason="No RFID tag and no slot assignment",
  338. filament_type=tray.tray_type or None,
  339. color=tray.tray_color[:6] if tray.tray_color else None,
  340. )
  341. )
  342. except Exception as e:
  343. error_msg = f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}"
  344. logger.error(error_msg)
  345. errors.append(error_msg)
  346. # Persist slot assignment changes to the local table
  347. if slot_changes or empty_slots:
  348. try:
  349. for ams_id, tray_id, spool_id in slot_changes:
  350. await db.execute(
  351. text(
  352. "INSERT INTO spoolman_slot_assignments"
  353. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  354. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  355. " ON CONFLICT(printer_id, ams_id, tray_id)"
  356. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  357. ),
  358. {"printer_id": printer_id, "ams_id": ams_id, "tray_id": tray_id, "spool_id": spool_id},
  359. )
  360. for ams_id, tray_id in empty_slots:
  361. await db.execute(
  362. delete(SpoolmanSlotAssignment).where(
  363. SpoolmanSlotAssignment.printer_id == printer_id,
  364. SpoolmanSlotAssignment.ams_id == ams_id,
  365. SpoolmanSlotAssignment.tray_id == tray_id,
  366. )
  367. )
  368. await db.commit()
  369. except Exception as e:
  370. await db.rollback()
  371. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  372. errors.append(f"Failed to persist slot assignments: {type(e).__name__}")
  373. return SyncResult(
  374. success=len(errors) == 0,
  375. synced_count=synced,
  376. skipped_count=len(skipped),
  377. skipped=skipped,
  378. errors=errors,
  379. )
  380. @router.post("/sync-all", response_model=SyncResult)
  381. async def sync_all_printers(
  382. db: AsyncSession = Depends(get_db),
  383. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  384. ):
  385. """Sync AMS data from all connected printers to Spoolman."""
  386. # Check if Spoolman is enabled
  387. # disable_weight_sync is deprecated (#1119); weight comes from per-print tracking.
  388. sm = await get_spoolman_settings(db)
  389. enabled, url = sm["enabled"], sm["url"]
  390. if not enabled:
  391. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  392. client = await get_spoolman_client()
  393. if not client:
  394. if url:
  395. client = await init_spoolman_client(url)
  396. else:
  397. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  398. if not await client.health_check():
  399. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  400. # Get all active printers
  401. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  402. printers = result.scalars().all()
  403. total_synced = 0
  404. all_skipped: list[SkippedSpool] = []
  405. all_errors = []
  406. from backend.app.api.routes.settings import get_setting
  407. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  408. auto_add_unknown_rfid = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  409. # OPTIMIZATION: Fetch all spools once before processing ALL printers/trays
  410. # This eliminates redundant API calls across all printers
  411. logger.debug("Fetching spools cache for sync-all operation...")
  412. try:
  413. cached_spools = await client.get_spools()
  414. logger.debug("Cached %d spools for batch sync across %d printers", len(cached_spools), len(printers))
  415. except Exception as e:
  416. logger.error("Failed to fetch spools cache after retries: %s", e)
  417. raise HTTPException(
  418. status_code=503,
  419. detail=f"Failed to connect to Spoolman after multiple retries: {str(e)}",
  420. )
  421. # Load inventory assignments for weight fallback (when AMS MQTT data lacks remain values)
  422. # Key: (printer_id, ams_id, tray_id) → remaining_weight in grams
  423. inventory_weights: dict[tuple[int, int, int], float] = {}
  424. try:
  425. assign_result = await db.execute(select(SpoolAssignment).options(selectinload(SpoolAssignment.spool)))
  426. for assignment in assign_result.scalars().all():
  427. spool = assignment.spool
  428. if spool and spool.label_weight > 0:
  429. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  430. inventory_weights[(assignment.printer_id, assignment.ams_id, assignment.tray_id)] = remaining
  431. except Exception as e:
  432. logger.debug("Could not load inventory assignments for weight fallback: %s", e)
  433. # Load all Spoolman slot assignments for the no-RFID fallback
  434. # Key: (printer_id, ams_id, tray_id) → spoolman_spool_id
  435. all_slot_map: dict[tuple[int, int, int], int] = {}
  436. try:
  437. slot_result = await db.execute(select(SpoolmanSlotAssignment))
  438. for slot in slot_result.scalars().all():
  439. all_slot_map[(slot.printer_id, slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  440. except Exception as e:
  441. logger.warning("Could not load Spoolman slot assignments: %s", e)
  442. # Collect slot changes across all printers for a single DB write at the end
  443. all_slot_changes: list[tuple[int, int, int, int]] = [] # (printer_id, ams_id, tray_id, spool_id)
  444. all_empty_slots: list[tuple[int, int, int]] = [] # (printer_id, ams_id, tray_id)
  445. for printer in printers:
  446. state = printer_manager.get_status(printer.id)
  447. if not state or not state.raw_data:
  448. continue
  449. ams_data = state.raw_data.get("ams")
  450. if not ams_data:
  451. continue
  452. # Handle different AMS data structures
  453. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  454. # H2D/newer printers: dict with different structure
  455. ams_units = []
  456. if isinstance(ams_data, list):
  457. ams_units = ams_data
  458. elif isinstance(ams_data, dict):
  459. # H2D format: check for "ams" key containing list, or "tray" key directly
  460. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  461. ams_units = ams_data["ams"]
  462. elif "tray" in ams_data:
  463. # Single AMS unit format - wrap in list
  464. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  465. else:
  466. logger.debug("Printer %s AMS dict keys: %s", printer.name, list(ams_data.keys()))
  467. if not ams_units:
  468. logger.debug("Printer %s has no AMS units to sync (type: %s)", printer.name, type(ams_data).__name__)
  469. continue
  470. for ams_unit in ams_units:
  471. if not isinstance(ams_unit, dict):
  472. logger.debug("Skipping non-dict AMS unit: %s", type(ams_unit))
  473. continue
  474. ams_id = int(ams_unit.get("id", 0))
  475. trays = ams_unit.get("tray", [])
  476. for tray_data in trays:
  477. if not isinstance(tray_data, dict):
  478. continue
  479. tray_id_raw = int(tray_data.get("id", 0))
  480. tray = client.parse_ams_tray(ams_id, tray_data)
  481. if not tray:
  482. all_empty_slots.append((printer.id, ams_id, tray_id_raw))
  483. continue
  484. spool_tag = (
  485. tray.tray_uuid
  486. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  487. else tray.tag_uid
  488. )
  489. hint = all_slot_map.get((printer.id, ams_id, tray.tray_id)) if not spool_tag else None
  490. try:
  491. inv_remaining = inventory_weights.get((printer.id, ams_id, tray.tray_id))
  492. sync_result = await client.sync_ams_tray(
  493. tray,
  494. printer.name,
  495. # Per-print tracking owns weight updates (#1119); manual
  496. # sync-all only refreshes spool metadata + slot assignments.
  497. disable_weight_sync=True,
  498. cached_spools=cached_spools,
  499. inventory_remaining=inv_remaining,
  500. spoolman_spool_id_hint=hint,
  501. auto_add_unknown_rfid=auto_add_unknown_rfid,
  502. )
  503. if sync_result:
  504. total_synced += 1
  505. if sync_result.get("id"):
  506. all_slot_changes.append((printer.id, ams_id, tray.tray_id, sync_result["id"]))
  507. spool_exists = any(s.get("id") == sync_result["id"] for s in cached_spools)
  508. if not spool_exists:
  509. cached_spools.append(sync_result)
  510. logger.debug("Added newly created spool %s to cache", sync_result["id"])
  511. elif spool_tag and not auto_add_unknown_rfid:
  512. all_skipped.append(
  513. SkippedSpool(
  514. location=f"{printer.name} AMS {ams_id} T{tray.tray_id}",
  515. reason="Auto-add disabled; add to inventory manually",
  516. filament_type=tray.tray_type or None,
  517. color=tray.tray_color[:6] if tray.tray_color else None,
  518. )
  519. )
  520. elif spool_tag:
  521. all_errors.append(f"Spool not found in Spoolman: {printer.name} AMS {ams_id}:{tray.tray_id}")
  522. elif not hint:
  523. all_skipped.append(
  524. SkippedSpool(
  525. location=f"{printer.name} AMS {ams_id} T{tray.tray_id}",
  526. reason="No RFID tag and no slot assignment",
  527. filament_type=tray.tray_type or None,
  528. color=tray.tray_color[:6] if tray.tray_color else None,
  529. )
  530. )
  531. except Exception as e:
  532. all_errors.append(f"{printer.name} AMS {ams_id}:{tray.tray_id}: {e}")
  533. # Persist slot assignment changes across all printers
  534. if all_slot_changes or all_empty_slots:
  535. try:
  536. for p_id, ams_id, tray_id, spool_id in all_slot_changes:
  537. await db.execute(
  538. text(
  539. "INSERT INTO spoolman_slot_assignments"
  540. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  541. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  542. " ON CONFLICT(printer_id, ams_id, tray_id)"
  543. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  544. ),
  545. {"printer_id": p_id, "ams_id": ams_id, "tray_id": tray_id, "spool_id": spool_id},
  546. )
  547. for p_id, ams_id, tray_id in all_empty_slots:
  548. await db.execute(
  549. delete(SpoolmanSlotAssignment).where(
  550. SpoolmanSlotAssignment.printer_id == p_id,
  551. SpoolmanSlotAssignment.ams_id == ams_id,
  552. SpoolmanSlotAssignment.tray_id == tray_id,
  553. )
  554. )
  555. await db.commit()
  556. except Exception as e:
  557. await db.rollback()
  558. logger.error("Error persisting Spoolman slot assignments: %s", e)
  559. all_errors.append(f"Failed to persist slot assignments: {type(e).__name__}")
  560. return SyncResult(
  561. success=len(all_errors) == 0,
  562. synced_count=total_synced,
  563. skipped_count=len(all_skipped),
  564. skipped=all_skipped,
  565. errors=all_errors,
  566. )
  567. @router.get("/spools")
  568. async def get_spools(
  569. db: AsyncSession = Depends(get_db),
  570. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  571. ):
  572. """Get all spools from Spoolman."""
  573. sm = await get_spoolman_settings(db)
  574. enabled, url = sm["enabled"], sm["url"]
  575. if not enabled:
  576. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  577. client = await get_spoolman_client()
  578. if not client:
  579. if url:
  580. client = await init_spoolman_client(url)
  581. else:
  582. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  583. if not await client.health_check():
  584. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  585. spools = await client.get_spools()
  586. return {"spools": spools}
  587. @router.get("/filaments")
  588. async def get_filaments(
  589. db: AsyncSession = Depends(get_db),
  590. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  591. ):
  592. """Get all filaments from Spoolman."""
  593. sm = await get_spoolman_settings(db)
  594. enabled, url = sm["enabled"], sm["url"]
  595. if not enabled:
  596. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  597. client = await get_spoolman_client()
  598. if not client:
  599. if url:
  600. client = await init_spoolman_client(url)
  601. else:
  602. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  603. if not await client.health_check():
  604. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  605. filaments = await client.get_filaments()
  606. return {"filaments": filaments}
  607. class UnlinkedSpool(BaseModel):
  608. """A Spoolman spool that is not linked to any AMS tray."""
  609. id: int
  610. filament_name: str | None
  611. filament_vendor: str | None
  612. filament_material: str | None
  613. filament_color_hex: str | None
  614. remaining_weight: float | None
  615. location: str | None
  616. @router.get("/spools/unlinked", response_model=list[UnlinkedSpool])
  617. async def get_unlinked_spools(
  618. db: AsyncSession = Depends(get_db),
  619. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  620. ):
  621. """Get all Spoolman spools not currently assigned to an AMS slot."""
  622. sm = await get_spoolman_settings(db)
  623. enabled, url = sm["enabled"], sm["url"]
  624. if not enabled:
  625. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  626. client = await get_spoolman_client()
  627. if not client:
  628. if url:
  629. client = await init_spoolman_client(url)
  630. else:
  631. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  632. if not await client.health_check():
  633. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  634. spools = await client.get_spools()
  635. # A spool is "assignable" iff it does not currently occupy an AMS slot.
  636. # Assignability is decided by the spoolman_slot_assignments ledger — NOT by
  637. # the presence of extra.tag. extra.tag is only an RFID/NFC matching key, and
  638. # OpenSpoolman writes its own NFC tag value into that same field (#1122);
  639. # treating any non-empty extra.tag as "linked" hid every OpenSpoolman-tagged
  640. # spool from this picker even when it occupied no slot. Both link_spool and
  641. # the AMS auto-sync upsert a row here for every occupied slot, so the ledger
  642. # is a complete record of what is actually assigned.
  643. assigned_result = await db.execute(select(SpoolmanSlotAssignment.spoolman_spool_id))
  644. assigned_spool_ids = set(assigned_result.scalars().all())
  645. unlinked = []
  646. for spool in spools:
  647. if spool["id"] in assigned_spool_ids:
  648. continue
  649. filament = spool.get("filament", {}) or {}
  650. unlinked.append(
  651. UnlinkedSpool(
  652. id=spool["id"],
  653. filament_name=filament.get("name"),
  654. filament_vendor=(filament.get("vendor") or {}).get("name"),
  655. filament_material=filament.get("material"),
  656. filament_color_hex=filament.get("color_hex"),
  657. remaining_weight=spool.get("remaining_weight"),
  658. location=spool.get("location"),
  659. )
  660. )
  661. return unlinked
  662. @router.get("/spools/linked")
  663. async def get_linked_spools(
  664. db: AsyncSession = Depends(get_db),
  665. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  666. ):
  667. """Get a map of tag -> spool_id for all Spoolman spools that have a tag assigned."""
  668. sm = await get_spoolman_settings(db)
  669. enabled, url = sm["enabled"], sm["url"]
  670. if not enabled:
  671. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  672. client = await get_spoolman_client()
  673. if not client:
  674. if url:
  675. client = await init_spoolman_client(url)
  676. else:
  677. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  678. if not await client.health_check():
  679. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  680. spools = await client.get_spools()
  681. linked: dict[str, dict] = {}
  682. for spool in spools:
  683. # Check if spool has a tag in extra field
  684. extra = spool.get("extra", {}) or {}
  685. tag = extra.get("tag", "")
  686. if tag:
  687. # Remove quotes if present (JSON encoded string)
  688. clean_tag = tag.strip('"').upper()
  689. if clean_tag:
  690. filament = spool.get("filament") or {}
  691. linked[clean_tag] = {
  692. "id": spool["id"],
  693. "remaining_weight": spool.get("remaining_weight"),
  694. "filament_weight": filament.get("weight"),
  695. }
  696. return {"linked": linked}
  697. class LinkSpoolRequest(BaseModel):
  698. """Request to link a Spoolman spool to an AMS tag (tray_uuid or tag_uid)."""
  699. spool_tag: str | None = None
  700. tray_uuid: str | None = None
  701. tag_uid: str | None = None
  702. printer_id: int | None = None
  703. ams_id: int | None = None
  704. tray_id: int | None = None
  705. @router.post("/spools/{spool_id}/link")
  706. async def link_spool(
  707. spool_id: int,
  708. request: LinkSpoolRequest,
  709. db: AsyncSession = Depends(get_db),
  710. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  711. ):
  712. """Link a Spoolman spool to an AMS tag by setting Spoolman extra.tag."""
  713. sm = await get_spoolman_settings(db)
  714. enabled, url = sm["enabled"], sm["url"]
  715. if not enabled:
  716. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  717. client = await get_spoolman_client()
  718. if not client:
  719. if url:
  720. client = await init_spoolman_client(url)
  721. else:
  722. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  723. if not await client.health_check():
  724. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  725. # Resolve and validate spool tag (supports tray_uuid=32 hex and tag_uid=16 hex)
  726. spool_tag = (request.spool_tag or request.tray_uuid or request.tag_uid or "").strip()
  727. if not spool_tag:
  728. raise HTTPException(status_code=400, detail="Missing spool tag (tray_uuid or tag_uid)")
  729. if len(spool_tag) not in (16, 32):
  730. raise HTTPException(status_code=400, detail="Invalid spool tag format (must be 16 or 32 hex characters)")
  731. try:
  732. int(spool_tag, 16)
  733. except ValueError:
  734. raise HTTPException(status_code=400, detail="Invalid spool tag format (must be hex)")
  735. if set(spool_tag) == {"0"}:
  736. raise HTTPException(status_code=400, detail="Invalid spool tag format (all-zero tag is not linkable)")
  737. spool_tag = spool_tag.upper()
  738. # Validate printer context when provided, but do NOT write spool.location —
  739. # that field is user-managed in Spoolman. Slot assignment is stored locally.
  740. printer_context: tuple[int, int, int] | None = None
  741. if request.printer_id is not None and request.ams_id is not None and request.tray_id is not None:
  742. printer_result = await db.execute(select(Printer).where(Printer.id == request.printer_id))
  743. if not printer_result.scalar_one_or_none():
  744. raise HTTPException(status_code=404, detail="Printer not found")
  745. printer_context = (request.printer_id, request.ams_id, request.tray_id)
  746. try:
  747. await client.merge_spool_extra(spool_id, {"tag": json.dumps(spool_tag)})
  748. except SpoolmanNotFoundError:
  749. raise HTTPException(status_code=404, detail="Spool not found in Spoolman")
  750. except SpoolmanClientError:
  751. raise HTTPException(status_code=502, detail="Spoolman rejected the request")
  752. except SpoolmanUnavailableError:
  753. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  754. # Upsert slot assignment locally when printer context was supplied
  755. if printer_context:
  756. p_id, a_id, t_id = printer_context
  757. try:
  758. await db.execute(
  759. text(
  760. "INSERT INTO spoolman_slot_assignments"
  761. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  762. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  763. " ON CONFLICT(printer_id, ams_id, tray_id)"
  764. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  765. ),
  766. {"printer_id": p_id, "ams_id": a_id, "tray_id": t_id, "spool_id": spool_id},
  767. )
  768. await db.commit()
  769. except Exception as e:
  770. await db.rollback()
  771. logger.error(
  772. "Linked spool %s in Spoolman but failed to persist local slot assignment "
  773. "(printer=%s ams=%s tray=%s): %s",
  774. spool_id,
  775. p_id,
  776. a_id,
  777. t_id,
  778. e,
  779. )
  780. raise HTTPException(
  781. status_code=500,
  782. detail=(
  783. "Spool linked in Spoolman but the local slot assignment could not be saved. "
  784. "Please re-open the link dialog to retry."
  785. ),
  786. ) from e
  787. logger.info("Linked Spoolman spool %s to tag %s", spool_id, spool_tag)
  788. # #1457: clear stale tag links on OTHER spools still claiming this exact tag.
  789. # A given AMS-slot tag (RFID or deterministic fallback) belongs to one
  790. # physical spool; without this cleanup the previous holder's extra.tag
  791. # keeps it visible in the hover card / fill-level lookup.
  792. await _clear_stale_tag_links(
  793. client,
  794. tag=spool_tag,
  795. keep_spool_id=spool_id,
  796. log_context=(
  797. f"printer={printer_context[0]} ams={printer_context[1]} tray={printer_context[2]}"
  798. if printer_context
  799. else "via /spools/{id}/link"
  800. ),
  801. )
  802. # Auto-configure AMS slot via MQTT (best-effort; tag link and slot assignment already persisted)
  803. if printer_context:
  804. p_id, a_id, t_id = printer_context
  805. try:
  806. spool_data = await client.get_spool(spool_id)
  807. mapped = _map_spoolman_spool(spool_data)
  808. mqtt_client = printer_manager.get_client(p_id)
  809. if mqtt_client:
  810. # Spoolman's material is free text, so it arrives as whatever
  811. # the user typed there -- "PLA+", "PolyTerra PLA". The sub-brand
  812. # keeps that wording; the slot's type has to be one the printer
  813. # and the slicer know (issue #2902).
  814. material = mapped.get("material") or ""
  815. tray_type = printer_filament_type(material)
  816. brand = mapped.get("brand") or ""
  817. subtype = mapped.get("subtype") or ""
  818. if brand:
  819. tray_sub_brands = f"{brand} {material} {subtype}".strip()
  820. elif subtype:
  821. tray_sub_brands = f"{material} {subtype}".strip()
  822. else:
  823. tray_sub_brands = material
  824. tray_color = (mapped.get("rgba") or "808080FF").upper()
  825. if len(tray_color) == 6:
  826. tray_color = tray_color + "FF"
  827. # The spool's own wording is tried first and the reduced type
  828. # only as a further fallback, so a material that already
  829. # resolves keeps resolving to the same id: "PETG HF" has its
  830. # own generic preset (GFG96) that reducing it to "PETG" would
  831. # trade away for GFG99.
  832. material_upper = material.upper().strip()
  833. tray_info_idx = (
  834. GENERIC_FILAMENT_IDS.get(material_upper)
  835. or GENERIC_FILAMENT_IDS.get(material_upper.split("-")[0].split(" ")[0])
  836. or GENERIC_FILAMENT_IDS.get(tray_type.upper())
  837. or ""
  838. )
  839. setting_id = ""
  840. temp_defaults = (
  841. MATERIAL_TEMPS.get(material_upper) or MATERIAL_TEMPS.get(tray_type.upper()) or (200, 240)
  842. )
  843. temp_min = mapped.get("nozzle_temp_min") or temp_defaults[0]
  844. temp_max = temp_defaults[1]
  845. # Pull printer state via printer_manager (mqtt_client.printer_state
  846. # was a non-existent attribute — the hasattr check silently
  847. # returned None, defeating every state-based lookup below).
  848. state = printer_manager.get_status(p_id)
  849. nozzle_diameter = "0.4"
  850. if state and state.nozzles:
  851. nd = state.nozzles[0].nozzle_diameter
  852. if nd:
  853. nozzle_diameter = nd
  854. kp_result = await db.execute(
  855. select(SpoolmanKProfile).where(
  856. SpoolmanKProfile.spoolman_spool_id == spool_id,
  857. SpoolmanKProfile.printer_id == p_id,
  858. )
  859. )
  860. kp_rows = kp_result.scalars().all()
  861. slot_extruder = None
  862. if state and state.ams_extruder_map:
  863. if a_id == 255:
  864. slot_extruder = 1 - t_id
  865. else:
  866. slot_extruder = state.ams_extruder_map.get(str(a_id))
  867. # Prefer exact extruder match, fall back to extruder-agnostic kp
  868. # for the same nozzle. Hard-skip on extruder mismatch silently
  869. # dropped valid stored profiles when the AMS-extruder map
  870. # shifted since calibration.
  871. exact_kp = None
  872. fallback_kp = None
  873. for kp in kp_rows:
  874. if kp.nozzle_diameter != nozzle_diameter or kp.cali_idx is None:
  875. continue
  876. if slot_extruder is not None and kp.extruder is not None and kp.extruder == slot_extruder:
  877. exact_kp = kp
  878. break
  879. if fallback_kp is None:
  880. fallback_kp = kp
  881. matching_kp = exact_kp or fallback_kp
  882. # Resolve printer-side calibration entry by cali_idx — the
  883. # printer keys its calibration table by filament_id, not by
  884. # setting_id. Stored kp.setting_id alone isn't enough.
  885. printer_kp = None
  886. if matching_kp and state and state.kprofiles:
  887. for pkp in state.kprofiles:
  888. if pkp.slot_id == matching_kp.cali_idx and pkp.nozzle_diameter == nozzle_diameter:
  889. printer_kp = pkp
  890. break
  891. # Realign slot's filament context to the kp's calibration
  892. # context so ams_filament_setting and extrusion_cali_sel
  893. # reference the same preset; otherwise the printer drops the
  894. # cali_idx to default. PFUS-prefix cloud-user presets are
  895. # rejected by the slicer in tray_info_idx — skip realignment
  896. # in that case.
  897. effective_tray_info_idx = tray_info_idx
  898. effective_setting_id = setting_id
  899. if printer_kp and printer_kp.filament_id:
  900. if not printer_kp.filament_id.startswith("PFUS"):
  901. effective_tray_info_idx = printer_kp.filament_id
  902. if printer_kp.setting_id:
  903. effective_setting_id = printer_kp.setting_id
  904. elif matching_kp and matching_kp.setting_id:
  905. derived = normalize_slicer_filament(matching_kp.setting_id)[0]
  906. if derived and not derived.startswith("PFUS"):
  907. effective_tray_info_idx = derived
  908. effective_setting_id = matching_kp.setting_id
  909. if effective_tray_info_idx != tray_info_idx or effective_setting_id != setting_id:
  910. logger.info(
  911. "Spoolman link: realigning tray_info_idx %r → %r, setting_id %r → %r (kp_id=%s, source=%s)",
  912. tray_info_idx,
  913. effective_tray_info_idx,
  914. setting_id,
  915. effective_setting_id,
  916. matching_kp.id if matching_kp else None,
  917. "printer" if printer_kp else "stored",
  918. )
  919. mqtt_client.ams_set_filament_setting(
  920. ams_id=a_id,
  921. tray_id=t_id,
  922. tray_info_idx=effective_tray_info_idx,
  923. tray_type=tray_type,
  924. tray_sub_brands=tray_sub_brands,
  925. tray_color=tray_color,
  926. nozzle_temp_min=temp_min,
  927. nozzle_temp_max=temp_max,
  928. setting_id=effective_setting_id,
  929. )
  930. if matching_kp and matching_kp.cali_idx is not None:
  931. cali_filament_id = (
  932. printer_kp.filament_id if printer_kp and printer_kp.filament_id else None
  933. ) or effective_tray_info_idx
  934. mqtt_client.extrusion_cali_sel(
  935. ams_id=a_id,
  936. tray_id=t_id,
  937. cali_idx=matching_kp.cali_idx,
  938. filament_id=cali_filament_id,
  939. nozzle_diameter=nozzle_diameter,
  940. )
  941. logger.info(
  942. "Spoolman link: applied K-profile cali_idx=%d "
  943. "(kp_id=%d, filament_id=%s) for spool %d on printer %d AMS%d-T%d",
  944. matching_kp.cali_idx,
  945. matching_kp.id,
  946. cali_filament_id,
  947. spool_id,
  948. p_id,
  949. a_id,
  950. t_id,
  951. )
  952. else:
  953. from backend.app.api.routes.inventory import _find_tray_in_ams_data # noqa: PLC0415
  954. live_tray = None
  955. if state and state.raw_data:
  956. ams_raw = state.raw_data.get("ams", [])
  957. if isinstance(ams_raw, dict):
  958. ams_raw = ams_raw.get("ams", [])
  959. live_tray = _find_tray_in_ams_data(ams_raw, a_id, t_id)
  960. live_cali_idx = (live_tray or {}).get("cali_idx")
  961. if live_cali_idx is not None and live_cali_idx >= 0:
  962. mqtt_client.extrusion_cali_sel(
  963. ams_id=a_id,
  964. tray_id=t_id,
  965. cali_idx=live_cali_idx,
  966. filament_id=effective_tray_info_idx,
  967. nozzle_diameter=nozzle_diameter,
  968. )
  969. logger.info(
  970. "Auto-configured AMS slot ams=%d tray=%d after linking Spoolman spool %d on printer %d",
  971. a_id,
  972. t_id,
  973. spool_id,
  974. p_id,
  975. )
  976. except (SpoolmanNotFoundError, SpoolmanUnavailableError) as e:
  977. logger.warning(
  978. "Could not fetch Spoolman spool %d for MQTT configure after tag link: %s",
  979. spool_id,
  980. e,
  981. )
  982. except Exception:
  983. logger.exception(
  984. "Failed to auto-configure AMS slot after linking Spoolman spool %d (printer=%d ams=%d tray=%d)",
  985. spool_id,
  986. p_id,
  987. a_id,
  988. t_id,
  989. )
  990. return {"success": True, "message": f"Spool {spool_id} linked to AMS tag"}
  991. @router.post("/spools/{spool_id}/unlink")
  992. async def unlink_spool(
  993. spool_id: int,
  994. db: AsyncSession = Depends(get_db),
  995. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  996. ):
  997. """Unlink a Spoolman spool from AMS by clearing Spoolman extra.tag."""
  998. sm = await get_spoolman_settings(db)
  999. enabled, url = sm["enabled"], sm["url"]
  1000. if not enabled:
  1001. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  1002. client = await get_spoolman_client()
  1003. if not client:
  1004. if url:
  1005. client = await init_spoolman_client(url)
  1006. else:
  1007. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  1008. if not await client.health_check():
  1009. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  1010. # Spoolman PATCHes the extra dict by MERGING with the existing keys —
  1011. # popping "tag" from a copy of the dict and sending the rest doesn't
  1012. # clear it; Spoolman keeps the old value because the key wasn't in the
  1013. # payload. To actually clear a key we must explicitly send it as the
  1014. # JSON-encoded empty string ('""'), which the read-side filters in
  1015. # _map_spoolman_spool and get_linked_spools strip via .strip('"').
  1016. #
  1017. # merge_spool_extra acquires extra_lock(spool_id) internally — wrapping
  1018. # this call in another `async with client.extra_lock(spool_id)` would
  1019. # deadlock (asyncio.Lock is not reentrant).
  1020. try:
  1021. await client.merge_spool_extra(spool_id, {"tag": json.dumps("")})
  1022. except SpoolmanNotFoundError:
  1023. raise HTTPException(status_code=404, detail="Spool not found in Spoolman")
  1024. except SpoolmanClientError:
  1025. raise HTTPException(status_code=502, detail="Spoolman rejected the request")
  1026. except SpoolmanUnavailableError:
  1027. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  1028. # Remove local slot assignment for this spool (all slots — a spool can only be in one at a time)
  1029. try:
  1030. await db.execute(delete(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.spoolman_spool_id == spool_id))
  1031. await db.commit()
  1032. except Exception:
  1033. await db.rollback()
  1034. logger.exception("DB error removing slot assignment for spool %s", spool_id)
  1035. raise HTTPException(status_code=500, detail="Failed to remove local slot assignment")
  1036. logger.info("Unlinked Spoolman spool %s", spool_id)
  1037. return {"success": True, "message": f"Spool {spool_id} unlinked from AMS"}
  1038. class CreateSpoolFromSlotRequest(BaseModel):
  1039. printer_id: int
  1040. ams_id: int
  1041. tray_id: int
  1042. @router.post("/spools/from-slot")
  1043. async def create_spool_from_slot(
  1044. req: CreateSpoolFromSlotRequest,
  1045. db: AsyncSession = Depends(get_db),
  1046. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  1047. ):
  1048. """Explicit user action: create a Spoolman spool from an AMS slot's current tray data.
  1049. Used by the "+ Add to inventory" affordance when auto_add_unknown_rfid is disabled —
  1050. the user looked at the slot and chose to register it. Calls sync_ams_tray with the
  1051. auto-add override on so the spool is created even when the global setting is off.
  1052. """
  1053. sm = await get_spoolman_settings(db)
  1054. if not sm["enabled"]:
  1055. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  1056. client = await get_spoolman_client()
  1057. if not client:
  1058. if sm["url"]:
  1059. client = await init_spoolman_client(sm["url"])
  1060. else:
  1061. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  1062. if not await client.health_check():
  1063. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  1064. result = await db.execute(select(Printer).where(Printer.id == req.printer_id))
  1065. printer = result.scalar_one_or_none()
  1066. if not printer:
  1067. raise HTTPException(status_code=404, detail="Printer not found")
  1068. state = printer_manager.get_status(req.printer_id)
  1069. if not state or not state.raw_data:
  1070. raise HTTPException(status_code=404, detail="Printer not connected or no state available")
  1071. ams_data = state.raw_data.get("ams")
  1072. ams_units: list[dict] = []
  1073. if isinstance(ams_data, list):
  1074. ams_units = ams_data
  1075. elif isinstance(ams_data, dict):
  1076. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  1077. ams_units = ams_data["ams"]
  1078. elif "tray" in ams_data:
  1079. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  1080. tray = None
  1081. for unit in ams_units:
  1082. if not isinstance(unit, dict):
  1083. continue
  1084. if int(unit.get("id", -1)) != req.ams_id:
  1085. continue
  1086. for t in unit.get("tray", []):
  1087. if isinstance(t, dict) and int(t.get("id", -1)) == req.tray_id:
  1088. tray = client.parse_ams_tray(req.ams_id, t)
  1089. break
  1090. if tray:
  1091. break
  1092. if not tray:
  1093. raise HTTPException(status_code=400, detail="Slot is empty or has no readable tray data")
  1094. # Same ghost-spool guard as the inventory route: no tag → no stable
  1095. # identity → confirm would just create a fresh Spoolman row per push.
  1096. from backend.app.services.spool_tag_matcher import is_valid_tag
  1097. if not is_valid_tag(tray.tag_uid or "", tray.tray_uuid or ""):
  1098. raise HTTPException(status_code=400, detail="Slot has no RFID tag")
  1099. sync_result = await client.sync_ams_tray(
  1100. tray,
  1101. printer.name,
  1102. disable_weight_sync=True,
  1103. auto_add_unknown_rfid=True,
  1104. )
  1105. if not sync_result:
  1106. raise HTTPException(status_code=500, detail="Spoolman did not create a spool from the slot")
  1107. # Persist the slot assignment so the new spool shows on the slot tile.
  1108. # If this fails, surface a 500 — silently returning success while the
  1109. # binding rolled back leaves the user thinking the spool was added,
  1110. # then watching the modal re-fire on the next MQTT push.
  1111. if sync_result.get("id"):
  1112. try:
  1113. await db.execute(
  1114. text(
  1115. "INSERT INTO spoolman_slot_assignments"
  1116. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  1117. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  1118. " ON CONFLICT(printer_id, ams_id, tray_id)"
  1119. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  1120. ),
  1121. {
  1122. "printer_id": req.printer_id,
  1123. "ams_id": req.ams_id,
  1124. "tray_id": req.tray_id,
  1125. "spool_id": sync_result["id"],
  1126. },
  1127. )
  1128. await db.commit()
  1129. except Exception as exc:
  1130. await db.rollback()
  1131. logger.exception("Failed to persist Spoolman slot assignment")
  1132. raise HTTPException(
  1133. status_code=500,
  1134. detail=f"Spool created in Spoolman but slot assignment failed: {exc}",
  1135. ) from exc
  1136. return {"success": True, "spool_id": sync_result.get("id")}