spoolman.py 57 KB

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