spoolman.py 37 KB

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