spoolman.py 59 KB

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