spoolman.py 61 KB

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