spoolman.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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) -> tuple[bool, str, str]:
  40. """Get Spoolman settings from database.
  41. Returns:
  42. Tuple of (enabled, url, sync_mode)
  43. """
  44. enabled = False
  45. url = ""
  46. sync_mode = "auto"
  47. result = await db.execute(select(Settings))
  48. for setting in result.scalars().all():
  49. if setting.key == "spoolman_enabled":
  50. enabled = setting.value.lower() == "true"
  51. elif setting.key == "spoolman_url":
  52. url = setting.value
  53. elif setting.key == "spoolman_sync_mode":
  54. sync_mode = setting.value
  55. return enabled, url, sync_mode
  56. @router.get("/status", response_model=SpoolmanStatus)
  57. async def get_spoolman_status(
  58. db: AsyncSession = Depends(get_db),
  59. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  60. ):
  61. """Get Spoolman integration status."""
  62. enabled, url, _ = await get_spoolman_settings(db)
  63. client = await get_spoolman_client()
  64. connected = False
  65. if client:
  66. connected = await client.health_check()
  67. return SpoolmanStatus(
  68. enabled=enabled,
  69. connected=connected,
  70. url=url if url else None,
  71. )
  72. @router.post("/connect")
  73. async def connect_spoolman(
  74. db: AsyncSession = Depends(get_db),
  75. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  76. ):
  77. """Connect to Spoolman server using configured URL."""
  78. enabled, url, _ = await get_spoolman_settings(db)
  79. if not enabled:
  80. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  81. if not url:
  82. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  83. try:
  84. client = await init_spoolman_client(url)
  85. connected = await client.health_check()
  86. if not connected:
  87. raise HTTPException(
  88. status_code=503,
  89. detail=f"Could not connect to Spoolman at {url}",
  90. )
  91. # Ensure the 'tag' extra field exists for RFID/UUID storage
  92. await client.ensure_tag_extra_field()
  93. return {"success": True, "message": f"Connected to Spoolman at {url}"}
  94. except Exception as e:
  95. logger.error(f"Failed to connect to Spoolman: {e}")
  96. raise HTTPException(status_code=503, detail=str(e))
  97. @router.post("/disconnect")
  98. async def disconnect_spoolman(
  99. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  100. ):
  101. """Disconnect from Spoolman server."""
  102. await close_spoolman_client()
  103. return {"success": True, "message": "Disconnected from Spoolman"}
  104. @router.post("/sync/{printer_id}", response_model=SyncResult)
  105. async def sync_printer_ams(
  106. printer_id: int,
  107. db: AsyncSession = Depends(get_db),
  108. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  109. ):
  110. """Sync AMS data from a specific printer to Spoolman."""
  111. # Check if Spoolman is enabled and connected
  112. enabled, url, _ = await get_spoolman_settings(db)
  113. if not enabled:
  114. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  115. client = await get_spoolman_client()
  116. if not client:
  117. # Try to connect
  118. if url:
  119. client = await init_spoolman_client(url)
  120. else:
  121. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  122. if not await client.health_check():
  123. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  124. # Get printer info
  125. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  126. printer = result.scalar_one_or_none()
  127. if not printer:
  128. raise HTTPException(status_code=404, detail="Printer not found")
  129. # Get current printer state with AMS data
  130. state = printer_manager.get_status(printer_id)
  131. if not state:
  132. raise HTTPException(status_code=404, detail="Printer not connected")
  133. if not state.raw_data:
  134. raise HTTPException(status_code=400, detail="No AMS data available")
  135. ams_data = state.raw_data.get("ams")
  136. if not ams_data:
  137. raise HTTPException(
  138. status_code=400,
  139. detail="No AMS data in printer state. Try triggering a slot re-read on the printer.",
  140. )
  141. # Sync each AMS tray to Spoolman
  142. synced = 0
  143. skipped: list[SkippedSpool] = []
  144. errors = []
  145. # Track tray UUIDs currently in the AMS (for clearing removed spools)
  146. current_tray_uuids: set[str] = set()
  147. # Handle different AMS data structures
  148. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  149. # H2D/newer printers: dict with different structure
  150. ams_units = []
  151. if isinstance(ams_data, list):
  152. ams_units = ams_data
  153. elif isinstance(ams_data, dict):
  154. # H2D format: check for "ams" key containing list, or "tray" key directly
  155. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  156. ams_units = ams_data["ams"]
  157. elif "tray" in ams_data:
  158. # Single AMS unit format - wrap in list
  159. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  160. else:
  161. logger.info(f"AMS dict keys for debugging: {list(ams_data.keys())}")
  162. if not ams_units:
  163. raise HTTPException(
  164. status_code=400,
  165. detail=f"AMS data format not supported. Keys: {list(ams_data.keys()) if isinstance(ams_data, dict) else type(ams_data).__name__}",
  166. )
  167. for ams_unit in ams_units:
  168. if not isinstance(ams_unit, dict):
  169. continue
  170. ams_id = int(ams_unit.get("id", 0))
  171. trays = ams_unit.get("tray", [])
  172. for tray_data in trays:
  173. if not isinstance(tray_data, dict):
  174. continue
  175. tray = client.parse_ams_tray(ams_id, tray_data)
  176. if not tray:
  177. continue # Empty tray - nothing to sync
  178. # Build location string for reporting
  179. location = client.convert_ams_slot_to_location(ams_id, tray.tray_id)
  180. # Skip non-Bambu Lab spools (SpoolEase/third-party) - track as skipped
  181. if not client.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  182. skipped.append(
  183. SkippedSpool(
  184. location=location,
  185. reason="Non-Bambu Lab spool (no RFID tag)",
  186. filament_type=tray.tray_type if tray.tray_type else None,
  187. color=tray.tray_color[:6] if tray.tray_color else None,
  188. )
  189. )
  190. continue
  191. # Track this spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  192. spool_tag = (
  193. tray.tray_uuid
  194. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  195. else tray.tag_uid
  196. )
  197. if spool_tag:
  198. current_tray_uuids.add(spool_tag.upper())
  199. try:
  200. sync_result = await client.sync_ams_tray(tray, printer.name)
  201. if sync_result:
  202. synced += 1
  203. logger.info(f"Synced {tray.tray_sub_brands} from {printer.name} AMS {ams_id} tray {tray.tray_id}")
  204. else:
  205. # Bambu Lab spool that wasn't synced (not found in Spoolman)
  206. errors.append(f"Spool not found in Spoolman: AMS {ams_id}:{tray.tray_id}")
  207. except Exception as e:
  208. error_msg = f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}"
  209. logger.error(error_msg)
  210. errors.append(error_msg)
  211. # Clear location for spools that were removed from this printer's AMS
  212. try:
  213. cleared = await client.clear_location_for_removed_spools(printer.name, current_tray_uuids)
  214. if cleared > 0:
  215. logger.info(f"Cleared location for {cleared} spools removed from {printer.name}")
  216. except Exception as e:
  217. logger.error(f"Error clearing locations for removed spools: {e}")
  218. return SyncResult(
  219. success=len(errors) == 0,
  220. synced_count=synced,
  221. skipped_count=len(skipped),
  222. skipped=skipped,
  223. errors=errors,
  224. )
  225. @router.post("/sync-all", response_model=SyncResult)
  226. async def sync_all_printers(
  227. db: AsyncSession = Depends(get_db),
  228. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  229. ):
  230. """Sync AMS data from all connected printers to Spoolman."""
  231. # Check if Spoolman is enabled
  232. enabled, url, _ = await get_spoolman_settings(db)
  233. if not enabled:
  234. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  235. client = await get_spoolman_client()
  236. if not client:
  237. if url:
  238. client = await init_spoolman_client(url)
  239. else:
  240. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  241. if not await client.health_check():
  242. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  243. # Get all active printers
  244. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  245. printers = result.scalars().all()
  246. total_synced = 0
  247. all_skipped: list[SkippedSpool] = []
  248. all_errors = []
  249. # Track tray UUIDs per printer (for clearing removed spools)
  250. printer_tray_uuids: dict[str, set[str]] = {}
  251. for printer in printers:
  252. state = printer_manager.get_status(printer.id)
  253. if not state or not state.raw_data:
  254. continue
  255. ams_data = state.raw_data.get("ams")
  256. if not ams_data:
  257. continue
  258. # Initialize tray UUID set for this printer
  259. printer_tray_uuids[printer.name] = set()
  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.debug(f"Printer {printer.name} AMS dict keys: {list(ams_data.keys())}")
  275. if not ams_units:
  276. logger.debug(f"Printer {printer.name} has no AMS units to sync (type: {type(ams_data).__name__})")
  277. continue
  278. for ams_unit in ams_units:
  279. if not isinstance(ams_unit, dict):
  280. logger.debug(f"Skipping non-dict AMS unit: {type(ams_unit)}")
  281. continue
  282. ams_id = int(ams_unit.get("id", 0))
  283. trays = ams_unit.get("tray", [])
  284. for tray_data in trays:
  285. if not isinstance(tray_data, dict):
  286. continue
  287. tray = client.parse_ams_tray(ams_id, tray_data)
  288. if not tray:
  289. continue
  290. # Build location string for reporting
  291. location = f"{printer.name} - {client.convert_ams_slot_to_location(ams_id, tray.tray_id)}"
  292. # Skip non-Bambu Lab spools (SpoolEase/third-party) - track as skipped
  293. if not client.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  294. all_skipped.append(
  295. SkippedSpool(
  296. location=location,
  297. reason="Non-Bambu Lab spool (no RFID tag)",
  298. filament_type=tray.tray_type if tray.tray_type else None,
  299. color=tray.tray_color[:6] if tray.tray_color else None,
  300. )
  301. )
  302. continue
  303. # Track this spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  304. spool_tag = (
  305. tray.tray_uuid
  306. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  307. else tray.tag_uid
  308. )
  309. if spool_tag:
  310. printer_tray_uuids[printer.name].add(spool_tag.upper())
  311. try:
  312. sync_result = await client.sync_ams_tray(tray, printer.name)
  313. if sync_result:
  314. total_synced += 1
  315. except Exception as e:
  316. all_errors.append(f"{printer.name} AMS {ams_id}:{tray.tray_id}: {e}")
  317. # Clear location for spools that were removed from each printer's AMS
  318. for printer_name, current_tray_uuids in printer_tray_uuids.items():
  319. try:
  320. cleared = await client.clear_location_for_removed_spools(printer_name, current_tray_uuids)
  321. if cleared > 0:
  322. logger.info(f"Cleared location for {cleared} spools removed from {printer_name}")
  323. except Exception as e:
  324. logger.error(f"Error clearing locations for {printer_name}: {e}")
  325. return SyncResult(
  326. success=len(all_errors) == 0,
  327. synced_count=total_synced,
  328. skipped_count=len(all_skipped),
  329. skipped=all_skipped,
  330. errors=all_errors,
  331. )
  332. @router.get("/spools")
  333. async def get_spools(
  334. db: AsyncSession = Depends(get_db),
  335. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  336. ):
  337. """Get all spools from Spoolman."""
  338. enabled, url, _ = await get_spoolman_settings(db)
  339. if not enabled:
  340. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  341. client = await get_spoolman_client()
  342. if not client:
  343. if url:
  344. client = await init_spoolman_client(url)
  345. else:
  346. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  347. if not await client.health_check():
  348. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  349. spools = await client.get_spools()
  350. return {"spools": spools}
  351. @router.get("/filaments")
  352. async def get_filaments(
  353. db: AsyncSession = Depends(get_db),
  354. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  355. ):
  356. """Get all filaments from Spoolman."""
  357. enabled, url, _ = await get_spoolman_settings(db)
  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. filaments = await client.get_filaments()
  369. return {"filaments": filaments}
  370. class UnlinkedSpool(BaseModel):
  371. """A Spoolman spool that is not linked to any AMS tray."""
  372. id: int
  373. filament_name: str | None
  374. filament_material: str | None
  375. filament_color_hex: str | None
  376. remaining_weight: float | None
  377. location: str | None
  378. @router.get("/spools/unlinked", response_model=list[UnlinkedSpool])
  379. async def get_unlinked_spools(
  380. db: AsyncSession = Depends(get_db),
  381. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  382. ):
  383. """Get all Spoolman spools that don't have a tag (not linked to AMS)."""
  384. enabled, url, _ = await get_spoolman_settings(db)
  385. if not enabled:
  386. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  387. client = await get_spoolman_client()
  388. if not client:
  389. if url:
  390. client = await init_spoolman_client(url)
  391. else:
  392. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  393. if not await client.health_check():
  394. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  395. spools = await client.get_spools()
  396. unlinked = []
  397. for spool in spools:
  398. # Check if spool has a tag in extra field
  399. extra = spool.get("extra", {}) or {}
  400. tag = extra.get("tag", "")
  401. # Remove quotes if present (JSON encoded string) and check if empty
  402. clean_tag = tag.strip('"') if tag else ""
  403. if not clean_tag:
  404. filament = spool.get("filament", {}) or {}
  405. unlinked.append(
  406. UnlinkedSpool(
  407. id=spool["id"],
  408. filament_name=filament.get("name"),
  409. filament_material=filament.get("material"),
  410. filament_color_hex=filament.get("color_hex"),
  411. remaining_weight=spool.get("remaining_weight"),
  412. location=spool.get("location"),
  413. )
  414. )
  415. return unlinked
  416. @router.get("/spools/linked")
  417. async def get_linked_spools(
  418. db: AsyncSession = Depends(get_db),
  419. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  420. ):
  421. """Get a map of tag -> spool_id for all Spoolman spools that have a tag assigned."""
  422. enabled, url, _ = await get_spoolman_settings(db)
  423. if not enabled:
  424. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  425. client = await get_spoolman_client()
  426. if not client:
  427. if url:
  428. client = await init_spoolman_client(url)
  429. else:
  430. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  431. if not await client.health_check():
  432. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  433. spools = await client.get_spools()
  434. linked: dict[str, int] = {}
  435. for spool in spools:
  436. # Check if spool has a tag in extra field
  437. extra = spool.get("extra", {}) or {}
  438. tag = extra.get("tag", "")
  439. if tag:
  440. # Remove quotes if present (JSON encoded string)
  441. clean_tag = tag.strip('"').upper()
  442. if clean_tag:
  443. linked[clean_tag] = spool["id"]
  444. return {"linked": linked}
  445. class LinkSpoolRequest(BaseModel):
  446. """Request to link a Spoolman spool to an AMS tray."""
  447. tray_uuid: str
  448. @router.post("/spools/{spool_id}/link")
  449. async def link_spool(
  450. spool_id: int,
  451. request: LinkSpoolRequest,
  452. db: AsyncSession = Depends(get_db),
  453. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_UPDATE),
  454. ):
  455. """Link a Spoolman spool to an AMS tray by setting the tag to tray_uuid."""
  456. enabled, url, _ = await get_spoolman_settings(db)
  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. # Validate tray_uuid format (32 hex characters)
  468. tray_uuid = request.tray_uuid.strip()
  469. if len(tray_uuid) != 32:
  470. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be 32 hex characters)")
  471. try:
  472. int(tray_uuid, 16)
  473. except ValueError:
  474. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be hex)")
  475. # Update spool with tag
  476. # Note: Spoolman extra field values must be valid JSON, so we encode the string
  477. import json
  478. result = await client.update_spool(
  479. spool_id=spool_id,
  480. extra={"tag": json.dumps(tray_uuid)},
  481. )
  482. if result:
  483. logger.info(f"Linked Spoolman spool {spool_id} to tray_uuid {tray_uuid}")
  484. return {"success": True, "message": f"Spool {spool_id} linked to AMS tray"}
  485. else:
  486. raise HTTPException(status_code=500, detail="Failed to update spool")