spoolman.py 60 KB

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