spoolman.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. """Spoolman integration API routes."""
  2. import logging
  3. from fastapi import APIRouter, Depends, HTTPException
  4. from pydantic import BaseModel
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  8. from backend.app.core.database import get_db
  9. from backend.app.core.permissions import Permission
  10. from backend.app.models.printer import Printer
  11. from backend.app.models.settings import Settings
  12. from backend.app.models.user import User
  13. from backend.app.services.printer_manager import printer_manager
  14. from backend.app.services.spoolman import (
  15. close_spoolman_client,
  16. get_spoolman_client,
  17. init_spoolman_client,
  18. )
  19. logger = logging.getLogger(__name__)
  20. router = APIRouter(prefix="/spoolman", tags=["spoolman"])
  21. class SpoolmanStatus(BaseModel):
  22. """Spoolman connection status."""
  23. enabled: bool
  24. connected: bool
  25. url: str | None
  26. class SkippedSpool(BaseModel):
  27. """Information about a skipped spool during sync."""
  28. location: str # e.g., "AMS A1" or "External Spool"
  29. reason: str # e.g., "Not a Bambu Lab spool", "Empty tray"
  30. filament_type: str | None = None # e.g., "PLA", "PETG"
  31. color: str | None = None # Hex color
  32. class SyncResult(BaseModel):
  33. """Result of a Spoolman sync operation."""
  34. success: bool
  35. synced_count: int
  36. skipped_count: int = 0
  37. skipped: list[SkippedSpool] = []
  38. errors: list[str]
  39. async def get_spoolman_settings(db: AsyncSession) -> dict:
  40. """Get Spoolman settings from database.
  41. Returns:
  42. Dict with keys: enabled, url, sync_mode, disable_weight_sync
  43. """
  44. settings = {
  45. "enabled": False,
  46. "url": "",
  47. "sync_mode": "auto",
  48. "disable_weight_sync": False,
  49. }
  50. result = await db.execute(select(Settings))
  51. for setting in result.scalars().all():
  52. if setting.key == "spoolman_enabled":
  53. settings["enabled"] = setting.value.lower() == "true"
  54. elif setting.key == "spoolman_url":
  55. settings["url"] = setting.value
  56. elif setting.key == "spoolman_sync_mode":
  57. settings["sync_mode"] = setting.value
  58. elif setting.key == "spoolman_disable_weight_sync":
  59. settings["disable_weight_sync"] = setting.value.lower() == "true"
  60. return settings
  61. @router.get("/status", response_model=SpoolmanStatus)
  62. async def get_spoolman_status(
  63. db: AsyncSession = Depends(get_db),
  64. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  65. ):
  66. """Get Spoolman integration status."""
  67. sm = await get_spoolman_settings(db)
  68. enabled, url = sm["enabled"], sm["url"]
  69. client = await get_spoolman_client()
  70. connected = False
  71. if client:
  72. connected = await client.health_check()
  73. return SpoolmanStatus(
  74. enabled=enabled,
  75. connected=connected,
  76. url=url if url else None,
  77. )
  78. @router.post("/connect")
  79. async def connect_spoolman(
  80. db: AsyncSession = Depends(get_db),
  81. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  82. ):
  83. """Connect to Spoolman server using configured URL."""
  84. sm = await get_spoolman_settings(db)
  85. enabled, url = sm["enabled"], sm["url"]
  86. if not enabled:
  87. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  88. if not url:
  89. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  90. try:
  91. client = await init_spoolman_client(url)
  92. connected = await client.health_check()
  93. if not connected:
  94. raise HTTPException(
  95. status_code=503,
  96. detail=f"Could not connect to Spoolman at {url}",
  97. )
  98. # Ensure the 'tag' extra field exists for RFID/UUID storage
  99. await client.ensure_tag_extra_field()
  100. return {"success": True, "message": f"Connected to Spoolman at {url}"}
  101. except Exception as e:
  102. logger.error("Failed to connect to Spoolman: %s", e)
  103. raise HTTPException(status_code=503, detail=str(e))
  104. @router.post("/disconnect")
  105. async def disconnect_spoolman(
  106. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  107. ):
  108. """Disconnect from Spoolman server."""
  109. await close_spoolman_client()
  110. return {"success": True, "message": "Disconnected from Spoolman"}
  111. @router.post("/sync/{printer_id}", response_model=SyncResult)
  112. async def sync_printer_ams(
  113. printer_id: int,
  114. db: AsyncSession = Depends(get_db),
  115. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  116. ):
  117. """Sync AMS data from a specific printer to Spoolman."""
  118. # Check if Spoolman is enabled and connected
  119. sm = await get_spoolman_settings(db)
  120. enabled, url, disable_weight_sync = sm["enabled"], sm["url"], sm["disable_weight_sync"]
  121. if not enabled:
  122. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  123. client = await get_spoolman_client()
  124. if not client:
  125. # Try to connect
  126. if url:
  127. client = await init_spoolman_client(url)
  128. else:
  129. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  130. if not await client.health_check():
  131. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  132. # Get printer info
  133. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  134. printer = result.scalar_one_or_none()
  135. if not printer:
  136. raise HTTPException(status_code=404, detail="Printer not found")
  137. # Get current printer state with AMS data
  138. state = printer_manager.get_status(printer_id)
  139. if not state:
  140. raise HTTPException(status_code=404, detail="Printer not connected")
  141. if not state.raw_data:
  142. raise HTTPException(status_code=400, detail="No AMS data available")
  143. ams_data = state.raw_data.get("ams")
  144. if not ams_data:
  145. raise HTTPException(
  146. status_code=400,
  147. detail="No AMS data in printer state. Try triggering a slot re-read on the printer.",
  148. )
  149. # Sync each AMS tray to Spoolman
  150. synced = 0
  151. skipped: list[SkippedSpool] = []
  152. errors = []
  153. # Track tray UUIDs currently in the AMS (for clearing removed spools)
  154. current_tray_uuids: set[str] = set()
  155. # Handle different AMS data structures
  156. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  157. # H2D/newer printers: dict with different structure
  158. ams_units = []
  159. if isinstance(ams_data, list):
  160. ams_units = ams_data
  161. elif isinstance(ams_data, dict):
  162. # H2D format: check for "ams" key containing list, or "tray" key directly
  163. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  164. ams_units = ams_data["ams"]
  165. elif "tray" in ams_data:
  166. # Single AMS unit format - wrap in list
  167. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  168. else:
  169. logger.info("AMS dict keys for debugging: %s", list(ams_data.keys()))
  170. if not ams_units:
  171. raise HTTPException(
  172. status_code=400,
  173. detail=f"AMS data format not supported. Keys: {list(ams_data.keys()) if isinstance(ams_data, dict) else type(ams_data).__name__}",
  174. )
  175. # OPTIMIZATION: Fetch all spools once before processing trays
  176. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  177. logger.debug("[Printer %s] Fetching spools cache for sync...", printer.name)
  178. try:
  179. cached_spools = await client.get_spools()
  180. logger.debug("[Printer %s] Cached %d spools for batch sync", printer.name, len(cached_spools))
  181. except Exception as e:
  182. logger.error("[Printer %s] Failed to fetch spools cache after retries: %s", printer.name, e)
  183. raise HTTPException(
  184. status_code=503,
  185. detail=f"Failed to connect to Spoolman after multiple retries: {str(e)}",
  186. )
  187. for ams_unit in ams_units:
  188. if not isinstance(ams_unit, dict):
  189. continue
  190. ams_id = int(ams_unit.get("id", 0))
  191. trays = ams_unit.get("tray", [])
  192. for tray_data in trays:
  193. if not isinstance(tray_data, dict):
  194. continue
  195. tray = client.parse_ams_tray(ams_id, tray_data)
  196. if not tray:
  197. continue # Empty tray - nothing to sync
  198. # Build location string for reporting
  199. location = client.convert_ams_slot_to_location(ams_id, tray.tray_id)
  200. # Skip non-Bambu Lab spools (SpoolEase/third-party) - track as skipped
  201. if not client.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  202. skipped.append(
  203. SkippedSpool(
  204. location=location,
  205. reason="Non-Bambu Lab spool (no RFID tag)",
  206. filament_type=tray.tray_type if tray.tray_type else None,
  207. color=tray.tray_color[:6] if tray.tray_color else None,
  208. )
  209. )
  210. continue
  211. # Track this spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  212. spool_tag = (
  213. tray.tray_uuid
  214. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  215. else tray.tag_uid
  216. )
  217. if spool_tag:
  218. current_tray_uuids.add(spool_tag.upper())
  219. try:
  220. sync_result = await client.sync_ams_tray(
  221. tray,
  222. printer.name,
  223. disable_weight_sync=disable_weight_sync,
  224. cached_spools=cached_spools,
  225. )
  226. if sync_result:
  227. synced += 1
  228. # Add newly created spool to cache
  229. if sync_result.get("id"):
  230. spool_exists = any(s.get("id") == sync_result["id"] for s in cached_spools)
  231. if not spool_exists:
  232. cached_spools.append(sync_result)
  233. logger.debug("Added newly created spool %s to cache", sync_result["id"])
  234. logger.info(
  235. "Synced %s from %s AMS %s tray %s", tray.tray_sub_brands, printer.name, ams_id, tray.tray_id
  236. )
  237. else:
  238. # Bambu Lab spool that wasn't synced (not found in Spoolman)
  239. errors.append(f"Spool not found in Spoolman: AMS {ams_id}:{tray.tray_id}")
  240. except Exception as e:
  241. error_msg = f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}"
  242. logger.error(error_msg)
  243. errors.append(error_msg)
  244. # Clear location for spools that were removed from this printer's AMS
  245. try:
  246. cleared = await client.clear_location_for_removed_spools(
  247. printer.name, current_tray_uuids, cached_spools=cached_spools
  248. )
  249. if cleared > 0:
  250. logger.info("Cleared location for %s spools removed from %s", cleared, printer.name)
  251. except Exception as e:
  252. logger.error("Error clearing locations for removed spools: %s", e)
  253. return SyncResult(
  254. success=len(errors) == 0,
  255. synced_count=synced,
  256. skipped_count=len(skipped),
  257. skipped=skipped,
  258. errors=errors,
  259. )
  260. @router.post("/sync-all", response_model=SyncResult)
  261. async def sync_all_printers(
  262. db: AsyncSession = Depends(get_db),
  263. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  264. ):
  265. """Sync AMS data from all connected printers to Spoolman."""
  266. # Check if Spoolman is enabled
  267. sm = await get_spoolman_settings(db)
  268. enabled, url, disable_weight_sync = sm["enabled"], sm["url"], sm["disable_weight_sync"]
  269. if not enabled:
  270. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  271. client = await get_spoolman_client()
  272. if not client:
  273. if url:
  274. client = await init_spoolman_client(url)
  275. else:
  276. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  277. if not await client.health_check():
  278. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  279. # Get all active printers
  280. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  281. printers = result.scalars().all()
  282. total_synced = 0
  283. all_skipped: list[SkippedSpool] = []
  284. all_errors = []
  285. # Track tray UUIDs per printer (for clearing removed spools)
  286. printer_tray_uuids: dict[str, set[str]] = {}
  287. # Track synced spool IDs per printer (for location-based cleanup when no UUIDs available)
  288. printer_synced_ids: dict[str, set[int]] = {}
  289. # OPTIMIZATION: Fetch all spools once before processing ALL printers/trays
  290. # This eliminates redundant API calls across all printers
  291. logger.debug("Fetching spools cache for sync-all operation...")
  292. try:
  293. cached_spools = await client.get_spools()
  294. logger.debug("Cached %d spools for batch sync across %d printers", len(cached_spools), len(printers))
  295. except Exception as e:
  296. logger.error("Failed to fetch spools cache after retries: %s", e)
  297. raise HTTPException(
  298. status_code=503,
  299. detail=f"Failed to connect to Spoolman after multiple retries: {str(e)}",
  300. )
  301. for printer in printers:
  302. state = printer_manager.get_status(printer.id)
  303. if not state or not state.raw_data:
  304. continue
  305. ams_data = state.raw_data.get("ams")
  306. if not ams_data:
  307. continue
  308. # Initialize tracking sets for this printer
  309. printer_tray_uuids[printer.name] = set()
  310. printer_synced_ids[printer.name] = set()
  311. # Handle different AMS data structures
  312. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  313. # H2D/newer printers: dict with different structure
  314. ams_units = []
  315. if isinstance(ams_data, list):
  316. ams_units = ams_data
  317. elif isinstance(ams_data, dict):
  318. # H2D format: check for "ams" key containing list, or "tray" key directly
  319. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  320. ams_units = ams_data["ams"]
  321. elif "tray" in ams_data:
  322. # Single AMS unit format - wrap in list
  323. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  324. else:
  325. logger.debug("Printer %s AMS dict keys: %s", printer.name, list(ams_data.keys()))
  326. if not ams_units:
  327. logger.debug("Printer %s has no AMS units to sync (type: %s)", printer.name, type(ams_data).__name__)
  328. continue
  329. for ams_unit in ams_units:
  330. if not isinstance(ams_unit, dict):
  331. logger.debug("Skipping non-dict AMS unit: %s", type(ams_unit))
  332. continue
  333. ams_id = int(ams_unit.get("id", 0))
  334. trays = ams_unit.get("tray", [])
  335. for tray_data in trays:
  336. if not isinstance(tray_data, dict):
  337. continue
  338. tray = client.parse_ams_tray(ams_id, tray_data)
  339. if not tray:
  340. continue
  341. # Build location string for reporting
  342. location = f"{printer.name} - {client.convert_ams_slot_to_location(ams_id, tray.tray_id)}"
  343. # Skip non-Bambu Lab spools (SpoolEase/third-party) - track as skipped
  344. if not client.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  345. all_skipped.append(
  346. SkippedSpool(
  347. location=location,
  348. reason="Non-Bambu Lab spool (no RFID tag)",
  349. filament_type=tray.tray_type if tray.tray_type else None,
  350. color=tray.tray_color[:6] if tray.tray_color else None,
  351. )
  352. )
  353. continue
  354. # Track this spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  355. spool_tag = (
  356. tray.tray_uuid
  357. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  358. else tray.tag_uid
  359. )
  360. if spool_tag:
  361. printer_tray_uuids[printer.name].add(spool_tag.upper())
  362. try:
  363. sync_result = await client.sync_ams_tray(
  364. tray,
  365. printer.name,
  366. disable_weight_sync=disable_weight_sync,
  367. cached_spools=cached_spools,
  368. )
  369. if sync_result:
  370. total_synced += 1
  371. # Track synced spool ID for cleanup
  372. if sync_result.get("id"):
  373. printer_synced_ids[printer.name].add(sync_result["id"])
  374. # Add newly created spool to cache
  375. spool_exists = any(s.get("id") == sync_result["id"] for s in cached_spools)
  376. if not spool_exists:
  377. cached_spools.append(sync_result)
  378. logger.debug("Added newly created spool %s to cache", sync_result["id"])
  379. except Exception as e:
  380. all_errors.append(f"{printer.name} AMS {ams_id}:{tray.tray_id}: {e}")
  381. # Clear location for spools that were removed from each printer's AMS
  382. for printer_name, current_tray_uuids in printer_tray_uuids.items():
  383. try:
  384. cleared = await client.clear_location_for_removed_spools(
  385. printer_name,
  386. current_tray_uuids,
  387. cached_spools=cached_spools,
  388. synced_spool_ids=printer_synced_ids.get(printer_name, set()),
  389. )
  390. if cleared > 0:
  391. logger.info("Cleared location for %s spools removed from %s", cleared, printer_name)
  392. except Exception as e:
  393. logger.error("Error clearing locations for %s: %s", printer_name, e)
  394. return SyncResult(
  395. success=len(all_errors) == 0,
  396. synced_count=total_synced,
  397. skipped_count=len(all_skipped),
  398. skipped=all_skipped,
  399. errors=all_errors,
  400. )
  401. @router.get("/spools")
  402. async def get_spools(
  403. db: AsyncSession = Depends(get_db),
  404. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  405. ):
  406. """Get all spools from Spoolman."""
  407. sm = await get_spoolman_settings(db)
  408. enabled, url = sm["enabled"], sm["url"]
  409. if not enabled:
  410. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  411. client = await get_spoolman_client()
  412. if not client:
  413. if url:
  414. client = await init_spoolman_client(url)
  415. else:
  416. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  417. if not await client.health_check():
  418. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  419. spools = await client.get_spools()
  420. return {"spools": spools}
  421. @router.get("/filaments")
  422. async def get_filaments(
  423. db: AsyncSession = Depends(get_db),
  424. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  425. ):
  426. """Get all filaments from Spoolman."""
  427. sm = await get_spoolman_settings(db)
  428. enabled, url = sm["enabled"], sm["url"]
  429. if not enabled:
  430. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  431. client = await get_spoolman_client()
  432. if not client:
  433. if url:
  434. client = await init_spoolman_client(url)
  435. else:
  436. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  437. if not await client.health_check():
  438. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  439. filaments = await client.get_filaments()
  440. return {"filaments": filaments}
  441. class UnlinkedSpool(BaseModel):
  442. """A Spoolman spool that is not linked to any AMS tray."""
  443. id: int
  444. filament_name: str | None
  445. filament_material: str | None
  446. filament_color_hex: str | None
  447. remaining_weight: float | None
  448. location: str | None
  449. @router.get("/spools/unlinked", response_model=list[UnlinkedSpool])
  450. async def get_unlinked_spools(
  451. db: AsyncSession = Depends(get_db),
  452. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  453. ):
  454. """Get all Spoolman spools that don't have a tag (not linked to AMS)."""
  455. sm = await get_spoolman_settings(db)
  456. enabled, url = sm["enabled"], sm["url"]
  457. if not enabled:
  458. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  459. client = await get_spoolman_client()
  460. if not client:
  461. if url:
  462. client = await init_spoolman_client(url)
  463. else:
  464. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  465. if not await client.health_check():
  466. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  467. spools = await client.get_spools()
  468. unlinked = []
  469. for spool in spools:
  470. # Check if spool has a tag in extra field
  471. extra = spool.get("extra", {}) or {}
  472. tag = extra.get("tag", "")
  473. # Remove quotes if present (JSON encoded string) and check if empty
  474. clean_tag = tag.strip('"') if tag else ""
  475. if not clean_tag:
  476. filament = spool.get("filament", {}) or {}
  477. unlinked.append(
  478. UnlinkedSpool(
  479. id=spool["id"],
  480. filament_name=filament.get("name"),
  481. filament_material=filament.get("material"),
  482. filament_color_hex=filament.get("color_hex"),
  483. remaining_weight=spool.get("remaining_weight"),
  484. location=spool.get("location"),
  485. )
  486. )
  487. return unlinked
  488. @router.get("/spools/linked")
  489. async def get_linked_spools(
  490. db: AsyncSession = Depends(get_db),
  491. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  492. ):
  493. """Get a map of tag -> spool_id for all Spoolman spools that have a tag assigned."""
  494. sm = await get_spoolman_settings(db)
  495. enabled, url = sm["enabled"], sm["url"]
  496. if not enabled:
  497. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  498. client = await get_spoolman_client()
  499. if not client:
  500. if url:
  501. client = await init_spoolman_client(url)
  502. else:
  503. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  504. if not await client.health_check():
  505. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  506. spools = await client.get_spools()
  507. linked: dict[str, dict] = {}
  508. for spool in spools:
  509. # Check if spool has a tag in extra field
  510. extra = spool.get("extra", {}) or {}
  511. tag = extra.get("tag", "")
  512. if tag:
  513. # Remove quotes if present (JSON encoded string)
  514. clean_tag = tag.strip('"').upper()
  515. if clean_tag:
  516. filament = spool.get("filament") or {}
  517. linked[clean_tag] = {
  518. "id": spool["id"],
  519. "remaining_weight": spool.get("remaining_weight"),
  520. "filament_weight": filament.get("weight"),
  521. }
  522. return {"linked": linked}
  523. class LinkSpoolRequest(BaseModel):
  524. """Request to link a Spoolman spool to an AMS tray."""
  525. tray_uuid: str
  526. @router.post("/spools/{spool_id}/link")
  527. async def link_spool(
  528. spool_id: int,
  529. request: LinkSpoolRequest,
  530. db: AsyncSession = Depends(get_db),
  531. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  532. ):
  533. """Link a Spoolman spool to an AMS tray by setting the tag to tray_uuid."""
  534. sm = await get_spoolman_settings(db)
  535. enabled, url = sm["enabled"], sm["url"]
  536. if not enabled:
  537. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  538. client = await get_spoolman_client()
  539. if not client:
  540. if url:
  541. client = await init_spoolman_client(url)
  542. else:
  543. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  544. if not await client.health_check():
  545. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  546. # Validate tray_uuid format (32 hex characters)
  547. tray_uuid = request.tray_uuid.strip()
  548. if len(tray_uuid) != 32:
  549. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be 32 hex characters)")
  550. try:
  551. int(tray_uuid, 16)
  552. except ValueError:
  553. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be hex)")
  554. # Update spool with tag
  555. # Note: Spoolman extra field values must be valid JSON, so we encode the string
  556. import json
  557. result = await client.update_spool(
  558. spool_id=spool_id,
  559. extra={"tag": json.dumps(tray_uuid)},
  560. )
  561. if result:
  562. logger.info("Linked Spoolman spool %s to tray_uuid %s", spool_id, tray_uuid)
  563. return {"success": True, "message": f"Spool {spool_id} linked to AMS tray"}
  564. else:
  565. raise HTTPException(status_code=500, detail="Failed to update spool")