spoolman.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. """Spoolman integration service for syncing AMS filament data."""
  2. import asyncio
  3. import logging
  4. import weakref
  5. from dataclasses import dataclass
  6. from datetime import datetime, timezone
  7. from typing import Literal
  8. import httpx
  9. from backend.app.utils.color_utils import color_match_key, spoolman_color_hex
  10. logger = logging.getLogger(__name__)
  11. BAMBU_RFID_TAG_LENGTH = 32
  12. @dataclass
  13. class SpoolmanSpool:
  14. """Represents a spool in Spoolman."""
  15. id: int
  16. filament_id: int | None
  17. remaining_weight: float | None
  18. used_weight: float
  19. first_used: str | None
  20. last_used: str | None
  21. location: str | None
  22. lot_nr: str | None
  23. comment: str | None
  24. extra: dict | None # Contains tag_uid in extra.tag
  25. @dataclass
  26. class SpoolmanFilament:
  27. """Represents a filament type in Spoolman."""
  28. id: int
  29. name: str
  30. vendor_id: int | None
  31. material: str | None
  32. color_hex: str | None
  33. weight: float | None # Net weight in grams
  34. @dataclass
  35. class AMSTray:
  36. """Represents an AMS tray with filament data from Bambu printer."""
  37. ams_id: int # 0-3 for regular AMS, 128-135 for AMS-HT, 254+ for external spool
  38. tray_id: int # 0-3
  39. tray_type: str # PLA, PETG, ABS, etc.
  40. tray_sub_brands: str # Full name like "PLA Basic", "PETG HF"
  41. tray_color: str # Hex color like "FEC600FF"
  42. remain: int # Remaining percentage (0-100)
  43. tag_uid: str # RFID tag UID
  44. tray_uuid: str # Spool UUID
  45. tray_info_idx: str # Bambu filament preset ID like "GFA00"
  46. tray_weight: int # Spool weight in grams (usually 1000)
  47. class SpoolmanNotFoundError(Exception):
  48. """Raised when a spool ID does not exist in Spoolman (HTTP 404)."""
  49. class SpoolmanUnavailableError(Exception):
  50. """Raised when Spoolman is unreachable or returns a server/network error."""
  51. class SpoolmanClientError(Exception):
  52. """Raised when Spoolman returns a 4xx client error (not 404)."""
  53. def __init__(self, message: str, status_code: int, response_text: str = "") -> None:
  54. super().__init__(message)
  55. self.status_code = status_code
  56. self.response_text = response_text
  57. def _filament_subtype_part(name: str, material: str) -> str:
  58. """Return the subtype portion of a filament name, lowercased.
  59. Mirrors the read-side derivation in
  60. ``backend/app/api/routes/_spoolman_helpers.py::_map_spoolman_spool``:
  61. if the filament name starts with the material prefix (e.g. ``"PLA Glow"``
  62. when material is ``"PLA"``), strip it; otherwise return the name as-is.
  63. Used by ``find_or_create_filament`` so that an existing filament saved by
  64. the AMS-sync path with name ``"Glow"`` still matches a user-driven edit
  65. that composes ``"PLA Glow"`` (#1357).
  66. """
  67. s = (name or "").strip()
  68. m = (material or "").strip()
  69. if m and s.upper().startswith(m.upper() + " "):
  70. return s[len(m) + 1 :].strip().lower()
  71. return s.lower()
  72. class SpoolmanClient:
  73. """Client for interacting with Spoolman API."""
  74. def __init__(self, base_url: str):
  75. """Initialize the Spoolman client."""
  76. self.base_url = base_url.rstrip("/")
  77. self.api_url = f"{self.base_url}/api/v1"
  78. self._client: httpx.AsyncClient | None = None
  79. self._connected = False
  80. # Per-spool locks for atomic read-modify-write in merge_spool_extra.
  81. # WeakValueDictionary: locks are GC'd once no coroutine holds a reference.
  82. self._extra_locks: weakref.WeakValueDictionary[int, asyncio.Lock] = weakref.WeakValueDictionary()
  83. # Extra-field names this client has already registered with Spoolman.
  84. # Bounded by the number of distinct keys Bambuddy writes, so it never
  85. # grows with spool count; scoped to the instance so a client pointed at
  86. # a different Spoolman starts over.
  87. self._ensured_extra_fields: set[str] = set()
  88. self._ensure_extra_lock = asyncio.Lock()
  89. async def _get_client(self) -> httpx.AsyncClient:
  90. """Get or create the HTTP client with connection pooling limits."""
  91. if self._client is None:
  92. self._client = httpx.AsyncClient(
  93. timeout=httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=5.0),
  94. follow_redirects=False,
  95. verify=True,
  96. limits=httpx.Limits(
  97. max_keepalive_connections=5,
  98. max_connections=10,
  99. keepalive_expiry=30.0,
  100. ),
  101. )
  102. return self._client
  103. async def close(self):
  104. """Close the HTTP client."""
  105. if self._client:
  106. await self._client.aclose()
  107. self._client = None
  108. async def health_check(self) -> bool:
  109. """Check if Spoolman server is reachable; returns True if healthy."""
  110. try:
  111. client = await self._get_client()
  112. response = await client.get(f"{self.api_url}/health")
  113. self._connected = response.status_code == 200
  114. return self._connected
  115. except Exception as e:
  116. logger.warning(
  117. "Spoolman health check failed (url=%s, type=%s): %s",
  118. self.api_url,
  119. type(e).__name__,
  120. e,
  121. )
  122. self._connected = False
  123. return False
  124. @property
  125. def is_connected(self) -> bool:
  126. """Check if client is connected to Spoolman."""
  127. return self._connected
  128. async def get_spools(self) -> list[dict]:
  129. """Fetch all spools from Spoolman with up to 3 retries on connection errors."""
  130. max_attempts = 3
  131. retry_delay = 0.5 # 500ms
  132. for attempt in range(1, max_attempts + 1):
  133. try:
  134. client = await self._get_client()
  135. response = await client.get(f"{self.api_url}/spool")
  136. response.raise_for_status()
  137. spools = response.json()
  138. if attempt > 1:
  139. logger.info("Successfully fetched %d spools on attempt %d", len(spools), attempt)
  140. return spools
  141. except (httpx.ReadError, httpx.RemoteProtocolError, httpx.ConnectError) as e:
  142. # Connection-related errors - close and recreate client for next attempt
  143. if attempt < max_attempts:
  144. logger.warning(
  145. "Connection error getting spools (attempt %d/%d): %s. Recreating client and retrying in %dms...",
  146. attempt,
  147. max_attempts,
  148. e,
  149. int(retry_delay * 1000),
  150. )
  151. # Close the stale client and recreate it
  152. await self.close()
  153. await asyncio.sleep(retry_delay)
  154. else:
  155. logger.error("Failed to get spools from Spoolman after %d attempts: %s", max_attempts, e)
  156. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  157. except Exception as e:
  158. # Other errors (HTTP errors, JSON decode errors, etc.)
  159. if attempt < max_attempts:
  160. logger.warning(
  161. "Failed to get spools from Spoolman (attempt %d/%d): %s. Retrying in %dms...",
  162. attempt,
  163. max_attempts,
  164. e,
  165. int(retry_delay * 1000),
  166. )
  167. await asyncio.sleep(retry_delay)
  168. else:
  169. logger.error("Failed to get spools from Spoolman after %d attempts: %s", max_attempts, e)
  170. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  171. async def _get_with_retry(self, path: str, params: dict | None = None) -> list[dict]:
  172. """GET a Spoolman JSON list endpoint with up to 3 retries on connection errors."""
  173. max_attempts = 3
  174. retry_delay = 0.5
  175. url = f"{self.api_url}/{path.lstrip('/')}"
  176. for attempt in range(1, max_attempts + 1):
  177. try:
  178. client = await self._get_client()
  179. response = await client.get(url, params=params or None)
  180. response.raise_for_status()
  181. return response.json()
  182. except (httpx.ReadError, httpx.RemoteProtocolError, httpx.ConnectError) as e:
  183. if attempt < max_attempts:
  184. logger.warning(
  185. "Connection error fetching %s (attempt %d/%d): %s. Recreating client and retrying in %dms...",
  186. path,
  187. attempt,
  188. max_attempts,
  189. e,
  190. int(retry_delay * 1000),
  191. )
  192. await self.close()
  193. await asyncio.sleep(retry_delay)
  194. else:
  195. logger.error("Failed to fetch %s from Spoolman after %d attempts: %s", path, max_attempts, e)
  196. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  197. except Exception as e:
  198. if attempt < max_attempts:
  199. logger.warning(
  200. "Failed to fetch %s from Spoolman (attempt %d/%d): %s. Retrying in %dms...",
  201. path,
  202. attempt,
  203. max_attempts,
  204. e,
  205. int(retry_delay * 1000),
  206. )
  207. await asyncio.sleep(retry_delay)
  208. else:
  209. logger.error("Failed to fetch %s from Spoolman after %d attempts: %s", path, max_attempts, e)
  210. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  211. async def get_filaments(self) -> list[dict]:
  212. """Fetch all internal filaments from Spoolman."""
  213. try:
  214. client = await self._get_client()
  215. response = await client.get(f"{self.api_url}/filament")
  216. response.raise_for_status()
  217. return response.json()
  218. except Exception as e:
  219. logger.error("Failed to get filaments from Spoolman: %s", e)
  220. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  221. async def get_filament(self, filament_id: int) -> dict:
  222. """Fetch a single filament by ID from Spoolman."""
  223. if filament_id <= 0:
  224. raise ValueError(f"Invalid filament_id: {filament_id}")
  225. response = await self._request_filament("GET", filament_id, operation="get_filament")
  226. return response.json()
  227. async def get_external_filaments(self) -> list[dict]:
  228. """Fetch external/library filaments from Spoolman."""
  229. try:
  230. client = await self._get_client()
  231. response = await client.get(f"{self.api_url}/external/filament")
  232. response.raise_for_status()
  233. return response.json()
  234. except Exception as e:
  235. logger.error("Failed to get external filaments from Spoolman: %s", e)
  236. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  237. async def get_vendors(self) -> list[dict]:
  238. """Fetch all vendors from Spoolman."""
  239. try:
  240. client = await self._get_client()
  241. response = await client.get(f"{self.api_url}/vendor")
  242. response.raise_for_status()
  243. return response.json()
  244. except Exception as e:
  245. logger.error("Failed to get vendors from Spoolman: %s", e)
  246. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  247. async def create_vendor(self, name: str) -> dict:
  248. """Create a new vendor in Spoolman."""
  249. try:
  250. client = await self._get_client()
  251. response = await client.post(f"{self.api_url}/vendor", json={"name": name})
  252. if 400 <= response.status_code < 500:
  253. raise SpoolmanClientError(
  254. f"Spoolman rejected vendor creation (HTTP {response.status_code})",
  255. response.status_code,
  256. )
  257. response.raise_for_status()
  258. return response.json()
  259. except SpoolmanClientError:
  260. raise
  261. except Exception as e:
  262. logger.error("Failed to create vendor in Spoolman: %s", e)
  263. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  264. def _get_material_density(self, material: str | None) -> float:
  265. """Return typical density (g/cm³) for the given filament material; defaults to PLA (1.24)."""
  266. # Typical densities for common filament materials
  267. densities = {
  268. "PLA": 1.24,
  269. "PLA-CF": 1.29,
  270. "PLA-S": 1.24,
  271. "PETG": 1.27,
  272. "ABS": 1.04,
  273. "ASA": 1.07,
  274. "TPU": 1.21,
  275. "PA": 1.14, # Nylon
  276. "PA-CF": 1.20,
  277. "PC": 1.20,
  278. "PVA": 1.23,
  279. "HIPS": 1.04,
  280. "PP": 0.90,
  281. "PET": 1.38,
  282. }
  283. if material:
  284. # Try exact match first, then uppercase
  285. mat_upper = material.upper()
  286. for key, density in densities.items():
  287. if key.upper() == mat_upper or mat_upper.startswith(key.upper()):
  288. return density
  289. return 1.24 # Default to PLA density
  290. async def create_filament(
  291. self,
  292. name: str,
  293. vendor_id: int | None = None,
  294. material: str | None = None,
  295. color_hex: str | None = None,
  296. color_name: str | None = None,
  297. weight: float | None = None,
  298. diameter: float = 1.75,
  299. density: float | None = None,
  300. ) -> dict:
  301. """Create a new filament in Spoolman."""
  302. if not name or not name.strip():
  303. raise ValueError("Filament name is required")
  304. if density is None:
  305. density = self._get_material_density(material)
  306. data: dict = {
  307. "name": name.strip(),
  308. "diameter": diameter,
  309. "density": density,
  310. }
  311. if vendor_id:
  312. data["vendor_id"] = vendor_id
  313. if material:
  314. data["material"] = material
  315. if color_hex:
  316. # Every create funnels through here, so this is where the stored shape
  317. # is decided: six characters for an opaque spool, eight only when the
  318. # alpha byte says the filament is translucent. See #2912.
  319. data["color_hex"] = spoolman_color_hex(color_hex) or color_hex
  320. if color_name:
  321. data["color_name"] = color_name
  322. if weight:
  323. data["weight"] = weight
  324. logger.debug("Creating filament in Spoolman: %s", data)
  325. try:
  326. client = await self._get_client()
  327. response = await client.post(f"{self.api_url}/filament", json=data)
  328. if 400 <= response.status_code < 500:
  329. raise SpoolmanClientError(
  330. f"Spoolman rejected filament creation (HTTP {response.status_code})",
  331. response.status_code,
  332. )
  333. response.raise_for_status()
  334. return response.json()
  335. except SpoolmanClientError:
  336. raise
  337. except Exception as e:
  338. logger.error("Failed to create filament in Spoolman: %s", e)
  339. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  340. async def patch_filament(self, filament_id: int, data: dict) -> dict:
  341. """PATCH a filament entry in Spoolman (e.g. update name or spool_weight)."""
  342. if filament_id <= 0:
  343. raise ValueError(f"Invalid filament_id: {filament_id}")
  344. response = await self._request_filament("PATCH", filament_id, json_body=data, operation="patch_filament")
  345. return response.json()
  346. async def create_spool(
  347. self,
  348. filament_id: int,
  349. remaining_weight: float | None = None,
  350. location: str | None = None,
  351. lot_nr: str | None = None,
  352. comment: str | None = None,
  353. extra: dict | None = None,
  354. ) -> dict:
  355. """Create a new spool in Spoolman."""
  356. data: dict = {"filament_id": filament_id}
  357. if remaining_weight is not None:
  358. data["remaining_weight"] = remaining_weight
  359. if location:
  360. data["location"] = location
  361. if lot_nr:
  362. data["lot_nr"] = lot_nr
  363. if comment:
  364. data["comment"] = comment
  365. if extra:
  366. data["extra"] = extra
  367. await self._ensure_extra_fields(extra)
  368. logger.debug("Creating spool in Spoolman: %s", data)
  369. try:
  370. client = await self._get_client()
  371. response = await client.post(f"{self.api_url}/spool", json=data)
  372. if response.status_code == 404:
  373. raise SpoolmanNotFoundError(f"Filament {filament_id} not found in Spoolman")
  374. if 400 <= response.status_code < 500:
  375. raise SpoolmanClientError(
  376. f"Spoolman rejected spool creation (HTTP {response.status_code})",
  377. response.status_code,
  378. )
  379. response.raise_for_status()
  380. result = response.json()
  381. logger.info("Created spool %s in Spoolman", result.get("id"))
  382. return result
  383. except (SpoolmanNotFoundError, SpoolmanClientError):
  384. raise
  385. except Exception as e:
  386. logger.error("Failed to create spool in Spoolman: %s", e)
  387. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  388. async def update_spool(
  389. self,
  390. spool_id: int,
  391. remaining_weight: float | None = None,
  392. location: str | None = None,
  393. clear_location: bool = False,
  394. extra: dict | None = None,
  395. ) -> dict:
  396. """Update an existing spool in Spoolman, always setting last_used."""
  397. data: dict = {}
  398. if remaining_weight is not None:
  399. data["remaining_weight"] = remaining_weight
  400. if clear_location:
  401. data["location"] = None
  402. elif location:
  403. data["location"] = location
  404. if extra:
  405. data["extra"] = extra
  406. await self._ensure_extra_fields(extra)
  407. data["last_used"] = datetime.now(timezone.utc).isoformat()
  408. response = await self._request_spool("PATCH", spool_id, json_body=data, operation="update")
  409. return response.json()
  410. async def _request_spool(
  411. self,
  412. method: Literal["GET", "PATCH", "DELETE"],
  413. spool_id: int,
  414. *,
  415. json_body: dict | None = None,
  416. operation: str,
  417. ) -> httpx.Response:
  418. """Perform a spool-scoped HTTP request, translating 404 and errors to named exceptions."""
  419. try:
  420. client = await self._get_client()
  421. response = await client.request(
  422. method,
  423. f"{self.api_url}/spool/{spool_id}",
  424. json=json_body,
  425. )
  426. if response.status_code == 404:
  427. raise SpoolmanNotFoundError(f"Spool {spool_id} not found in Spoolman")
  428. response.raise_for_status()
  429. return response
  430. except SpoolmanNotFoundError:
  431. raise
  432. except httpx.HTTPStatusError as e:
  433. if 400 <= e.response.status_code < 500:
  434. logger.warning(
  435. "Spoolman returned %d for %s spool %s",
  436. e.response.status_code,
  437. operation,
  438. spool_id,
  439. )
  440. raise SpoolmanClientError(
  441. f"Spoolman rejected {operation} for spool {spool_id} (HTTP {e.response.status_code})",
  442. e.response.status_code,
  443. e.response.text[:500],
  444. ) from e
  445. else:
  446. logger.error("Failed to %s spool %s in Spoolman: %s", operation, spool_id, e)
  447. raise SpoolmanUnavailableError(f"Failed to {operation} spool {spool_id}") from e
  448. except Exception as e:
  449. logger.error("Failed to %s spool %s in Spoolman: %s", operation, spool_id, e)
  450. raise SpoolmanUnavailableError(f"Failed to {operation} spool {spool_id}") from e
  451. async def _request_filament(
  452. self,
  453. method: Literal["GET", "PATCH"],
  454. filament_id: int,
  455. *,
  456. json_body: dict | None = None,
  457. operation: str,
  458. ) -> httpx.Response:
  459. """Perform a filament-scoped HTTP request, translating 404 and errors to named exceptions."""
  460. try:
  461. client = await self._get_client()
  462. response = await client.request(
  463. method,
  464. f"{self.api_url}/filament/{filament_id}",
  465. json=json_body,
  466. )
  467. if response.status_code == 404:
  468. raise SpoolmanNotFoundError(f"Filament {filament_id} not found in Spoolman")
  469. response.raise_for_status()
  470. return response
  471. except SpoolmanNotFoundError:
  472. raise
  473. except httpx.HTTPStatusError as e:
  474. if 400 <= e.response.status_code < 500:
  475. logger.warning(
  476. "Spoolman returned %d for %s filament %s",
  477. e.response.status_code,
  478. operation,
  479. filament_id,
  480. )
  481. raise SpoolmanClientError(
  482. f"Spoolman rejected {operation} for filament {filament_id} (HTTP {e.response.status_code})",
  483. e.response.status_code,
  484. e.response.text[:500],
  485. ) from e
  486. else:
  487. logger.error("Failed to %s filament %s in Spoolman: %s", operation, filament_id, e)
  488. raise SpoolmanUnavailableError(f"Failed to {operation} filament {filament_id}") from e
  489. except Exception as e:
  490. logger.error("Failed to %s filament %s in Spoolman: %s", operation, filament_id, e)
  491. raise SpoolmanUnavailableError(f"Failed to {operation} filament {filament_id}") from e
  492. async def get_spool(self, spool_id: int) -> dict:
  493. """Fetch a single spool by ID from Spoolman."""
  494. response = await self._request_spool("GET", spool_id, operation="get")
  495. return response.json()
  496. async def get_all_spools(self, allow_archived: bool = False) -> list[dict]:
  497. """Fetch all spools from Spoolman with retry, optionally including archived ones."""
  498. params: dict = {}
  499. if allow_archived:
  500. params["allow_archived"] = "true"
  501. return await self._get_with_retry("/spool", params=params or None)
  502. async def get_distinct_locations(self) -> list[str]:
  503. """Return distinct location strings currently assigned to Spoolman spools.
  504. Spoolman's `/location` endpoint shape varies across versions: older
  505. releases return `list[str]`, newer ones return `list[dict]` with a
  506. `name` field. Normalize to `list[str]` so callers can iterate without
  507. runtime shape checks.
  508. """
  509. raw = await self._get_with_retry("/location")
  510. if not isinstance(raw, list):
  511. return []
  512. names: list[str] = []
  513. for entry in raw:
  514. if isinstance(entry, str):
  515. names.append(entry)
  516. elif isinstance(entry, dict):
  517. name = entry.get("name")
  518. if isinstance(name, str):
  519. names.append(name)
  520. return names
  521. async def rename_location(self, current_name: str, new_name: str) -> int:
  522. """Bulk-rename a location string on all Spoolman spools.
  523. Tries the bulk `PATCH /location/{name}` endpoint first. Spoolman
  524. versions older than ~0.16 don't expose it and respond 404/405 — in
  525. that case fall back to iterating every spool currently at
  526. ``current_name`` and PATCHing each one's ``location`` field directly.
  527. Returns the number of spools renamed (or 0 if the bulk endpoint
  528. succeeded without enumerating).
  529. """
  530. from urllib.parse import quote
  531. encoded = quote(current_name, safe="")
  532. client = await self._get_client()
  533. try:
  534. response = await client.patch(
  535. f"{self.api_url}/location/{encoded}",
  536. json={"name": new_name},
  537. )
  538. response.raise_for_status()
  539. return 0
  540. except httpx.HTTPStatusError as exc:
  541. if exc.response.status_code not in (404, 405):
  542. raise
  543. logger.info(
  544. "Spoolman bulk-rename endpoint unavailable (status %d); falling back to per-spool PATCH",
  545. exc.response.status_code,
  546. )
  547. # Per-spool fallback: enumerate every spool currently at the old name
  548. # and PATCH each. Keep going on individual failures so a single
  549. # already-deleted spool doesn't strand the rest at the old name —
  550. # collect errors and re-raise as a single SpoolmanClientError if any
  551. # leftover survives.
  552. spools = await self.get_all_spools(allow_archived=True)
  553. renamed = 0
  554. failures: list[str] = []
  555. for spool in spools:
  556. if (spool.get("location") or "").strip() != current_name:
  557. continue
  558. try:
  559. await self._request_spool(
  560. "PATCH",
  561. spool["id"],
  562. json_body={"location": new_name},
  563. operation="rename-location",
  564. )
  565. renamed += 1
  566. except SpoolmanNotFoundError:
  567. continue
  568. except Exception as exc: # noqa: BLE001 — accumulate and re-raise below
  569. failures.append(f"spool {spool.get('id')}: {exc}")
  570. if failures:
  571. raise SpoolmanClientError(
  572. f"Spoolman rename fallback failed for {len(failures)} spool(s): {'; '.join(failures[:3])}",
  573. status_code=502,
  574. )
  575. return renamed
  576. async def delete_spool(self, spool_id: int) -> None:
  577. """Delete a spool from Spoolman."""
  578. await self._request_spool("DELETE", spool_id, operation="delete")
  579. async def is_filament_shared(self, filament_id: int, exclude_spool_id: int) -> bool:
  580. """True if any spool other than ``exclude_spool_id`` is linked to ``filament_id``.
  581. Used by the spool-edit path to decide between PATCHing the existing
  582. filament in place (singleton) and falling back to find_or_create
  583. (shared — re-linking the spool is the only safe option). Includes
  584. archived spools so a shared link doesn't suddenly look singleton just
  585. because the sibling spool was archived.
  586. """
  587. spools = await self.get_all_spools(allow_archived=True)
  588. for s in spools:
  589. if s.get("id") == exclude_spool_id:
  590. continue
  591. if ((s.get("filament") or {}).get("id")) == filament_id:
  592. return True
  593. return False
  594. async def set_spool_archived(self, spool_id: int, archived: bool) -> dict:
  595. """Archive or restore a spool in Spoolman."""
  596. response = await self._request_spool(
  597. "PATCH",
  598. spool_id,
  599. json_body={"archived": archived},
  600. operation="archive/restore",
  601. )
  602. return response.json()
  603. async def reset_spool_usage(self, spool_id: int) -> dict:
  604. """Reset a spool's used_weight to 0 in Spoolman.
  605. Used by the per-spool / bulk "Reset usage to 0" actions on the
  606. Inventory page so the Total Consumed stat can be cleared without
  607. touching the rest of the spool's data.
  608. """
  609. response = await self._request_spool(
  610. "PATCH",
  611. spool_id,
  612. json_body={"used_weight": 0},
  613. operation="reset-usage",
  614. )
  615. return response.json()
  616. async def update_spool_full(
  617. self,
  618. spool_id: int,
  619. *,
  620. filament_id: int | None = None,
  621. remaining_weight: float | None = None,
  622. comment: str | None = None,
  623. price: float | None = None,
  624. location: str | None = None,
  625. clear_location: bool = False,
  626. extra: dict | None = None,
  627. spool_weight: float | None = None,
  628. clear_spool_weight: bool = False,
  629. ) -> dict:
  630. """Update a spool with full field support; unlike update_spool, does not auto-set last_used."""
  631. data: dict = {}
  632. if filament_id is not None:
  633. data["filament_id"] = filament_id
  634. if remaining_weight is not None:
  635. data["remaining_weight"] = remaining_weight
  636. if comment is not None:
  637. data["comment"] = comment if comment else None
  638. if price is not None:
  639. data["price"] = price
  640. if clear_location:
  641. data["location"] = None
  642. elif location is not None:
  643. data["location"] = location
  644. if extra is not None:
  645. data["extra"] = extra
  646. await self._ensure_extra_fields(extra)
  647. if clear_spool_weight:
  648. data["spool_weight"] = None
  649. elif spool_weight is not None:
  650. data["spool_weight"] = spool_weight
  651. response = await self._request_spool("PATCH", spool_id, json_body=data, operation="update")
  652. return response.json()
  653. def extra_lock(self, spool_id: int) -> asyncio.Lock:
  654. """Return (creating if needed) the per-spool asyncio.Lock used by merge_spool_extra."""
  655. lock = self._extra_locks.get(spool_id)
  656. if lock is None:
  657. lock = asyncio.Lock()
  658. self._extra_locks[spool_id] = lock
  659. return lock
  660. async def merge_spool_extra(self, spool_id: int, new_fields: dict) -> dict:
  661. """Fetch the spool's extra dict, merge new_fields into it, then PATCH back — serialised per spool."""
  662. async with self.extra_lock(spool_id):
  663. current = await self.get_spool(spool_id) # raises on error
  664. current_extra: dict = current.get("extra") or {}
  665. merged = {**current_extra, **new_fields}
  666. return await self.update_spool_full(spool_id=spool_id, extra=merged)
  667. async def find_or_create_vendor(self, name: str) -> int:
  668. """Return the Spoolman vendor ID for the given name, creating the vendor if absent."""
  669. vendors = await self.get_vendors()
  670. name_lower = name.strip().lower()
  671. for vendor in vendors:
  672. if vendor.get("name", "").strip().lower() == name_lower:
  673. return vendor["id"]
  674. created = await self.create_vendor(name.strip())
  675. vendor_id = created.get("id")
  676. if not vendor_id:
  677. raise SpoolmanUnavailableError(f"Spoolman returned vendor without id field: {list(created.keys())}")
  678. return vendor_id
  679. async def find_or_create_filament(
  680. self,
  681. material: str,
  682. subtype: str,
  683. brand: str | None,
  684. color_hex: str,
  685. label_weight: int,
  686. color_name: str | None = None,
  687. ) -> int:
  688. """Return the filament ID matching material/name/brand/color, creating it if absent."""
  689. name = f"{material} {subtype}".strip() if subtype else material
  690. # One value in both roles. `color_match_key` returns the shape the colour
  691. # would be stored as, so the key the loop below compares on and the value
  692. # a new filament is created with are the same string by construction: an
  693. # opaque spool keys and stores as six characters, a translucent one as
  694. # eight, and neither can be conflated with the other (#2912).
  695. color = color_match_key(color_hex)
  696. vendor_id: int | None = None
  697. if brand:
  698. vendor_id = await self.find_or_create_vendor(brand)
  699. # Normalised match keys (case-insensitive). Computed once outside the
  700. # loop so the inner comparison stays simple.
  701. composed_subtype = _filament_subtype_part(name, material)
  702. material_norm = material.upper()
  703. brand_norm = (brand or "").strip().lower()
  704. filaments = await self.get_filaments()
  705. for f in filaments:
  706. f_material = (f.get("material") or "").upper()
  707. f_color = color_match_key(f.get("color_hex"))
  708. f_vendor = f.get("vendor") or {}
  709. f_vendor_name = (f_vendor.get("name") or "").strip().lower()
  710. material_match = f_material == material_norm
  711. # Match on the subtype portion of the filament name. AMS-sync
  712. # auto-create (the underscore-prefixed `_find_or_create_filament`
  713. # used during MQTT tray import) stores the filament as just
  714. # ``tray.tray_sub_brands`` — e.g. ``"Glow"`` — while the
  715. # user-driven edit path here composes ``"<material> <subtype>"``
  716. # — ``"PLA Glow"``. The old literal equality `f_name == name`
  717. # failed to bridge the two shapes, so every edit fell through to
  718. # `create_filament`, leaving a trail of duplicate filaments AND
  719. # leaving the spool either still pointed at the old filament
  720. # whose `color_name` never got patched, or pointed at a new
  721. # filament with the colour while the inventory list kept
  722. # showing the synth fallback from the old one (#1357).
  723. f_subtype_part = _filament_subtype_part(f.get("name") or "", material)
  724. name_match = f_subtype_part == composed_subtype
  725. color_match = f_color == color
  726. vendor_match = (not brand) or f_vendor_name == brand_norm
  727. if material_match and name_match and color_match and vendor_match:
  728. # color_name is intentionally not part of the match key and
  729. # is no longer patched onto the filament here: Spoolman 0.23.1
  730. # has no `color_name` field on Filament (#1357 — confirmed
  731. # against the FilamentUpdateParameters schema). The earlier
  732. # #1319 fix tried to patch it and Spoolman silently dropped
  733. # the key, which is exactly why the user's edit looked "not
  734. # saved". The route now persists color_name via
  735. # spool.extra.bambu_color_name (see _map_spoolman_spool for
  736. # the read side); find_or_create_filament's only job is to
  737. # resolve the right filament_id for the spool link.
  738. return f["id"]
  739. # color_name omitted: Spoolman has no such field on Filament (#1357);
  740. # the user's color_name lands in spool.extra.bambu_color_name via the
  741. # route after find_or_create_filament returns the new id.
  742. filament = await self.create_filament(
  743. name=name,
  744. vendor_id=vendor_id,
  745. material=material,
  746. color_hex=color,
  747. weight=float(label_weight),
  748. )
  749. filament_id = filament.get("id")
  750. if not filament_id:
  751. raise SpoolmanUnavailableError(f"Spoolman returned filament without id field: {list(filament.keys())}")
  752. return filament_id
  753. async def use_spool(self, spool_id: int, used_weight: float) -> dict:
  754. """Record filament usage for a spool via the Spoolman /use endpoint."""
  755. try:
  756. client = await self._get_client()
  757. response = await client.put(
  758. f"{self.api_url}/spool/{spool_id}/use",
  759. json={"use_weight": used_weight},
  760. )
  761. if response.status_code == 404:
  762. raise SpoolmanNotFoundError(f"Spool {spool_id} not found in Spoolman")
  763. if 400 <= response.status_code < 500:
  764. raise SpoolmanClientError(
  765. f"Spoolman rejected use_spool for spool {spool_id} (HTTP {response.status_code})",
  766. response.status_code,
  767. )
  768. response.raise_for_status()
  769. return response.json()
  770. except (SpoolmanNotFoundError, SpoolmanClientError):
  771. raise
  772. except Exception as e:
  773. logger.error("Failed to record spool usage in Spoolman: %s", e)
  774. raise SpoolmanUnavailableError(f"Failed to record usage for spool {spool_id}") from e
  775. async def find_spool_by_tag(self, tag_uid: str, cached_spools: list[dict] | None = None) -> dict | None:
  776. """Return the spool matching the given RFID tag UID, or None if not found."""
  777. # Use cached spools if provided, otherwise fetch from API
  778. spools = cached_spools if cached_spools is not None else await self.get_spools()
  779. # Normalize tag_uid for comparison (uppercase, strip quotes)
  780. search_tag = tag_uid.strip('"').upper()
  781. for spool in spools:
  782. extra = spool.get("extra", {})
  783. if extra:
  784. stored_tag = extra.get("tag", "")
  785. # Normalize stored tag (strip quotes, uppercase)
  786. if stored_tag:
  787. normalized_tag = stored_tag.strip('"').upper()
  788. if normalized_tag == search_tag:
  789. logger.debug("Found spool %s matching tag %s", spool["id"], tag_uid)
  790. return spool
  791. return None
  792. def _find_spool_by_location(self, location: str, cached_spools: list[dict] | None) -> dict | None:
  793. """Return the spool at the exact location string, or None; fallback when RFID is unavailable."""
  794. if not cached_spools:
  795. return None
  796. for spool in cached_spools:
  797. if spool.get("location") == location:
  798. return spool
  799. return None
  800. async def find_spools_by_location_prefix(
  801. self, location_prefix: str, cached_spools: list[dict] | None = None
  802. ) -> list[dict]:
  803. """Return all spools whose location starts with location_prefix."""
  804. # Use cached spools if provided, otherwise fetch from API
  805. spools = cached_spools if cached_spools is not None else await self.get_spools()
  806. matching = []
  807. for spool in spools:
  808. location = spool.get("location", "")
  809. if location and location.startswith(location_prefix):
  810. matching.append(spool)
  811. return matching
  812. async def clear_location_for_removed_spools(
  813. self,
  814. printer_name: str,
  815. current_tray_uuids: set[str],
  816. cached_spools: list[dict] | None = None,
  817. synced_spool_ids: set[int] | None = None,
  818. ) -> int:
  819. """Clear location for Bambu Lab spools at this printer whose tray_uuid is no longer in the AMS."""
  820. location_prefix = f"{printer_name} - "
  821. spools_at_printer = await self.find_spools_by_location_prefix(location_prefix, cached_spools=cached_spools)
  822. cleared_count = 0
  823. for spool in spools_at_printer:
  824. spool_id = spool.get("id")
  825. # Skip spools that were just synced (matched by location or tag)
  826. if synced_spool_ids and spool_id in synced_spool_ids:
  827. continue
  828. # Get the tray_uuid (stored as "tag" in extra field)
  829. extra = spool.get("extra", {}) or {}
  830. stored_tag = extra.get("tag", "")
  831. if stored_tag:
  832. # Normalize: strip quotes and uppercase
  833. spool_uuid = stored_tag.strip('"').upper()
  834. else:
  835. spool_uuid = ""
  836. # Only clear location for Bambu Lab spools (those with a stored 32-character RFID tag).
  837. if len(spool_uuid) != BAMBU_RFID_TAG_LENGTH:
  838. continue
  839. # If this spool's UUID is not in the current AMS, clear its location
  840. if spool_uuid not in current_tray_uuids:
  841. logger.info(
  842. f"Clearing location for spool {spool_id} "
  843. f"(was: {spool.get('location')}, uuid: {spool_uuid[:16] if spool_uuid else 'none'}...)"
  844. )
  845. result = await self.update_spool(spool_id=spool_id, clear_location=True)
  846. if result:
  847. cleared_count += 1
  848. return cleared_count
  849. async def ensure_bambu_vendor(self) -> int | None:
  850. """Return the Bambu Lab vendor ID in Spoolman, creating the vendor if absent."""
  851. vendors = await self.get_vendors()
  852. for vendor in vendors:
  853. if vendor.get("name", "").lower() == "bambu lab":
  854. return vendor["id"]
  855. # Create Bambu Lab vendor if not exists
  856. vendor = await self.create_vendor("Bambu Lab")
  857. return vendor["id"] if vendor else None
  858. async def ensure_tag_extra_field(self) -> bool:
  859. """Register the 'tag' extra field in Spoolman if not present; returns True on success."""
  860. return await self.ensure_extra_field("tag")
  861. async def ensure_extra_field(self, name: str, field_type: str = "text") -> bool:
  862. """Register a custom extra field in Spoolman if not present.
  863. Spoolman rejects PATCH requests that include unknown extra-dict keys
  864. with HTTP 400 ('Unknown extra field <name>.'), so any custom field
  865. Bambuddy persists alongside spools needs to be pre-registered.
  866. Idempotent — returns True if the field already exists.
  867. """
  868. try:
  869. client = await self._get_client()
  870. # Check if field already exists
  871. response = await client.get(f"{self.api_url}/field/spool/{name}")
  872. if response.status_code == 200:
  873. logger.debug("Spoolman extra field %r already exists", name)
  874. self._ensured_extra_fields.add(name)
  875. return True
  876. # Field doesn't exist - create it
  877. field_data = {
  878. "name": name,
  879. "field_type": field_type,
  880. "default_value": None,
  881. }
  882. response = await client.post(f"{self.api_url}/field/spool/{name}", json=field_data)
  883. if response.status_code in (200, 201):
  884. logger.info("Created Spoolman extra field %r", name)
  885. self._ensured_extra_fields.add(name)
  886. return True
  887. logger.warning(
  888. "Failed to create Spoolman extra field %r: %s - %s",
  889. name,
  890. response.status_code,
  891. response.text,
  892. )
  893. return False
  894. except Exception as e:
  895. logger.warning("Failed to ensure Spoolman extra field %r exists: %s", name, e)
  896. return False
  897. async def _ensure_extra_fields(self, extra: dict | None) -> None:
  898. """Register every extra key an outgoing write declares, once per client.
  899. Spoolman answers HTTP 400 "Unknown extra field <name>." for any extra
  900. key that was not registered first, so registration has to happen before
  901. the write, not before the feature. It used to happen before the feature:
  902. three hand-maintained lists (the connect route, startup, and two inline
  903. blocks in the inventory routes) each named the fields they expected to
  904. be written later. Enabling Spoolman from Settings reaches none of them,
  905. so the first AMS sync on a fresh Spoolman failed on every slot -- and
  906. the Connect button that would have registered them is hidden by then,
  907. because saving the settings initialises the client and the status
  908. endpoint reads that as "connected" (issue #2903).
  909. Keying off the payload instead removes the chance to forget: a write
  910. that carries a key is a write that registers it. ``bambu_color_name``
  911. is the cautionary case -- it never made it into the connect or startup
  912. lists, and only works today because two call sites remembered to
  913. register it by hand.
  914. Best-effort by design. ``ensure_extra_field`` logs and returns False
  915. rather than raising, and a failure here must not turn a write that
  916. might still succeed into one that never happens -- the caller's own
  917. error handling stays exactly as it was.
  918. """
  919. names = [name for name in (extra or {}) if name not in self._ensured_extra_fields]
  920. if not names:
  921. return
  922. async with self._ensure_extra_lock:
  923. for name in names:
  924. # Re-check under the lock: a concurrent write may have just
  925. # registered this one, and two syncs racing to POST the same
  926. # field is how one of them gets a needless warning logged.
  927. if name not in self._ensured_extra_fields:
  928. await self.ensure_extra_field(name)
  929. def parse_ams_tray(self, ams_id: int, tray_data: dict) -> AMSTray | None:
  930. """Parse raw MQTT tray data into an AMSTray; returns None for empty or invalid trays."""
  931. # Skip empty trays - check for valid tray_type
  932. tray_type = tray_data.get("tray_type", "")
  933. if not tray_type or tray_type.strip() == "":
  934. return None
  935. # Need valid color to create filament
  936. tray_color = tray_data.get("tray_color", "")
  937. if not tray_color or tray_color.strip() == "":
  938. logger.debug("Skipping tray with empty color")
  939. return None
  940. # Transparent filament (alpha=00) used to be rewritten to a cream
  941. # "natural PLA" colour before being stored, because the swatch
  942. # renderer couldn't show alpha. The swatch now paints a checkerboard
  943. # underlay for translucent rgbas (see filamentSwatchHelpers.ts), so
  944. # we pass `00000000` through verbatim — the inventory row keeps the
  945. # AMS-reported colour and the frontend resolves the name to "Clear"
  946. # via getColorName (#1545).
  947. # Get sub_brands, falling back to tray_type
  948. tray_sub_brands = tray_data.get("tray_sub_brands", "")
  949. if not tray_sub_brands or tray_sub_brands.strip() == "":
  950. tray_sub_brands = tray_type
  951. # Get tag_uid and tray_uuid, filtering out empty/invalid values
  952. tag_uid = tray_data.get("tag_uid", "")
  953. if tag_uid in ("", "0000000000000000"):
  954. tag_uid = ""
  955. tray_uuid = tray_data.get("tray_uuid", "")
  956. if tray_uuid in ("", "00000000000000000000000000000000"):
  957. tray_uuid = ""
  958. # Get tray_info_idx (Bambu filament preset ID like "GFA00")
  959. tray_info_idx = tray_data.get("tray_info_idx", "") or ""
  960. # Get remaining percentage (-1 means unknown/not read by AMS)
  961. remain = int(tray_data.get("remain", -1))
  962. return AMSTray(
  963. ams_id=ams_id,
  964. tray_id=int(tray_data.get("id", 0)),
  965. tray_type=tray_type.strip(),
  966. tray_sub_brands=tray_sub_brands.strip(),
  967. tray_color=tray_color,
  968. remain=remain,
  969. tag_uid=tag_uid,
  970. tray_uuid=tray_uuid,
  971. tray_info_idx=tray_info_idx.strip(),
  972. tray_weight=int(tray_data.get("tray_weight", 1000)),
  973. )
  974. def convert_ams_slot_to_location(self, ams_id: int, tray_id: int) -> str:
  975. """Return a human-readable location string (e.g. "AMS A1") for the given AMS slot."""
  976. if ams_id >= 254:
  977. return "External Spool"
  978. if 128 <= ams_id <= 135:
  979. # AMS-HT units use IDs 128-135
  980. ht_letter = chr(ord("A") + (ams_id - 128))
  981. return f"AMS-HT {ht_letter}{tray_id + 1}"
  982. ams_letter = chr(ord("A") + ams_id)
  983. return f"AMS {ams_letter}{tray_id + 1}"
  984. def is_bambu_lab_spool(self, tray_uuid: str, tag_uid: str = "", tray_info_idx: str = "") -> bool:
  985. """Return True if tray_uuid or tag_uid identifies a Bambu Lab spool; tray_info_idx is ignored."""
  986. # Check tray_uuid (preferred - consistent across printer models)
  987. if tray_uuid:
  988. uuid = tray_uuid.strip()
  989. if len(uuid) == 32 and uuid != "00000000000000000000000000000000":
  990. try:
  991. int(uuid, 16)
  992. return True
  993. except ValueError:
  994. pass
  995. # Fallback: check tag_uid (RFID tag - varies between printer readers)
  996. # Bambu Lab RFID tags are 16 hex characters (8 bytes)
  997. if tag_uid:
  998. tag = tag_uid.strip()
  999. if len(tag) == 16 and tag != "0000000000000000":
  1000. try:
  1001. int(tag, 16)
  1002. logger.debug("Identified Bambu Lab spool via tag_uid fallback: %s", tag)
  1003. return True
  1004. except ValueError:
  1005. pass
  1006. return False
  1007. def calculate_remaining_weight(self, remain_percent: int, spool_weight: int) -> float:
  1008. """Return remaining filament weight in grams given a percentage and total spool weight."""
  1009. return (remain_percent / 100.0) * spool_weight
  1010. async def sync_ams_tray(
  1011. self,
  1012. tray: AMSTray,
  1013. printer_name: str,
  1014. disable_weight_sync: bool = False,
  1015. cached_spools: list[dict] | None = None,
  1016. inventory_remaining: float | None = None,
  1017. spoolman_spool_id_hint: int | None = None,
  1018. auto_add_unknown_rfid: bool = True,
  1019. ) -> dict | None:
  1020. """Sync one AMS tray to Spoolman; creates the spool on first sight, updates weight otherwise."""
  1021. logger.debug(
  1022. f"Processing {printer_name} AMS {tray.ams_id} tray {tray.tray_id}: "
  1023. f"type={tray.tray_type}, idx={tray.tray_info_idx or 'none'}, "
  1024. f"uuid={tray.tray_uuid[:16] if tray.tray_uuid else 'none'}, "
  1025. f"tag={tray.tag_uid[:8] if tray.tag_uid else 'none'}..."
  1026. )
  1027. # Determine which identifier to use for Spoolman (prefer tray_uuid, fallback to tag_uid)
  1028. # Zero-filled values mean the AMS hasn't read the RFID tag — treat as no tag
  1029. zero_uuid = "00000000000000000000000000000000"
  1030. zero_tag = "0000000000000000"
  1031. spool_tag = None
  1032. if tray.tray_uuid and tray.tray_uuid != zero_uuid:
  1033. spool_tag = tray.tray_uuid
  1034. elif tray.tag_uid and tray.tag_uid != zero_tag:
  1035. spool_tag = tray.tag_uid
  1036. # Calculate remaining weight
  1037. # Primary: AMS MQTT data (remain percentage + tray_weight)
  1038. # Fallback: Built-in inventory tracked weight (when firmware sends invalid remain/tray_weight)
  1039. if tray.remain >= 0 and tray.tray_weight > 0:
  1040. remaining = self.calculate_remaining_weight(tray.remain, tray.tray_weight)
  1041. elif inventory_remaining is not None:
  1042. remaining = inventory_remaining
  1043. logger.debug(
  1044. "Using inventory weight fallback for %s AMS %s tray %s: %.1fg",
  1045. printer_name,
  1046. tray.ams_id,
  1047. tray.tray_id,
  1048. remaining,
  1049. )
  1050. else:
  1051. remaining = None
  1052. if spool_tag:
  1053. # Primary path: match by RFID tag
  1054. existing = await self.find_spool_by_tag(spool_tag, cached_spools=cached_spools)
  1055. if existing:
  1056. logger.info("Updating existing spool %s for tag %s...", existing["id"], spool_tag[:16])
  1057. return await self.update_spool(
  1058. spool_id=existing["id"],
  1059. remaining_weight=None if disable_weight_sync else remaining,
  1060. )
  1061. # Spool not found by tag - auto-create it, unless the user has
  1062. # opted out of auto-adding unknown RFIDs (settings.auto_add_unknown_rfid).
  1063. # Caller broadcasts unknown_tag on the resulting None so the UI can
  1064. # surface a "+ Add to inventory" affordance on the slot.
  1065. if not auto_add_unknown_rfid:
  1066. logger.info(
  1067. "Auto-add disabled; skipping Spoolman spool create for %s (tag: %s...)",
  1068. tray.tray_sub_brands,
  1069. spool_tag[:16],
  1070. )
  1071. return None
  1072. logger.info("Creating new spool in Spoolman for %s (tag: %s...)", tray.tray_sub_brands, spool_tag[:16])
  1073. if self.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  1074. filament = await self._find_or_create_filament(tray)
  1075. filament_id = filament["id"] if filament else None
  1076. else:
  1077. # Non-BL spool with custom RFID: use generic vendor lookup
  1078. brand = tray.tray_sub_brands if tray.tray_sub_brands != tray.tray_type else None
  1079. try:
  1080. filament_id = await self.find_or_create_filament(
  1081. material=tray.tray_type,
  1082. subtype="",
  1083. brand=brand,
  1084. color_hex=tray.tray_color,
  1085. label_weight=tray.tray_weight,
  1086. )
  1087. except (SpoolmanNotFoundError, SpoolmanUnavailableError, SpoolmanClientError):
  1088. logger.warning("Could not find or create filament for non-BL spool %s", tray.tray_sub_brands)
  1089. return None
  1090. if not filament_id:
  1091. logger.error("Failed to find or create filament for %s", tray.tray_sub_brands)
  1092. return None
  1093. import json
  1094. return await self.create_spool(
  1095. filament_id=filament_id,
  1096. remaining_weight=remaining,
  1097. comment="Created by Bambuddy",
  1098. extra={"tag": json.dumps(spool_tag)},
  1099. )
  1100. # No-RFID fallback: use the spool ID resolved from the local slot-assignment table.
  1101. # Never create new spools without a tag to avoid duplicates.
  1102. if spoolman_spool_id_hint is not None:
  1103. existing = next((s for s in (cached_spools or []) if s.get("id") == spoolman_spool_id_hint), None)
  1104. if existing is None:
  1105. try:
  1106. existing = await self.get_spool(spoolman_spool_id_hint)
  1107. except (SpoolmanNotFoundError, SpoolmanUnavailableError):
  1108. existing = None
  1109. if existing:
  1110. logger.info(
  1111. "Updating spool %s by slot-assignment hint (no RFID tag available)",
  1112. existing["id"],
  1113. )
  1114. return await self.update_spool(
  1115. spool_id=existing["id"],
  1116. remaining_weight=None if disable_weight_sync else remaining,
  1117. )
  1118. logger.info(
  1119. "%s AMS %s tray %s — skipping (no RFID tag and no slot-assignment hint)",
  1120. printer_name,
  1121. tray.ams_id,
  1122. tray.tray_id,
  1123. )
  1124. return None
  1125. async def _find_or_create_filament(self, tray: AMSTray) -> dict | None:
  1126. """Return a Bambu Lab filament matching the tray's material/color, creating it if absent."""
  1127. bambu_vendor_id = await self.ensure_bambu_vendor()
  1128. material_upper = tray.tray_type.upper()
  1129. # Same single value as the user-driven path: the match key is the stored
  1130. # shape. That is what lets an opaque tray still find the six-character
  1131. # filaments every existing instance is full of, while a clear tray keys
  1132. # to eight and gets its own record (#2912).
  1133. color = color_match_key(tray.tray_color)
  1134. # Search internal filaments - only match Bambu Lab vendor
  1135. filaments = await self.get_filaments()
  1136. for filament in filaments:
  1137. fil_vendor_id = filament.get("vendor_id") or filament.get("vendor", {}).get("id")
  1138. if fil_vendor_id != bambu_vendor_id:
  1139. continue
  1140. fil_material = filament.get("material") or ""
  1141. if fil_material.upper() == material_upper and color_match_key(filament.get("color_hex")) == color:
  1142. return filament
  1143. # Search external filaments (SpoolmanDB) — restrict to Bambu Lab only.
  1144. # The /api/v1/external/filament endpoint returns the full multi-vendor catalog
  1145. # with no server-side filter, so without a manufacturer check the first PLA/black
  1146. # hit is typically 3DJAKE or 3DXTECH, not Bambu Lab.
  1147. external = await self.get_external_filaments()
  1148. sub_brand = (tray.tray_sub_brands or "").strip().lower()
  1149. bambu_candidates = []
  1150. for filament in external:
  1151. manufacturer = (filament.get("manufacturer") or "").strip().lower()
  1152. ext_id = (filament.get("id") or "").strip().lower()
  1153. if manufacturer != "bambu lab" and not ext_id.startswith("bambulab_"):
  1154. continue
  1155. fil_material = filament.get("material") or ""
  1156. if fil_material.upper() == material_upper and color_match_key(filament.get("color_hex")) == color:
  1157. bambu_candidates.append(filament)
  1158. if bambu_candidates:
  1159. # Prefer the entry whose `name` matches the AMS `tray_sub_brands`
  1160. # (e.g. "PLA Basic", "Support for PLA/PETG Black") so the more specific
  1161. # variant wins over a generic "Black" entry when both are present.
  1162. chosen = next(
  1163. (f for f in bambu_candidates if (f.get("name") or "").strip().lower() == sub_brand),
  1164. bambu_candidates[0],
  1165. )
  1166. return await self._create_filament_from_external(chosen, tray)
  1167. # Not found in either source - create a new Bambu Lab filament from scratch.
  1168. return await self.create_filament(
  1169. name=tray.tray_sub_brands or tray.tray_type,
  1170. vendor_id=bambu_vendor_id,
  1171. material=tray.tray_type,
  1172. color_hex=color,
  1173. weight=tray.tray_weight,
  1174. )
  1175. async def _create_filament_from_external(self, external: dict, tray: AMSTray) -> dict | None:
  1176. """Create an internal Spoolman filament from an external library entry."""
  1177. vendor_id = await self.ensure_bambu_vendor()
  1178. return await self.create_filament(
  1179. name=external.get("name", tray.tray_sub_brands),
  1180. vendor_id=vendor_id,
  1181. material=external.get("material", tray.tray_type),
  1182. # `or`, not a two-argument get: an entry that carries the key with an
  1183. # explicit null would hand None to create_filament rather than reach
  1184. # the tray fallback. Only a candidate when the tray colour is empty
  1185. # too, so this is a correctness tidy, not a fix for a live path.
  1186. color_hex=external.get("color_hex") or color_match_key(tray.tray_color),
  1187. weight=external.get("weight", tray.tray_weight),
  1188. density=external.get("density"),
  1189. )
  1190. # Global client instance (initialized when settings are loaded)
  1191. _spoolman_client: SpoolmanClient | None = None
  1192. async def get_spoolman_client() -> SpoolmanClient | None:
  1193. """Return the global SpoolmanClient, or None if not configured."""
  1194. return _spoolman_client
  1195. async def init_spoolman_client(url: str) -> SpoolmanClient:
  1196. """Initialise (or reinitialise) the global SpoolmanClient; raises ValueError if url fails SSRF guard."""
  1197. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  1198. assert_safe_spoolman_url(url)
  1199. global _spoolman_client
  1200. if _spoolman_client:
  1201. await _spoolman_client.close()
  1202. _spoolman_client = SpoolmanClient(url)
  1203. return _spoolman_client
  1204. async def close_spoolman_client():
  1205. """Close the global Spoolman client."""
  1206. global _spoolman_client
  1207. if _spoolman_client:
  1208. await _spoolman_client.close()
  1209. _spoolman_client = None