spoolman.py 53 KB

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