spoolman.py 18 KB

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