spoolman.py 57 KB

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