spoolman.py 21 KB

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