spoolman.py 61 KB

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