spoolman.py 56 KB

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