spoolman.py 22 KB

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