spoolman.py 19 KB

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