spoolman.py 61 KB

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