spoolman.py 55 KB

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