spoolman.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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, tray.tag_uid, tray.tray_info_idx):
  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 spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  178. spool_tag = (
  179. tray.tray_uuid
  180. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  181. else tray.tag_uid
  182. )
  183. if spool_tag:
  184. current_tray_uuids.add(spool_tag.upper())
  185. try:
  186. sync_result = await client.sync_ams_tray(tray, printer.name)
  187. if sync_result:
  188. synced += 1
  189. logger.info(f"Synced {tray.tray_sub_brands} from {printer.name} AMS {ams_id} tray {tray.tray_id}")
  190. else:
  191. # Bambu Lab spool that wasn't synced (not found in Spoolman)
  192. errors.append(f"Spool not found in Spoolman: AMS {ams_id}:{tray.tray_id}")
  193. except Exception as e:
  194. error_msg = f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}"
  195. logger.error(error_msg)
  196. errors.append(error_msg)
  197. # Clear location for spools that were removed from this printer's AMS
  198. try:
  199. cleared = await client.clear_location_for_removed_spools(printer.name, current_tray_uuids)
  200. if cleared > 0:
  201. logger.info(f"Cleared location for {cleared} spools removed from {printer.name}")
  202. except Exception as e:
  203. logger.error(f"Error clearing locations for removed spools: {e}")
  204. return SyncResult(
  205. success=len(errors) == 0,
  206. synced_count=synced,
  207. skipped_count=len(skipped),
  208. skipped=skipped,
  209. errors=errors,
  210. )
  211. @router.post("/sync-all", response_model=SyncResult)
  212. async def sync_all_printers(db: AsyncSession = Depends(get_db)):
  213. """Sync AMS data from all connected printers to Spoolman."""
  214. # Check if Spoolman is enabled
  215. enabled, url, _ = await get_spoolman_settings(db)
  216. if not enabled:
  217. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  218. client = await get_spoolman_client()
  219. if not client:
  220. if url:
  221. client = await init_spoolman_client(url)
  222. else:
  223. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  224. if not await client.health_check():
  225. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  226. # Get all active printers
  227. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  228. printers = result.scalars().all()
  229. total_synced = 0
  230. all_skipped: list[SkippedSpool] = []
  231. all_errors = []
  232. # Track tray UUIDs per printer (for clearing removed spools)
  233. printer_tray_uuids: dict[str, set[str]] = {}
  234. for printer in printers:
  235. state = printer_manager.get_status(printer.id)
  236. if not state or not state.raw_data:
  237. continue
  238. ams_data = state.raw_data.get("ams")
  239. if not ams_data:
  240. continue
  241. # Initialize tray UUID set for this printer
  242. printer_tray_uuids[printer.name] = set()
  243. # Handle different AMS data structures
  244. # Traditional AMS: list of {"id": N, "tray": [...]} dicts
  245. # H2D/newer printers: dict with different structure
  246. ams_units = []
  247. if isinstance(ams_data, list):
  248. ams_units = ams_data
  249. elif isinstance(ams_data, dict):
  250. # H2D format: check for "ams" key containing list, or "tray" key directly
  251. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  252. ams_units = ams_data["ams"]
  253. elif "tray" in ams_data:
  254. # Single AMS unit format - wrap in list
  255. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  256. else:
  257. logger.debug(f"Printer {printer.name} AMS dict keys: {list(ams_data.keys())}")
  258. if not ams_units:
  259. logger.debug(f"Printer {printer.name} has no AMS units to sync (type: {type(ams_data).__name__})")
  260. continue
  261. for ams_unit in ams_units:
  262. if not isinstance(ams_unit, dict):
  263. logger.debug(f"Skipping non-dict AMS unit: {type(ams_unit)}")
  264. continue
  265. ams_id = int(ams_unit.get("id", 0))
  266. trays = ams_unit.get("tray", [])
  267. for tray_data in trays:
  268. if not isinstance(tray_data, dict):
  269. continue
  270. tray = client.parse_ams_tray(ams_id, tray_data)
  271. if not tray:
  272. continue
  273. # Build location string for reporting
  274. location = f"{printer.name} - {client.convert_ams_slot_to_location(ams_id, tray.tray_id)}"
  275. # Skip non-Bambu Lab spools (SpoolEase/third-party) - track as skipped
  276. if not client.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  277. all_skipped.append(
  278. SkippedSpool(
  279. location=location,
  280. reason="Non-Bambu Lab spool (no RFID tag)",
  281. filament_type=tray.tray_type if tray.tray_type else None,
  282. color=tray.tray_color[:6] if tray.tray_color else None,
  283. )
  284. )
  285. continue
  286. # Track this spool tag as currently present in the AMS (prefer tray_uuid, fallback to tag_uid)
  287. spool_tag = (
  288. tray.tray_uuid
  289. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  290. else tray.tag_uid
  291. )
  292. if spool_tag:
  293. printer_tray_uuids[printer.name].add(spool_tag.upper())
  294. try:
  295. sync_result = await client.sync_ams_tray(tray, printer.name)
  296. if sync_result:
  297. total_synced += 1
  298. except Exception as e:
  299. all_errors.append(f"{printer.name} AMS {ams_id}:{tray.tray_id}: {e}")
  300. # Clear location for spools that were removed from each printer's AMS
  301. for printer_name, current_tray_uuids in printer_tray_uuids.items():
  302. try:
  303. cleared = await client.clear_location_for_removed_spools(printer_name, current_tray_uuids)
  304. if cleared > 0:
  305. logger.info(f"Cleared location for {cleared} spools removed from {printer_name}")
  306. except Exception as e:
  307. logger.error(f"Error clearing locations for {printer_name}: {e}")
  308. return SyncResult(
  309. success=len(all_errors) == 0,
  310. synced_count=total_synced,
  311. skipped_count=len(all_skipped),
  312. skipped=all_skipped,
  313. errors=all_errors,
  314. )
  315. @router.get("/spools")
  316. async def get_spools(db: AsyncSession = Depends(get_db)):
  317. """Get all spools from Spoolman."""
  318. enabled, url, _ = await get_spoolman_settings(db)
  319. if not enabled:
  320. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  321. client = await get_spoolman_client()
  322. if not client:
  323. if url:
  324. client = await init_spoolman_client(url)
  325. else:
  326. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  327. if not await client.health_check():
  328. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  329. spools = await client.get_spools()
  330. return {"spools": spools}
  331. @router.get("/filaments")
  332. async def get_filaments(db: AsyncSession = Depends(get_db)):
  333. """Get all filaments from Spoolman."""
  334. enabled, url, _ = await get_spoolman_settings(db)
  335. if not enabled:
  336. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  337. client = await get_spoolman_client()
  338. if not client:
  339. if url:
  340. client = await init_spoolman_client(url)
  341. else:
  342. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  343. if not await client.health_check():
  344. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  345. filaments = await client.get_filaments()
  346. return {"filaments": filaments}
  347. class UnlinkedSpool(BaseModel):
  348. """A Spoolman spool that is not linked to any AMS tray."""
  349. id: int
  350. filament_name: str | None
  351. filament_material: str | None
  352. filament_color_hex: str | None
  353. remaining_weight: float | None
  354. location: str | None
  355. @router.get("/spools/unlinked", response_model=list[UnlinkedSpool])
  356. async def get_unlinked_spools(db: AsyncSession = Depends(get_db)):
  357. """Get all Spoolman spools that don't have a tag (not linked to AMS)."""
  358. enabled, url, _ = await get_spoolman_settings(db)
  359. if not enabled:
  360. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  361. client = await get_spoolman_client()
  362. if not client:
  363. if url:
  364. client = await init_spoolman_client(url)
  365. else:
  366. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  367. if not await client.health_check():
  368. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  369. spools = await client.get_spools()
  370. unlinked = []
  371. for spool in spools:
  372. # Check if spool has a tag in extra field
  373. extra = spool.get("extra", {}) or {}
  374. tag = extra.get("tag", "")
  375. if not tag:
  376. filament = spool.get("filament", {}) or {}
  377. unlinked.append(
  378. UnlinkedSpool(
  379. id=spool["id"],
  380. filament_name=filament.get("name"),
  381. filament_material=filament.get("material"),
  382. filament_color_hex=filament.get("color_hex"),
  383. remaining_weight=spool.get("remaining_weight"),
  384. location=spool.get("location"),
  385. )
  386. )
  387. return unlinked
  388. class LinkSpoolRequest(BaseModel):
  389. """Request to link a Spoolman spool to an AMS tray."""
  390. tray_uuid: str
  391. @router.post("/spools/{spool_id}/link")
  392. async def link_spool(
  393. spool_id: int,
  394. request: LinkSpoolRequest,
  395. db: AsyncSession = Depends(get_db),
  396. ):
  397. """Link a Spoolman spool to an AMS tray by setting the tag to tray_uuid."""
  398. enabled, url, _ = await get_spoolman_settings(db)
  399. if not enabled:
  400. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  401. client = await get_spoolman_client()
  402. if not client:
  403. if url:
  404. client = await init_spoolman_client(url)
  405. else:
  406. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  407. if not await client.health_check():
  408. raise HTTPException(status_code=503, detail="Spoolman is not reachable")
  409. # Validate tray_uuid format (32 hex characters)
  410. tray_uuid = request.tray_uuid.strip()
  411. if len(tray_uuid) != 32:
  412. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be 32 hex characters)")
  413. try:
  414. int(tray_uuid, 16)
  415. except ValueError:
  416. raise HTTPException(status_code=400, detail="Invalid tray_uuid format (must be hex)")
  417. # Update spool with tag
  418. # Note: Spoolman extra field values must be valid JSON, so we encode the string
  419. import json
  420. result = await client.update_spool(
  421. spool_id=spool_id,
  422. extra={"tag": json.dumps(tray_uuid)},
  423. )
  424. if result:
  425. logger.info(f"Linked Spoolman spool {spool_id} to tray_uuid {tray_uuid}")
  426. return {"success": True, "message": f"Spool {spool_id} linked to AMS tray"}
  427. else:
  428. raise HTTPException(status_code=500, detail="Failed to update spool")