spoolman.py 64 KB

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