spoolman.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. """Spoolman integration service for syncing AMS filament data."""
  2. import asyncio
  3. import logging
  4. from dataclasses import dataclass
  5. from datetime import datetime, timezone
  6. import httpx
  7. logger = logging.getLogger(__name__)
  8. @dataclass
  9. class SpoolmanSpool:
  10. """Represents a spool in Spoolman."""
  11. id: int
  12. filament_id: int | None
  13. remaining_weight: float | None
  14. used_weight: float
  15. first_used: str | None
  16. last_used: str | None
  17. location: str | None
  18. lot_nr: str | None
  19. comment: str | None
  20. extra: dict | None # Contains tag_uid in extra.tag
  21. @dataclass
  22. class SpoolmanFilament:
  23. """Represents a filament type in Spoolman."""
  24. id: int
  25. name: str
  26. vendor_id: int | None
  27. material: str | None
  28. color_hex: str | None
  29. weight: float | None # Net weight in grams
  30. @dataclass
  31. class AMSTray:
  32. """Represents an AMS tray with filament data from Bambu printer."""
  33. ams_id: int # 0-3 for regular AMS, 128-135 for external spool
  34. tray_id: int # 0-3
  35. tray_type: str # PLA, PETG, ABS, etc.
  36. tray_sub_brands: str # Full name like "PLA Basic", "PETG HF"
  37. tray_color: str # Hex color like "FEC600FF"
  38. remain: int # Remaining percentage (0-100)
  39. tag_uid: str # RFID tag UID
  40. tray_uuid: str # Spool UUID
  41. tray_info_idx: str # Bambu filament preset ID like "GFA00"
  42. tray_weight: int # Spool weight in grams (usually 1000)
  43. class SpoolmanClient:
  44. """Client for interacting with Spoolman API."""
  45. def __init__(self, base_url: str):
  46. """Initialize the Spoolman client.
  47. Args:
  48. base_url: The base URL of the Spoolman server (e.g., http://localhost:7912)
  49. """
  50. self.base_url = base_url.rstrip("/")
  51. self.api_url = f"{self.base_url}/api/v1"
  52. self._client: httpx.AsyncClient | None = None
  53. self._connected = False
  54. async def _get_client(self) -> httpx.AsyncClient:
  55. """Get or create the HTTP client with connection pooling limits.
  56. Configures the client to prevent idle connection issues:
  57. - max_keepalive_connections=5: Limit number of persistent connections
  58. - keepalive_expiry=30: Close idle connections after 30 seconds
  59. - max_connections=10: Limit total connections to prevent resource exhaustion
  60. """
  61. if self._client is None:
  62. self._client = httpx.AsyncClient(
  63. timeout=10.0,
  64. limits=httpx.Limits(
  65. max_keepalive_connections=5,
  66. max_connections=10,
  67. keepalive_expiry=30.0,
  68. ),
  69. )
  70. return self._client
  71. async def close(self):
  72. """Close the HTTP client."""
  73. if self._client:
  74. await self._client.aclose()
  75. self._client = None
  76. async def health_check(self) -> bool:
  77. """Check if Spoolman server is reachable.
  78. Returns:
  79. True if server is healthy, False otherwise.
  80. """
  81. try:
  82. client = await self._get_client()
  83. response = await client.get(f"{self.api_url}/health")
  84. self._connected = response.status_code == 200
  85. return self._connected
  86. except Exception as e:
  87. logger.warning("Spoolman health check failed: %s", e)
  88. self._connected = False
  89. return False
  90. @property
  91. def is_connected(self) -> bool:
  92. """Check if client is connected to Spoolman."""
  93. return self._connected
  94. async def get_spools(self) -> list[dict]:
  95. """Get all spools from Spoolman with retry logic.
  96. Attempts to fetch spools up to 3 times with 500ms delay between attempts.
  97. This handles transient network errors like closed connections.
  98. Returns:
  99. List of spool dictionaries.
  100. Raises:
  101. Exception: If all 3 retry attempts fail.
  102. """
  103. max_attempts = 3
  104. retry_delay = 0.5 # 500ms
  105. for attempt in range(1, max_attempts + 1):
  106. try:
  107. client = await self._get_client()
  108. response = await client.get(f"{self.api_url}/spool")
  109. response.raise_for_status()
  110. spools = response.json()
  111. if attempt > 1:
  112. logger.info("Successfully fetched %d spools on attempt %d", len(spools), attempt)
  113. return spools
  114. except (httpx.ReadError, httpx.RemoteProtocolError, httpx.ConnectError) as e:
  115. # Connection-related errors - close and recreate client for next attempt
  116. if attempt < max_attempts:
  117. logger.warning(
  118. "Connection error getting spools (attempt %d/%d): %s. Recreating client and retrying in %dms...",
  119. attempt,
  120. max_attempts,
  121. e,
  122. int(retry_delay * 1000),
  123. )
  124. # Close the stale client and recreate it
  125. await self.close()
  126. await asyncio.sleep(retry_delay)
  127. else:
  128. logger.error("Failed to get spools from Spoolman after %d attempts: %s", max_attempts, e)
  129. raise
  130. except Exception as e:
  131. # Other errors (HTTP errors, JSON decode errors, etc.)
  132. if attempt < max_attempts:
  133. logger.warning(
  134. "Failed to get spools from Spoolman (attempt %d/%d): %s. Retrying in %dms...",
  135. attempt,
  136. max_attempts,
  137. e,
  138. int(retry_delay * 1000),
  139. )
  140. await asyncio.sleep(retry_delay)
  141. else:
  142. logger.error("Failed to get spools from Spoolman after %d attempts: %s", max_attempts, e)
  143. raise
  144. async def get_filaments(self) -> list[dict]:
  145. """Get all internal filaments from Spoolman.
  146. Returns:
  147. List of filament dictionaries.
  148. """
  149. try:
  150. client = await self._get_client()
  151. response = await client.get(f"{self.api_url}/filament")
  152. response.raise_for_status()
  153. return response.json()
  154. except Exception as e:
  155. logger.error("Failed to get filaments from Spoolman: %s", e)
  156. return []
  157. async def get_external_filaments(self) -> list[dict]:
  158. """Get external/library filaments from Spoolman.
  159. Returns:
  160. List of external filament dictionaries.
  161. """
  162. try:
  163. client = await self._get_client()
  164. response = await client.get(f"{self.api_url}/external/filament")
  165. response.raise_for_status()
  166. return response.json()
  167. except Exception as e:
  168. logger.error("Failed to get external filaments from Spoolman: %s", e)
  169. return []
  170. async def get_vendors(self) -> list[dict]:
  171. """Get all vendors from Spoolman.
  172. Returns:
  173. List of vendor dictionaries.
  174. """
  175. try:
  176. client = await self._get_client()
  177. response = await client.get(f"{self.api_url}/vendor")
  178. response.raise_for_status()
  179. return response.json()
  180. except Exception as e:
  181. logger.error("Failed to get vendors from Spoolman: %s", e)
  182. return []
  183. async def create_vendor(self, name: str) -> dict | None:
  184. """Create a new vendor in Spoolman.
  185. Args:
  186. name: Vendor name (e.g., "Bambu Lab")
  187. Returns:
  188. Created vendor dictionary or None on failure.
  189. """
  190. try:
  191. client = await self._get_client()
  192. response = await client.post(f"{self.api_url}/vendor", json={"name": name})
  193. response.raise_for_status()
  194. return response.json()
  195. except Exception as e:
  196. logger.error("Failed to create vendor in Spoolman: %s", e)
  197. return None
  198. def _get_material_density(self, material: str | None) -> float:
  199. """Get typical density for a filament material type.
  200. Args:
  201. material: Material type (PLA, PETG, ABS, etc.)
  202. Returns:
  203. Density in g/cm³
  204. """
  205. # Typical densities for common filament materials
  206. densities = {
  207. "PLA": 1.24,
  208. "PLA-CF": 1.29,
  209. "PLA-S": 1.24,
  210. "PETG": 1.27,
  211. "ABS": 1.04,
  212. "ASA": 1.07,
  213. "TPU": 1.21,
  214. "PA": 1.14, # Nylon
  215. "PA-CF": 1.20,
  216. "PC": 1.20,
  217. "PVA": 1.23,
  218. "HIPS": 1.04,
  219. "PP": 0.90,
  220. "PET": 1.38,
  221. }
  222. if material:
  223. # Try exact match first, then uppercase
  224. mat_upper = material.upper()
  225. for key, density in densities.items():
  226. if key.upper() == mat_upper or mat_upper.startswith(key.upper()):
  227. return density
  228. return 1.24 # Default to PLA density
  229. async def create_filament(
  230. self,
  231. name: str,
  232. vendor_id: int | None = None,
  233. material: str | None = None,
  234. color_hex: str | None = None,
  235. weight: float | None = None,
  236. diameter: float = 1.75,
  237. density: float | None = None,
  238. ) -> dict | None:
  239. """Create a new filament in Spoolman.
  240. Args:
  241. name: Filament name
  242. vendor_id: Vendor ID
  243. material: Material type (PLA, PETG, etc.)
  244. color_hex: Color in hex format (without #)
  245. weight: Net weight in grams
  246. diameter: Filament diameter in mm (default 1.75)
  247. density: Filament density in g/cm³ (auto-calculated if not provided)
  248. Returns:
  249. Created filament dictionary or None on failure.
  250. """
  251. # Validate required fields
  252. if not name or not name.strip():
  253. logger.error("Cannot create filament: name is required")
  254. return None
  255. try:
  256. # Calculate density from material if not provided
  257. if density is None:
  258. density = self._get_material_density(material)
  259. data = {
  260. "name": name.strip(),
  261. "diameter": diameter,
  262. "density": density,
  263. }
  264. if vendor_id:
  265. data["vendor_id"] = vendor_id
  266. if material:
  267. data["material"] = material
  268. if color_hex:
  269. # Strip alpha channel if present (RRGGBBAA -> RRGGBB)
  270. color_hex = color_hex[:6] if len(color_hex) >= 6 else color_hex
  271. data["color_hex"] = color_hex
  272. if weight:
  273. data["weight"] = weight
  274. logger.debug("Creating filament in Spoolman: %s", data)
  275. client = await self._get_client()
  276. response = await client.post(f"{self.api_url}/filament", json=data)
  277. response.raise_for_status()
  278. return response.json()
  279. except httpx.HTTPStatusError as e:
  280. logger.error("Failed to create filament in Spoolman: %s, response: %s", e, e.response.text)
  281. return None
  282. except Exception as e:
  283. logger.error("Failed to create filament in Spoolman: %s", e)
  284. return None
  285. async def create_spool(
  286. self,
  287. filament_id: int,
  288. remaining_weight: float | None = None,
  289. location: str | None = None,
  290. lot_nr: str | None = None,
  291. comment: str | None = None,
  292. extra: dict | None = None,
  293. ) -> dict | None:
  294. """Create a new spool in Spoolman.
  295. Args:
  296. filament_id: ID of the filament type
  297. remaining_weight: Remaining weight in grams
  298. location: Physical location description
  299. lot_nr: Lot/batch number
  300. comment: Optional comment
  301. extra: Extra fields (e.g., {"tag": "RFID_TAG_UID"})
  302. Returns:
  303. Created spool dictionary or None on failure.
  304. """
  305. try:
  306. data = {"filament_id": filament_id}
  307. if remaining_weight is not None:
  308. data["remaining_weight"] = remaining_weight
  309. if location:
  310. data["location"] = location
  311. if lot_nr:
  312. data["lot_nr"] = lot_nr
  313. if comment:
  314. data["comment"] = comment
  315. if extra:
  316. data["extra"] = extra
  317. logger.debug("Creating spool in Spoolman: %s", data)
  318. client = await self._get_client()
  319. response = await client.post(f"{self.api_url}/spool", json=data)
  320. response.raise_for_status()
  321. result = response.json()
  322. logger.info("Created spool %s in Spoolman", result.get("id"))
  323. return result
  324. except httpx.HTTPStatusError as e:
  325. logger.error("Failed to create spool in Spoolman: %s, response: %s", e, e.response.text)
  326. return None
  327. except Exception as e:
  328. logger.error("Failed to create spool in Spoolman: %s", e)
  329. return None
  330. async def update_spool(
  331. self,
  332. spool_id: int,
  333. remaining_weight: float | None = None,
  334. location: str | None = None,
  335. clear_location: bool = False,
  336. extra: dict | None = None,
  337. ) -> dict | None:
  338. """Update an existing spool in Spoolman.
  339. Args:
  340. spool_id: ID of the spool to update
  341. remaining_weight: New remaining weight in grams
  342. location: New location (ignored if clear_location is True)
  343. clear_location: If True, clears the location field
  344. extra: Extra fields to update
  345. Returns:
  346. Updated spool dictionary or None on failure.
  347. """
  348. try:
  349. data = {}
  350. if remaining_weight is not None:
  351. data["remaining_weight"] = remaining_weight
  352. if clear_location:
  353. data["location"] = None
  354. elif location:
  355. data["location"] = location
  356. if extra:
  357. data["extra"] = extra
  358. # Always update last_used
  359. data["last_used"] = datetime.now(timezone.utc).isoformat()
  360. client = await self._get_client()
  361. response = await client.patch(f"{self.api_url}/spool/{spool_id}", json=data)
  362. response.raise_for_status()
  363. return response.json()
  364. except Exception as e:
  365. logger.error("Failed to update spool in Spoolman: %s", e)
  366. return None
  367. async def use_spool(self, spool_id: int, used_weight: float) -> dict | None:
  368. """Record filament usage for a spool.
  369. Args:
  370. spool_id: ID of the spool
  371. used_weight: Amount of filament used in grams
  372. Returns:
  373. Updated spool dictionary or None on failure.
  374. """
  375. try:
  376. client = await self._get_client()
  377. response = await client.put(
  378. f"{self.api_url}/spool/{spool_id}/use",
  379. json={"use_weight": used_weight},
  380. )
  381. response.raise_for_status()
  382. return response.json()
  383. except Exception as e:
  384. logger.error("Failed to record spool usage in Spoolman: %s", e)
  385. return None
  386. async def find_spool_by_tag(self, tag_uid: str, cached_spools: list[dict] | None = None) -> dict | None:
  387. """Find a spool by its RFID tag UID.
  388. Args:
  389. tag_uid: The RFID tag UID to search for
  390. cached_spools: Optional pre-fetched list of spools to search (avoids API call)
  391. Returns:
  392. Spool dictionary or None if not found.
  393. """
  394. # Use cached spools if provided, otherwise fetch from API
  395. spools = cached_spools if cached_spools is not None else await self.get_spools()
  396. # Normalize tag_uid for comparison (uppercase, strip quotes)
  397. search_tag = tag_uid.strip('"').upper()
  398. for spool in spools:
  399. extra = spool.get("extra", {})
  400. if extra:
  401. stored_tag = extra.get("tag", "")
  402. # Normalize stored tag (strip quotes, uppercase)
  403. if stored_tag:
  404. normalized_tag = stored_tag.strip('"').upper()
  405. if normalized_tag == search_tag:
  406. logger.debug("Found spool %s matching tag %s", spool["id"], tag_uid)
  407. return spool
  408. return None
  409. def _find_spool_by_location(self, location: str, cached_spools: list[dict] | None) -> dict | None:
  410. """Find a spool by exact location match.
  411. Used as fallback when RFID tag data is unavailable (e.g., newer firmware
  412. that doesn't expose tray_uuid/tag_uid via MQTT).
  413. Args:
  414. location: Exact location string (e.g., "H2D-1 - AMS A1")
  415. cached_spools: Pre-fetched list of spools to search
  416. Returns:
  417. Spool dictionary or None if not found.
  418. """
  419. if not cached_spools:
  420. return None
  421. for spool in cached_spools:
  422. if spool.get("location") == location:
  423. return spool
  424. return None
  425. async def find_spools_by_location_prefix(
  426. self, location_prefix: str, cached_spools: list[dict] | None = None
  427. ) -> list[dict]:
  428. """Find all spools with locations starting with a given prefix.
  429. Args:
  430. location_prefix: The location prefix to search for (e.g., "PrinterName - ")
  431. cached_spools: Optional pre-fetched list of spools to search (avoids API call)
  432. Returns:
  433. List of spool dictionaries with matching locations.
  434. """
  435. # Use cached spools if provided, otherwise fetch from API
  436. spools = cached_spools if cached_spools is not None else await self.get_spools()
  437. matching = []
  438. for spool in spools:
  439. location = spool.get("location", "")
  440. if location and location.startswith(location_prefix):
  441. matching.append(spool)
  442. return matching
  443. async def clear_location_for_removed_spools(
  444. self,
  445. printer_name: str,
  446. current_tray_uuids: set[str],
  447. cached_spools: list[dict] | None = None,
  448. synced_spool_ids: set[int] | None = None,
  449. ) -> int:
  450. """Clear location for spools that are no longer in the AMS.
  451. When a spool is removed from the AMS, its location should be cleared
  452. in Spoolman. This method finds all spools with locations for this printer
  453. and clears the location for any that are not in the current_tray_uuids set
  454. and were not synced in this cycle (synced_spool_ids).
  455. Args:
  456. printer_name: The printer name used as location prefix
  457. current_tray_uuids: Set of tray_uuids currently in the AMS
  458. cached_spools: Optional pre-fetched list of spools to search (avoids API call)
  459. synced_spool_ids: Set of spool IDs that were synced in this cycle
  460. (protects location-matched spools when RFID data is unavailable)
  461. Returns:
  462. Number of spools whose location was cleared.
  463. """
  464. location_prefix = f"{printer_name} - "
  465. spools_at_printer = await self.find_spools_by_location_prefix(location_prefix, cached_spools=cached_spools)
  466. cleared_count = 0
  467. for spool in spools_at_printer:
  468. spool_id = spool.get("id")
  469. # Skip spools that were just synced (matched by location or tag)
  470. if synced_spool_ids and spool_id in synced_spool_ids:
  471. continue
  472. # Get the tray_uuid (stored as "tag" in extra field)
  473. extra = spool.get("extra", {}) or {}
  474. stored_tag = extra.get("tag", "")
  475. if stored_tag:
  476. # Normalize: strip quotes and uppercase
  477. spool_uuid = stored_tag.strip('"').upper()
  478. else:
  479. spool_uuid = ""
  480. # If this spool's UUID is not in the current AMS, clear its location
  481. if spool_uuid not in current_tray_uuids:
  482. logger.info(
  483. f"Clearing location for spool {spool_id} "
  484. f"(was: {spool.get('location')}, uuid: {spool_uuid[:16] if spool_uuid else 'none'}...)"
  485. )
  486. result = await self.update_spool(spool_id=spool_id, clear_location=True)
  487. if result:
  488. cleared_count += 1
  489. return cleared_count
  490. async def ensure_bambu_vendor(self) -> int | None:
  491. """Ensure Bambu Lab vendor exists and return its ID.
  492. Returns:
  493. Vendor ID or None on failure.
  494. """
  495. vendors = await self.get_vendors()
  496. for vendor in vendors:
  497. if vendor.get("name", "").lower() == "bambu lab":
  498. return vendor["id"]
  499. # Create Bambu Lab vendor if not exists
  500. vendor = await self.create_vendor("Bambu Lab")
  501. return vendor["id"] if vendor else None
  502. async def ensure_tag_extra_field(self) -> bool:
  503. """Ensure the 'tag' extra field exists for spools.
  504. Spoolman requires extra fields to be registered before use.
  505. This creates the 'tag' field used to store RFID/UUID identifiers.
  506. Returns:
  507. True if field exists or was created, False on failure.
  508. """
  509. try:
  510. client = await self._get_client()
  511. # Check if field already exists
  512. response = await client.get(f"{self.api_url}/field/spool/tag")
  513. if response.status_code == 200:
  514. logger.debug("Spoolman 'tag' extra field already exists")
  515. return True
  516. # Field doesn't exist - create it
  517. field_data = {
  518. "name": "tag",
  519. "field_type": "text",
  520. "default_value": None,
  521. }
  522. response = await client.post(f"{self.api_url}/field/spool/tag", json=field_data)
  523. if response.status_code in (200, 201):
  524. logger.info("Created 'tag' extra field in Spoolman")
  525. return True
  526. logger.warning("Failed to create 'tag' extra field: %s - %s", response.status_code, response.text)
  527. return False
  528. except Exception as e:
  529. logger.warning("Failed to ensure 'tag' extra field exists: %s", e)
  530. return False
  531. def parse_ams_tray(self, ams_id: int, tray_data: dict) -> AMSTray | None:
  532. """Parse AMS tray data into AMSTray object.
  533. Args:
  534. ams_id: The AMS unit ID (0-3 for regular, 128-135 for external)
  535. tray_data: Raw tray data from MQTT
  536. Returns:
  537. AMSTray object or None if tray is empty or invalid.
  538. """
  539. # Skip empty trays - check for valid tray_type
  540. tray_type = tray_data.get("tray_type", "")
  541. if not tray_type or tray_type.strip() == "":
  542. return None
  543. # Need valid color to create filament
  544. tray_color = tray_data.get("tray_color", "")
  545. if not tray_color or tray_color.strip() == "":
  546. logger.debug("Skipping tray with empty color")
  547. return None
  548. # Handle transparent/natural filament (RRGGBBAA with alpha=00)
  549. # Replace with cream color that represents how natural PLA actually looks
  550. if tray_color == "00000000":
  551. tray_color = "F5E6D3FF" # Light cream/natural color
  552. # Get sub_brands, falling back to tray_type
  553. tray_sub_brands = tray_data.get("tray_sub_brands", "")
  554. if not tray_sub_brands or tray_sub_brands.strip() == "":
  555. tray_sub_brands = tray_type
  556. # Get tag_uid and tray_uuid, filtering out empty/invalid values
  557. tag_uid = tray_data.get("tag_uid", "")
  558. if tag_uid in ("", "0000000000000000"):
  559. tag_uid = ""
  560. tray_uuid = tray_data.get("tray_uuid", "")
  561. if tray_uuid in ("", "00000000000000000000000000000000"):
  562. tray_uuid = ""
  563. # Get tray_info_idx (Bambu filament preset ID like "GFA00")
  564. tray_info_idx = tray_data.get("tray_info_idx", "") or ""
  565. # Get remaining percentage, ensure non-negative
  566. remain = max(0, int(tray_data.get("remain", 0)))
  567. return AMSTray(
  568. ams_id=ams_id,
  569. tray_id=int(tray_data.get("id", 0)),
  570. tray_type=tray_type.strip(),
  571. tray_sub_brands=tray_sub_brands.strip(),
  572. tray_color=tray_color,
  573. remain=remain,
  574. tag_uid=tag_uid,
  575. tray_uuid=tray_uuid,
  576. tray_info_idx=tray_info_idx.strip(),
  577. tray_weight=int(tray_data.get("tray_weight", 1000)),
  578. )
  579. def convert_ams_slot_to_location(self, ams_id: int, tray_id: int) -> str:
  580. """Convert AMS ID and tray ID to human-readable location.
  581. Args:
  582. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for external)
  583. tray_id: Tray ID within the AMS (0-3)
  584. Returns:
  585. Location string like "AMS A1", "AMS B2", "External"
  586. """
  587. if ams_id >= 128:
  588. return "External Spool"
  589. ams_letter = chr(ord("A") + ams_id)
  590. return f"AMS {ams_letter}{tray_id + 1}"
  591. def is_bambu_lab_spool(self, tray_uuid: str, tag_uid: str = "", tray_info_idx: str = "") -> bool:
  592. """Check if a tray has a valid Bambu Lab spool.
  593. Bambu Lab spools can be identified by:
  594. 1. tray_uuid: 32-character hex string (preferred, consistent across printers)
  595. 2. tag_uid: 16-character hex string (RFID tag, varies between readers)
  596. 3. tray_info_idx: Bambu filament preset ID like "GFA00" (most reliable)
  597. Non-Bambu Lab spools (SpoolEase, third-party) won't have these identifiers.
  598. Args:
  599. tray_uuid: The tray UUID to check (32 hex chars)
  600. tag_uid: The RFID tag UID to check as fallback (16 hex chars)
  601. tray_info_idx: Bambu filament preset ID like "GFA00", "GFB00"
  602. Returns:
  603. True if the spool has valid Bambu Lab identifiers, False otherwise.
  604. """
  605. # Check tray_info_idx first - Bambu filament preset IDs like "GFA00", "GFB00", etc.
  606. # This is the most reliable indicator as it's set when the spool is recognized
  607. if tray_info_idx:
  608. idx = tray_info_idx.strip()
  609. # Bambu Lab preset IDs start with "GF" followed by letter and digits
  610. # e.g., GFA00, GFB00, GFL00, GFN00, GFG00, GFS00, GFU00
  611. if idx and len(idx) >= 3 and idx.startswith("GF"):
  612. logger.debug("Identified Bambu Lab spool via tray_info_idx: %s", idx)
  613. return True
  614. # Check tray_uuid (preferred - consistent across printer models)
  615. if tray_uuid:
  616. uuid = tray_uuid.strip()
  617. if len(uuid) == 32 and uuid != "00000000000000000000000000000000":
  618. try:
  619. int(uuid, 16)
  620. return True
  621. except ValueError:
  622. pass
  623. # Fallback: check tag_uid (RFID tag - varies between printer readers)
  624. # Bambu Lab RFID tags are 16 hex characters (8 bytes)
  625. if tag_uid:
  626. tag = tag_uid.strip()
  627. if len(tag) == 16 and tag != "0000000000000000":
  628. try:
  629. int(tag, 16)
  630. logger.debug("Identified Bambu Lab spool via tag_uid fallback: %s", tag)
  631. return True
  632. except ValueError:
  633. pass
  634. return False
  635. def calculate_remaining_weight(self, remain_percent: int, spool_weight: int) -> float:
  636. """Calculate remaining weight from percentage.
  637. Args:
  638. remain_percent: Remaining percentage (0-100)
  639. spool_weight: Total spool weight in grams
  640. Returns:
  641. Remaining weight in grams.
  642. """
  643. return (remain_percent / 100.0) * spool_weight
  644. async def sync_ams_tray(
  645. self,
  646. tray: AMSTray,
  647. printer_name: str,
  648. disable_weight_sync: bool = False,
  649. cached_spools: list[dict] | None = None,
  650. ) -> dict | None:
  651. """Sync a single AMS tray to Spoolman.
  652. Only syncs trays with valid Bambu Lab tray_uuid (32 hex characters).
  653. Non-Bambu Lab spools (SpoolEase/third-party) are skipped.
  654. Uses tray_uuid for matching, as it's consistent across all printer models
  655. (unlike tag_uid which varies between X1C/H2D readers).
  656. Args:
  657. tray: The AMSTray to sync
  658. printer_name: Name of the printer for location
  659. disable_weight_sync: If True, skip updating remaining_weight for existing spools.
  660. This allows Spoolman's granular usage tracking to maintain accurate weights.
  661. cached_spools: Optional pre-fetched list of spools to search (avoids API calls).
  662. When provided, this cache is passed to find_spool_by_tag to avoid redundant
  663. API calls during batch sync operations.
  664. Returns:
  665. Synced spool dictionary or None if skipped or failed.
  666. """
  667. logger.debug(
  668. f"Processing {printer_name} AMS {tray.ams_id} tray {tray.tray_id}: "
  669. f"type={tray.tray_type}, idx={tray.tray_info_idx or 'none'}, "
  670. f"uuid={tray.tray_uuid[:16] if tray.tray_uuid else 'none'}, "
  671. f"tag={tray.tag_uid[:8] if tray.tag_uid else 'none'}..."
  672. )
  673. # Only sync trays with valid Bambu Lab identifiers
  674. if not self.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  675. if tray.tray_uuid or tray.tag_uid or tray.tray_info_idx:
  676. logger.info(
  677. f"Skipping non-Bambu Lab spool: {printer_name} AMS {tray.ams_id} tray {tray.tray_id} "
  678. f"(tray_info_idx={tray.tray_info_idx}, tray_uuid={tray.tray_uuid}, tag_uid={tray.tag_uid})"
  679. )
  680. else:
  681. logger.debug("Skipping tray without RFID tag: AMS %s tray %s", tray.ams_id, tray.tray_id)
  682. return None
  683. # Determine which identifier to use for Spoolman (prefer tray_uuid, fallback to tag_uid)
  684. spool_tag = (
  685. tray.tray_uuid if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000" else tray.tag_uid
  686. )
  687. # Calculate remaining weight (skip if data is invalid/unavailable)
  688. # Some firmware sends remain=-1 (→0 after max) and tray_weight=0, making weight unreliable
  689. remaining = (
  690. self.calculate_remaining_weight(tray.remain, tray.tray_weight)
  691. if tray.remain > 0 and tray.tray_weight > 0
  692. else None
  693. )
  694. location = f"{printer_name} - {self.convert_ams_slot_to_location(tray.ams_id, tray.tray_id)}"
  695. if spool_tag:
  696. # Primary path: match by RFID tag
  697. existing = await self.find_spool_by_tag(spool_tag, cached_spools=cached_spools)
  698. if existing:
  699. logger.info("Updating existing spool %s for tag %s...", existing["id"], spool_tag[:16])
  700. return await self.update_spool(
  701. spool_id=existing["id"],
  702. remaining_weight=None if disable_weight_sync else remaining,
  703. location=location,
  704. )
  705. # Spool not found by tag - auto-create it
  706. logger.info("Creating new spool in Spoolman for %s (tag: %s...)", tray.tray_sub_brands, spool_tag[:16])
  707. filament = await self._find_or_create_filament(tray)
  708. if not filament:
  709. logger.error("Failed to find or create filament for %s", tray.tray_sub_brands)
  710. return None
  711. import json
  712. return await self.create_spool(
  713. filament_id=filament["id"],
  714. remaining_weight=remaining,
  715. location=location,
  716. comment="Created by Bambuddy",
  717. extra={"tag": json.dumps(spool_tag)},
  718. )
  719. # Fallback path: no RFID tag available (newer firmware may not expose UUIDs)
  720. # Match existing Spoolman spools by their location (AMS slot position)
  721. existing = self._find_spool_by_location(location, cached_spools)
  722. if existing:
  723. logger.info(
  724. "Updating spool %s by location match '%s' (no RFID tag available)",
  725. existing["id"],
  726. location,
  727. )
  728. return await self.update_spool(
  729. spool_id=existing["id"],
  730. remaining_weight=None if disable_weight_sync else remaining,
  731. location=location,
  732. )
  733. # No existing spool at this location — create a new one without a tag
  734. logger.info(
  735. "Creating new spool in Spoolman for %s at %s (no RFID tag available)",
  736. tray.tray_sub_brands,
  737. location,
  738. )
  739. filament = await self._find_or_create_filament(tray)
  740. if not filament:
  741. logger.error("Failed to find or create filament for %s", tray.tray_sub_brands)
  742. return None
  743. return await self.create_spool(
  744. filament_id=filament["id"],
  745. remaining_weight=remaining,
  746. location=location,
  747. comment="Created by Bambuddy",
  748. )
  749. async def _find_or_create_filament(self, tray: AMSTray) -> dict | None:
  750. """Find existing filament or create new one.
  751. Only matches Bambu Lab vendor filaments since this is called for
  752. Bambu Lab spools. Third-party filaments (like 3DJAKE) are ignored
  753. to prevent incorrect matching by color alone.
  754. Args:
  755. tray: The AMSTray containing filament info
  756. Returns:
  757. Filament dictionary or None on failure.
  758. """
  759. # Get Bambu Lab vendor ID for filtering
  760. bambu_vendor_id = await self.ensure_bambu_vendor()
  761. color_hex = tray.tray_color[:6] # Strip alpha channel
  762. # Search internal filaments - only match Bambu Lab vendor
  763. filaments = await self.get_filaments()
  764. for filament in filaments:
  765. # Only match filaments from Bambu Lab vendor
  766. fil_vendor_id = filament.get("vendor_id") or filament.get("vendor", {}).get("id")
  767. if fil_vendor_id != bambu_vendor_id:
  768. continue
  769. # Match by material and color (handle None values)
  770. fil_material = filament.get("material") or ""
  771. fil_color = filament.get("color_hex") or ""
  772. if fil_material.upper() == tray.tray_type.upper() and fil_color.upper() == color_hex.upper():
  773. return filament
  774. # Search external filaments (Bambu library)
  775. external = await self.get_external_filaments()
  776. for filament in external:
  777. fil_material = filament.get("material") or ""
  778. fil_color = filament.get("color_hex") or ""
  779. if fil_material.upper() == tray.tray_type.upper() and fil_color.upper() == color_hex.upper():
  780. # Found in external library - need to create internal copy
  781. return await self._create_filament_from_external(filament, tray)
  782. # Not found - create new Bambu Lab filament
  783. return await self.create_filament(
  784. name=tray.tray_sub_brands or tray.tray_type,
  785. vendor_id=bambu_vendor_id,
  786. material=tray.tray_type,
  787. color_hex=color_hex,
  788. weight=tray.tray_weight,
  789. )
  790. async def _create_filament_from_external(self, external: dict, tray: AMSTray) -> dict | None:
  791. """Create internal filament from external library entry.
  792. Args:
  793. external: External filament dictionary
  794. tray: The AMSTray for additional info
  795. Returns:
  796. Created filament dictionary or None on failure.
  797. """
  798. vendor_id = await self.ensure_bambu_vendor()
  799. return await self.create_filament(
  800. name=external.get("name", tray.tray_sub_brands),
  801. vendor_id=vendor_id,
  802. material=external.get("material", tray.tray_type),
  803. color_hex=external.get("color_hex", tray.tray_color[:6]),
  804. weight=external.get("weight", tray.tray_weight),
  805. )
  806. # Global client instance (initialized when settings are loaded)
  807. _spoolman_client: SpoolmanClient | None = None
  808. async def get_spoolman_client() -> SpoolmanClient | None:
  809. """Get the global Spoolman client instance.
  810. Returns:
  811. SpoolmanClient instance or None if not configured.
  812. """
  813. return _spoolman_client
  814. async def init_spoolman_client(url: str) -> SpoolmanClient:
  815. """Initialize the global Spoolman client.
  816. Args:
  817. url: Spoolman server URL
  818. Returns:
  819. Initialized SpoolmanClient instance.
  820. """
  821. global _spoolman_client
  822. if _spoolman_client:
  823. await _spoolman_client.close()
  824. _spoolman_client = SpoolmanClient(url)
  825. return _spoolman_client
  826. async def close_spoolman_client():
  827. """Close the global Spoolman client."""
  828. global _spoolman_client
  829. if _spoolman_client:
  830. await _spoolman_client.close()
  831. _spoolman_client = None