spoolman.py 52 KB

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