spoolman.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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. spool_weight: float | None = None,
  368. ) -> dict:
  369. """Create a new spool in Spoolman."""
  370. data: dict = {"filament_id": filament_id}
  371. if remaining_weight is not None:
  372. data["remaining_weight"] = remaining_weight
  373. if location:
  374. data["location"] = location
  375. if lot_nr:
  376. data["lot_nr"] = lot_nr
  377. if comment:
  378. data["comment"] = comment
  379. # `is not None`, not truthiness: 0 g is a legitimate tare (a spool-less
  380. # coil), and it is not the same answer as "inherit from the filament",
  381. # which is what leaving the field off means to Spoolman.
  382. if spool_weight is not None:
  383. data["spool_weight"] = spool_weight
  384. if extra:
  385. data["extra"] = extra
  386. await self._ensure_extra_fields(extra)
  387. logger.debug("Creating spool in Spoolman: %s", data)
  388. try:
  389. client = await self._get_client()
  390. response = await client.post(f"{self.api_url}/spool", json=data)
  391. if response.status_code == 404:
  392. raise SpoolmanNotFoundError(f"Filament {filament_id} not found in Spoolman")
  393. if 400 <= response.status_code < 500:
  394. raise SpoolmanClientError(
  395. f"Spoolman rejected spool creation (HTTP {response.status_code})",
  396. response.status_code,
  397. )
  398. response.raise_for_status()
  399. result = response.json()
  400. logger.info("Created spool %s in Spoolman", result.get("id"))
  401. return result
  402. except (SpoolmanNotFoundError, SpoolmanClientError):
  403. raise
  404. except Exception as e:
  405. logger.error("Failed to create spool in Spoolman: %s", e)
  406. raise SpoolmanUnavailableError("Cannot reach Spoolman") from e
  407. async def update_spool(
  408. self,
  409. spool_id: int,
  410. remaining_weight: float | None = None,
  411. location: str | None = None,
  412. clear_location: bool = False,
  413. extra: dict | None = None,
  414. ) -> dict:
  415. """Update an existing spool in Spoolman, always setting last_used."""
  416. data: dict = {}
  417. if remaining_weight is not None:
  418. data["remaining_weight"] = remaining_weight
  419. if clear_location:
  420. data["location"] = None
  421. elif location:
  422. data["location"] = location
  423. if extra:
  424. data["extra"] = extra
  425. await self._ensure_extra_fields(extra)
  426. data["last_used"] = datetime.now(timezone.utc).isoformat()
  427. response = await self._request_spool("PATCH", spool_id, json_body=data, operation="update")
  428. return response.json()
  429. async def _request_spool(
  430. self,
  431. method: Literal["GET", "PATCH", "DELETE"],
  432. spool_id: int,
  433. *,
  434. json_body: dict | None = None,
  435. operation: str,
  436. ) -> httpx.Response:
  437. """Perform a spool-scoped HTTP request, translating 404 and errors to named exceptions."""
  438. try:
  439. client = await self._get_client()
  440. response = await client.request(
  441. method,
  442. f"{self.api_url}/spool/{spool_id}",
  443. json=json_body,
  444. )
  445. if response.status_code == 404:
  446. raise SpoolmanNotFoundError(f"Spool {spool_id} not found in Spoolman")
  447. response.raise_for_status()
  448. return response
  449. except SpoolmanNotFoundError:
  450. raise
  451. except httpx.HTTPStatusError as e:
  452. if 400 <= e.response.status_code < 500:
  453. logger.warning(
  454. "Spoolman returned %d for %s spool %s",
  455. e.response.status_code,
  456. operation,
  457. spool_id,
  458. )
  459. raise SpoolmanClientError(
  460. f"Spoolman rejected {operation} for spool {spool_id} (HTTP {e.response.status_code})",
  461. e.response.status_code,
  462. e.response.text[:500],
  463. ) from e
  464. else:
  465. logger.error("Failed to %s spool %s in Spoolman: %s", operation, spool_id, e)
  466. raise SpoolmanUnavailableError(f"Failed to {operation} spool {spool_id}") from e
  467. except Exception as e:
  468. logger.error("Failed to %s spool %s in Spoolman: %s", operation, spool_id, e)
  469. raise SpoolmanUnavailableError(f"Failed to {operation} spool {spool_id}") from e
  470. async def _request_filament(
  471. self,
  472. method: Literal["GET", "PATCH"],
  473. filament_id: int,
  474. *,
  475. json_body: dict | None = None,
  476. operation: str,
  477. ) -> httpx.Response:
  478. """Perform a filament-scoped HTTP request, translating 404 and errors to named exceptions."""
  479. try:
  480. client = await self._get_client()
  481. response = await client.request(
  482. method,
  483. f"{self.api_url}/filament/{filament_id}",
  484. json=json_body,
  485. )
  486. if response.status_code == 404:
  487. raise SpoolmanNotFoundError(f"Filament {filament_id} not found in Spoolman")
  488. response.raise_for_status()
  489. return response
  490. except SpoolmanNotFoundError:
  491. raise
  492. except httpx.HTTPStatusError as e:
  493. if 400 <= e.response.status_code < 500:
  494. logger.warning(
  495. "Spoolman returned %d for %s filament %s",
  496. e.response.status_code,
  497. operation,
  498. filament_id,
  499. )
  500. raise SpoolmanClientError(
  501. f"Spoolman rejected {operation} for filament {filament_id} (HTTP {e.response.status_code})",
  502. e.response.status_code,
  503. e.response.text[:500],
  504. ) from e
  505. else:
  506. logger.error("Failed to %s filament %s in Spoolman: %s", operation, filament_id, e)
  507. raise SpoolmanUnavailableError(f"Failed to {operation} filament {filament_id}") from e
  508. except Exception as e:
  509. logger.error("Failed to %s filament %s in Spoolman: %s", operation, filament_id, e)
  510. raise SpoolmanUnavailableError(f"Failed to {operation} filament {filament_id}") from e
  511. async def get_spool(self, spool_id: int) -> dict:
  512. """Fetch a single spool by ID from Spoolman."""
  513. response = await self._request_spool("GET", spool_id, operation="get")
  514. return response.json()
  515. async def get_all_spools(self, allow_archived: bool = False) -> list[dict]:
  516. """Fetch all spools from Spoolman with retry, optionally including archived ones."""
  517. params: dict = {}
  518. if allow_archived:
  519. params["allow_archived"] = "true"
  520. return await self._get_with_retry("/spool", params=params or None)
  521. async def get_distinct_locations(self) -> list[str]:
  522. """Return distinct location strings currently assigned to Spoolman spools.
  523. Spoolman's `/location` endpoint shape varies across versions: older
  524. releases return `list[str]`, newer ones return `list[dict]` with a
  525. `name` field. Normalize to `list[str]` so callers can iterate without
  526. runtime shape checks.
  527. """
  528. raw = await self._get_with_retry("/location")
  529. if not isinstance(raw, list):
  530. return []
  531. names: list[str] = []
  532. for entry in raw:
  533. if isinstance(entry, str):
  534. names.append(entry)
  535. elif isinstance(entry, dict):
  536. name = entry.get("name")
  537. if isinstance(name, str):
  538. names.append(name)
  539. return names
  540. async def rename_location(self, current_name: str, new_name: str) -> int:
  541. """Bulk-rename a location string on all Spoolman spools.
  542. Tries the bulk `PATCH /location/{name}` endpoint first. Spoolman
  543. versions older than ~0.16 don't expose it and respond 404/405 — in
  544. that case fall back to iterating every spool currently at
  545. ``current_name`` and PATCHing each one's ``location`` field directly.
  546. Returns the number of spools renamed (or 0 if the bulk endpoint
  547. succeeded without enumerating).
  548. """
  549. from urllib.parse import quote
  550. encoded = quote(current_name, safe="")
  551. client = await self._get_client()
  552. try:
  553. response = await client.patch(
  554. f"{self.api_url}/location/{encoded}",
  555. json={"name": new_name},
  556. )
  557. response.raise_for_status()
  558. return 0
  559. except httpx.HTTPStatusError as exc:
  560. if exc.response.status_code not in (404, 405):
  561. raise
  562. logger.info(
  563. "Spoolman bulk-rename endpoint unavailable (status %d); falling back to per-spool PATCH",
  564. exc.response.status_code,
  565. )
  566. # Per-spool fallback: enumerate every spool currently at the old name
  567. # and PATCH each. Keep going on individual failures so a single
  568. # already-deleted spool doesn't strand the rest at the old name —
  569. # collect errors and re-raise as a single SpoolmanClientError if any
  570. # leftover survives.
  571. spools = await self.get_all_spools(allow_archived=True)
  572. renamed = 0
  573. failures: list[str] = []
  574. for spool in spools:
  575. if (spool.get("location") or "").strip() != current_name:
  576. continue
  577. try:
  578. await self._request_spool(
  579. "PATCH",
  580. spool["id"],
  581. json_body={"location": new_name},
  582. operation="rename-location",
  583. )
  584. renamed += 1
  585. except SpoolmanNotFoundError:
  586. continue
  587. except Exception as exc: # noqa: BLE001 — accumulate and re-raise below
  588. failures.append(f"spool {spool.get('id')}: {exc}")
  589. if failures:
  590. raise SpoolmanClientError(
  591. f"Spoolman rename fallback failed for {len(failures)} spool(s): {'; '.join(failures[:3])}",
  592. status_code=502,
  593. )
  594. return renamed
  595. async def delete_spool(self, spool_id: int) -> None:
  596. """Delete a spool from Spoolman."""
  597. await self._request_spool("DELETE", spool_id, operation="delete")
  598. async def is_filament_shared(self, filament_id: int, exclude_spool_id: int) -> bool:
  599. """True if any spool other than ``exclude_spool_id`` is linked to ``filament_id``.
  600. Used by the spool-edit path to decide between PATCHing the existing
  601. filament in place (singleton) and falling back to find_or_create
  602. (shared — re-linking the spool is the only safe option). Includes
  603. archived spools so a shared link doesn't suddenly look singleton just
  604. because the sibling spool was archived.
  605. """
  606. spools = await self.get_all_spools(allow_archived=True)
  607. for s in spools:
  608. if s.get("id") == exclude_spool_id:
  609. continue
  610. if ((s.get("filament") or {}).get("id")) == filament_id:
  611. return True
  612. return False
  613. async def set_spool_archived(self, spool_id: int, archived: bool) -> dict:
  614. """Archive or restore a spool in Spoolman."""
  615. response = await self._request_spool(
  616. "PATCH",
  617. spool_id,
  618. json_body={"archived": archived},
  619. operation="archive/restore",
  620. )
  621. return response.json()
  622. async def reset_spool_consumed_counter(self, spool_id: int) -> dict:
  623. """Zero the displayed consumed counter by recording a baseline in spool.extra.
  624. This used to PATCH ``used_weight = 0``, which is not a baseline: Spoolman
  625. recomputes ``remaining_weight`` as initial minus used, so zeroing used
  626. weight put the spool back to full and threw away the measured remaining
  627. filament. The confirmation copy promised the opposite in all thirteen
  628. locales (#2906).
  629. Writing the baseline into ``extra`` instead touches no native Spoolman
  630. field -- initial, remaining and used all survive -- and is the same
  631. mechanism internal mode has always used for its ``weight_used_baseline``
  632. column, which is what #1644 asked the two modes to share rather than
  633. approximate. ``_map_spoolman_spool`` folds the stored value back into the
  634. baseline it reports.
  635. Serialised on the same per-spool lock as ``merge_spool_extra`` so a
  636. concurrent tag or colour write cannot read the extra dict between this
  637. method's fetch and its PATCH and put the old one back.
  638. """
  639. async with self.extra_lock(spool_id):
  640. current = await self.get_spool(spool_id) # raises on error
  641. used_weight = current.get("used_weight")
  642. try:
  643. baseline = float(used_weight) if used_weight is not None else 0.0
  644. except (TypeError, ValueError):
  645. baseline = 0.0
  646. if not math.isfinite(baseline) or baseline < 0:
  647. baseline = 0.0
  648. merged = {
  649. **(current.get("extra") or {}),
  650. # Stored as a JSON *string*, not a JSON number. Spoolman
  651. # registers an unseen extra key as field_type "text" on first
  652. # write, and its validate_extra_field_value then requires the
  653. # value to decode to a str -- a bare 263.0 is rejected with
  654. # "Value is not a string." and the PATCH 400s, so the reset
  655. # would never land. It has to be right the first time:
  656. # add_or_update_extra_field refuses to change a field's type
  657. # afterwards, so one numeric write would pin the key to text on
  658. # that install permanently. tag, bambu_color_name and both
  659. # slicer keys already store the string form for this reason.
  660. BAMBU_WEIGHT_USED_BASELINE_KEY: json.dumps(str(baseline)),
  661. }
  662. return await self.update_spool_full(spool_id=spool_id, extra=merged)
  663. async def update_spool_full(
  664. self,
  665. spool_id: int,
  666. *,
  667. filament_id: int | None = None,
  668. remaining_weight: float | None = None,
  669. comment: str | None = None,
  670. price: float | None = None,
  671. location: str | None = None,
  672. clear_location: bool = False,
  673. extra: dict | None = None,
  674. spool_weight: float | None = None,
  675. clear_spool_weight: bool = False,
  676. ) -> dict:
  677. """Update a spool with full field support; unlike update_spool, does not auto-set last_used."""
  678. data: dict = {}
  679. if filament_id is not None:
  680. data["filament_id"] = filament_id
  681. if remaining_weight is not None:
  682. data["remaining_weight"] = remaining_weight
  683. if comment is not None:
  684. data["comment"] = comment if comment else None
  685. if price is not None:
  686. data["price"] = price
  687. if clear_location:
  688. data["location"] = None
  689. elif location is not None:
  690. data["location"] = location
  691. if extra is not None:
  692. data["extra"] = extra
  693. await self._ensure_extra_fields(extra)
  694. if clear_spool_weight:
  695. data["spool_weight"] = None
  696. elif spool_weight is not None:
  697. data["spool_weight"] = spool_weight
  698. response = await self._request_spool("PATCH", spool_id, json_body=data, operation="update")
  699. return response.json()
  700. def extra_lock(self, spool_id: int) -> asyncio.Lock:
  701. """Return (creating if needed) the per-spool asyncio.Lock used by merge_spool_extra."""
  702. lock = self._extra_locks.get(spool_id)
  703. if lock is None:
  704. lock = asyncio.Lock()
  705. self._extra_locks[spool_id] = lock
  706. return lock
  707. async def merge_spool_extra(self, spool_id: int, new_fields: dict) -> dict:
  708. """Fetch the spool's extra dict, merge new_fields into it, then PATCH back — serialised per spool."""
  709. async with self.extra_lock(spool_id):
  710. current = await self.get_spool(spool_id) # raises on error
  711. current_extra: dict = current.get("extra") or {}
  712. merged = {**current_extra, **new_fields}
  713. return await self.update_spool_full(spool_id=spool_id, extra=merged)
  714. async def find_or_create_vendor(self, name: str) -> int:
  715. """Return the Spoolman vendor ID for the given name, creating the vendor if absent."""
  716. vendors = await self.get_vendors()
  717. name_lower = name.strip().lower()
  718. for vendor in vendors:
  719. if vendor.get("name", "").strip().lower() == name_lower:
  720. return vendor["id"]
  721. created = await self.create_vendor(name.strip())
  722. vendor_id = created.get("id")
  723. if not vendor_id:
  724. raise SpoolmanUnavailableError(f"Spoolman returned vendor without id field: {list(created.keys())}")
  725. return vendor_id
  726. async def find_or_create_filament(
  727. self,
  728. material: str,
  729. subtype: str,
  730. brand: str | None,
  731. color_hex: str,
  732. label_weight: int,
  733. color_name: str | None = None,
  734. ) -> int:
  735. """Return the filament ID matching material/name/brand/color, creating it if absent."""
  736. name = f"{material} {subtype}".strip() if subtype else material
  737. # One value in both roles. `color_match_key` returns the shape the colour
  738. # would be stored as, so the key the loop below compares on and the value
  739. # a new filament is created with are the same string by construction: an
  740. # opaque spool keys and stores as six characters, a translucent one as
  741. # eight, and neither can be conflated with the other (#2912).
  742. color = color_match_key(color_hex)
  743. vendor_id: int | None = None
  744. if brand:
  745. vendor_id = await self.find_or_create_vendor(brand)
  746. # Normalised match keys (case-insensitive). Computed once outside the
  747. # loop so the inner comparison stays simple.
  748. composed_subtype = _filament_subtype_part(name, material)
  749. material_norm = material.upper()
  750. brand_norm = (brand or "").strip().lower()
  751. filaments = await self.get_filaments()
  752. for f in filaments:
  753. f_material = (f.get("material") or "").upper()
  754. f_color = color_match_key(f.get("color_hex"))
  755. f_vendor = f.get("vendor") or {}
  756. f_vendor_name = (f_vendor.get("name") or "").strip().lower()
  757. material_match = f_material == material_norm
  758. # Match on the subtype portion of the filament name. AMS-sync
  759. # auto-create (the underscore-prefixed `_find_or_create_filament`
  760. # used during MQTT tray import) stores the filament as just
  761. # ``tray.tray_sub_brands`` — e.g. ``"Glow"`` — while the
  762. # user-driven edit path here composes ``"<material> <subtype>"``
  763. # — ``"PLA Glow"``. The old literal equality `f_name == name`
  764. # failed to bridge the two shapes, so every edit fell through to
  765. # `create_filament`, leaving a trail of duplicate filaments AND
  766. # leaving the spool either still pointed at the old filament
  767. # whose `color_name` never got patched, or pointed at a new
  768. # filament with the colour while the inventory list kept
  769. # showing the synth fallback from the old one (#1357).
  770. f_subtype_part = _filament_subtype_part(f.get("name") or "", material)
  771. name_match = f_subtype_part == composed_subtype
  772. color_match = f_color == color
  773. vendor_match = (not brand) or f_vendor_name == brand_norm
  774. if material_match and name_match and color_match and vendor_match:
  775. # color_name is intentionally not part of the match key and
  776. # is no longer patched onto the filament here: Spoolman 0.23.1
  777. # has no `color_name` field on Filament (#1357 — confirmed
  778. # against the FilamentUpdateParameters schema). The earlier
  779. # #1319 fix tried to patch it and Spoolman silently dropped
  780. # the key, which is exactly why the user's edit looked "not
  781. # saved". The route now persists color_name via
  782. # spool.extra.bambu_color_name (see _map_spoolman_spool for
  783. # the read side); find_or_create_filament's only job is to
  784. # resolve the right filament_id for the spool link.
  785. return f["id"]
  786. # color_name omitted: Spoolman has no such field on Filament (#1357);
  787. # the user's color_name lands in spool.extra.bambu_color_name via the
  788. # route after find_or_create_filament returns the new id.
  789. filament = await self.create_filament(
  790. name=name,
  791. vendor_id=vendor_id,
  792. material=material,
  793. color_hex=color,
  794. weight=float(label_weight),
  795. )
  796. filament_id = filament.get("id")
  797. if not filament_id:
  798. raise SpoolmanUnavailableError(f"Spoolman returned filament without id field: {list(filament.keys())}")
  799. return filament_id
  800. async def use_spool(self, spool_id: int, used_weight: float) -> dict:
  801. """Record filament usage for a spool via the Spoolman /use endpoint."""
  802. try:
  803. client = await self._get_client()
  804. response = await client.put(
  805. f"{self.api_url}/spool/{spool_id}/use",
  806. json={"use_weight": used_weight},
  807. )
  808. if response.status_code == 404:
  809. raise SpoolmanNotFoundError(f"Spool {spool_id} not found in Spoolman")
  810. if 400 <= response.status_code < 500:
  811. raise SpoolmanClientError(
  812. f"Spoolman rejected use_spool for spool {spool_id} (HTTP {response.status_code})",
  813. response.status_code,
  814. )
  815. response.raise_for_status()
  816. return response.json()
  817. except (SpoolmanNotFoundError, SpoolmanClientError):
  818. raise
  819. except Exception as e:
  820. logger.error("Failed to record spool usage in Spoolman: %s", e)
  821. raise SpoolmanUnavailableError(f"Failed to record usage for spool {spool_id}") from e
  822. async def find_spool_by_tag(self, tag_uid: str, cached_spools: list[dict] | None = None) -> dict | None:
  823. """Return the spool matching the given RFID tag UID, or None if not found."""
  824. # Use cached spools if provided, otherwise fetch from API
  825. spools = cached_spools if cached_spools is not None else await self.get_spools()
  826. # Normalize tag_uid for comparison (uppercase, strip quotes)
  827. search_tag = tag_uid.strip('"').upper()
  828. for spool in spools:
  829. extra = spool.get("extra", {})
  830. if extra:
  831. stored_tag = extra.get("tag", "")
  832. # Normalize stored tag (strip quotes, uppercase)
  833. if stored_tag:
  834. normalized_tag = stored_tag.strip('"').upper()
  835. if normalized_tag == search_tag:
  836. logger.debug("Found spool %s matching tag %s", spool["id"], tag_uid)
  837. return spool
  838. return None
  839. def _find_spool_by_location(self, location: str, cached_spools: list[dict] | None) -> dict | None:
  840. """Return the spool at the exact location string, or None; fallback when RFID is unavailable."""
  841. if not cached_spools:
  842. return None
  843. for spool in cached_spools:
  844. if spool.get("location") == location:
  845. return spool
  846. return None
  847. async def find_spools_by_location_prefix(
  848. self, location_prefix: str, cached_spools: list[dict] | None = None
  849. ) -> list[dict]:
  850. """Return all spools whose location starts with location_prefix."""
  851. # Use cached spools if provided, otherwise fetch from API
  852. spools = cached_spools if cached_spools is not None else await self.get_spools()
  853. matching = []
  854. for spool in spools:
  855. location = spool.get("location", "")
  856. if location and location.startswith(location_prefix):
  857. matching.append(spool)
  858. return matching
  859. async def clear_location_for_removed_spools(
  860. self,
  861. printer_name: str,
  862. current_tray_uuids: set[str],
  863. cached_spools: list[dict] | None = None,
  864. synced_spool_ids: set[int] | None = None,
  865. ) -> int:
  866. """Clear location for Bambu Lab spools at this printer whose tray_uuid is no longer in the AMS."""
  867. location_prefix = f"{printer_name} - "
  868. spools_at_printer = await self.find_spools_by_location_prefix(location_prefix, cached_spools=cached_spools)
  869. cleared_count = 0
  870. for spool in spools_at_printer:
  871. spool_id = spool.get("id")
  872. # Skip spools that were just synced (matched by location or tag)
  873. if synced_spool_ids and spool_id in synced_spool_ids:
  874. continue
  875. # Get the tray_uuid (stored as "tag" in extra field)
  876. extra = spool.get("extra", {}) or {}
  877. stored_tag = extra.get("tag", "")
  878. if stored_tag:
  879. # Normalize: strip quotes and uppercase
  880. spool_uuid = stored_tag.strip('"').upper()
  881. else:
  882. spool_uuid = ""
  883. # Only clear location for Bambu Lab spools (those with a stored 32-character RFID tag).
  884. if len(spool_uuid) != BAMBU_RFID_TAG_LENGTH:
  885. continue
  886. # If this spool's UUID is not in the current AMS, clear its location
  887. if spool_uuid not in current_tray_uuids:
  888. logger.info(
  889. f"Clearing location for spool {spool_id} "
  890. f"(was: {spool.get('location')}, uuid: {spool_uuid[:16] if spool_uuid else 'none'}...)"
  891. )
  892. result = await self.update_spool(spool_id=spool_id, clear_location=True)
  893. if result:
  894. cleared_count += 1
  895. return cleared_count
  896. async def ensure_bambu_vendor(self) -> int | None:
  897. """Return the Bambu Lab vendor ID in Spoolman, creating the vendor if absent."""
  898. vendors = await self.get_vendors()
  899. for vendor in vendors:
  900. if vendor.get("name", "").lower() == "bambu lab":
  901. return vendor["id"]
  902. # Create Bambu Lab vendor if not exists
  903. vendor = await self.create_vendor("Bambu Lab")
  904. return vendor["id"] if vendor else None
  905. async def ensure_tag_extra_field(self) -> bool:
  906. """Register the 'tag' extra field in Spoolman if not present; returns True on success."""
  907. return await self.ensure_extra_field("tag")
  908. async def _load_existing_extra_field_keys(self) -> set[str] | None:
  909. """Keys of the spool extra fields Spoolman already has, or ``None`` when
  910. the listing could not be read.
  911. ``None`` and ``set()`` mean different things and the caller acts on the
  912. difference: an empty set is "Spoolman has no extra fields", which means
  913. every field Bambuddy needs must be created; ``None`` is "we could not
  914. find out", where the only safe move is to fall back to attempting the
  915. write blind.
  916. """
  917. try:
  918. client = await self._get_client()
  919. response = await client.get(f"{self.api_url}/field/spool")
  920. if response.status_code != 200:
  921. logger.debug(
  922. "Spoolman extra-field listing returned %s; falling back to blind registration",
  923. response.status_code,
  924. )
  925. return None
  926. fields = response.json()
  927. except Exception as e: # noqa: BLE001 — registration is best-effort, see _ensure_extra_fields
  928. logger.debug("Could not read Spoolman extra-field listing: %s", e)
  929. return None
  930. if not isinstance(fields, list):
  931. return None
  932. # Match on `key`, not `name`: `key` is the identifier the extra dict is
  933. # written under and the one Bambuddy cares about, while `name` is the
  934. # free-text label a user is free to change in Spoolman's UI.
  935. return {f["key"] for f in fields if isinstance(f, dict) and isinstance(f.get("key"), str)}
  936. async def ensure_extra_field(self, name: str, field_type: str = "text") -> bool:
  937. """Register a custom extra field in Spoolman if not present.
  938. Spoolman rejects PATCH requests that include unknown extra-dict keys
  939. with HTTP 400 ('Unknown extra field <name>.'), so any custom field
  940. Bambuddy persists alongside spools needs to be pre-registered.
  941. Idempotent — returns True if the field already exists.
  942. Existence is read from ``GET /field/spool``, the whole-listing endpoint.
  943. This used to probe ``GET /field/spool/{name}`` for one field at a time,
  944. which Spoolman has never served: it declares only POST and DELETE at
  945. that path, so the probe answered 405 every time and the check could
  946. never succeed (issue #2983, reported by @ngreatorex).
  947. Falling through to the POST on every call was worse than a wasted
  948. request, because that endpoint is an upsert rather than a create. It
  949. answered 200 whether or not the field was already there, so a field a
  950. user had renamed, retyped or given a default in Spoolman's own UI was
  951. silently reset to Bambuddy's version of it on every restart. Reading
  952. the listing first is what lets an existing field be left alone.
  953. """
  954. try:
  955. if name in self._ensured_extra_fields:
  956. return True
  957. if not self._extra_fields_listed:
  958. existing = await self._load_existing_extra_field_keys()
  959. if existing is not None:
  960. # Bank the whole listing: the caller registers several
  961. # fields in a row, and each one it already has is a request
  962. # not sent and a user customisation not overwritten. Read
  963. # once per client — every field created after this point is
  964. # added to the set as it is created, so re-reading would
  965. # only ever confirm what we already know.
  966. self._ensured_extra_fields |= existing
  967. self._extra_fields_listed = True
  968. if name in existing:
  969. logger.debug("Spoolman extra field %r already exists", name)
  970. return True
  971. client = await self._get_client()
  972. field_data = {
  973. "name": name,
  974. "field_type": field_type,
  975. "default_value": None,
  976. }
  977. response = await client.post(f"{self.api_url}/field/spool/{name}", json=field_data)
  978. if response.status_code in (200, 201):
  979. logger.info("Created Spoolman extra field %r", name)
  980. self._ensured_extra_fields.add(name)
  981. return True
  982. logger.warning(
  983. "Failed to create Spoolman extra field %r: %s - %s",
  984. name,
  985. response.status_code,
  986. response.text,
  987. )
  988. return False
  989. except Exception as e:
  990. logger.warning("Failed to ensure Spoolman extra field %r exists: %s", name, e)
  991. return False
  992. async def _ensure_extra_fields(self, extra: dict | None) -> None:
  993. """Register every extra key an outgoing write declares, once per client.
  994. Spoolman answers HTTP 400 "Unknown extra field <name>." for any extra
  995. key that was not registered first, so registration has to happen before
  996. the write, not before the feature. It used to happen before the feature:
  997. three hand-maintained lists (the connect route, startup, and two inline
  998. blocks in the inventory routes) each named the fields they expected to
  999. be written later. Enabling Spoolman from Settings reaches none of them,
  1000. so the first AMS sync on a fresh Spoolman failed on every slot -- and
  1001. the Connect button that would have registered them is hidden by then,
  1002. because saving the settings initialises the client and the status
  1003. endpoint reads that as "connected" (issue #2903).
  1004. Keying off the payload instead removes the chance to forget: a write
  1005. that carries a key is a write that registers it. ``bambu_color_name``
  1006. is the cautionary case -- it never made it into the connect or startup
  1007. lists, and only works today because two call sites remembered to
  1008. register it by hand.
  1009. Best-effort by design. ``ensure_extra_field`` logs and returns False
  1010. rather than raising, and a failure here must not turn a write that
  1011. might still succeed into one that never happens -- the caller's own
  1012. error handling stays exactly as it was.
  1013. """
  1014. names = [name for name in (extra or {}) if name not in self._ensured_extra_fields]
  1015. if not names:
  1016. return
  1017. async with self._ensure_extra_lock:
  1018. for name in names:
  1019. # Re-check under the lock: a concurrent write may have just
  1020. # registered this one, and two syncs racing to POST the same
  1021. # field is how one of them gets a needless warning logged.
  1022. if name not in self._ensured_extra_fields:
  1023. await self.ensure_extra_field(name)
  1024. def parse_ams_tray(self, ams_id: int, tray_data: dict) -> AMSTray | None:
  1025. """Parse raw MQTT tray data into an AMSTray; returns None for empty or invalid trays."""
  1026. # Skip empty trays - check for valid tray_type
  1027. tray_type = tray_data.get("tray_type", "")
  1028. if not tray_type or tray_type.strip() == "":
  1029. return None
  1030. # Need valid color to create filament
  1031. tray_color = tray_data.get("tray_color", "")
  1032. if not tray_color or tray_color.strip() == "":
  1033. logger.debug("Skipping tray with empty color")
  1034. return None
  1035. # Transparent filament (alpha=00) used to be rewritten to a cream
  1036. # "natural PLA" colour before being stored, because the swatch
  1037. # renderer couldn't show alpha. The swatch now paints a checkerboard
  1038. # underlay for translucent rgbas (see filamentSwatchHelpers.ts), so
  1039. # we pass `00000000` through verbatim — the inventory row keeps the
  1040. # AMS-reported colour and the frontend resolves the name to "Clear"
  1041. # via getColorName (#1545).
  1042. # Get sub_brands, falling back to tray_type
  1043. tray_sub_brands = tray_data.get("tray_sub_brands", "")
  1044. if not tray_sub_brands or tray_sub_brands.strip() == "":
  1045. tray_sub_brands = tray_type
  1046. # Get tag_uid and tray_uuid, filtering out empty/invalid values
  1047. tag_uid = tray_data.get("tag_uid", "")
  1048. if tag_uid in ("", "0000000000000000"):
  1049. tag_uid = ""
  1050. tray_uuid = tray_data.get("tray_uuid", "")
  1051. if tray_uuid in ("", "00000000000000000000000000000000"):
  1052. tray_uuid = ""
  1053. # Get tray_info_idx (Bambu filament preset ID like "GFA00")
  1054. tray_info_idx = tray_data.get("tray_info_idx", "") or ""
  1055. # Get remaining percentage (-1 means unknown/not read by AMS)
  1056. remain = int(tray_data.get("remain", -1))
  1057. return AMSTray(
  1058. ams_id=ams_id,
  1059. tray_id=int(tray_data.get("id", 0)),
  1060. tray_type=tray_type.strip(),
  1061. tray_sub_brands=tray_sub_brands.strip(),
  1062. tray_color=tray_color,
  1063. remain=remain,
  1064. tag_uid=tag_uid,
  1065. tray_uuid=tray_uuid,
  1066. tray_info_idx=tray_info_idx.strip(),
  1067. tray_weight=int(tray_data.get("tray_weight", 1000)),
  1068. )
  1069. def convert_ams_slot_to_location(self, ams_id: int, tray_id: int) -> str:
  1070. """Return a human-readable location string (e.g. "AMS A1") for the given AMS slot."""
  1071. if ams_id >= 254:
  1072. return "External Spool"
  1073. if 128 <= ams_id <= 135:
  1074. # AMS-HT units use IDs 128-135
  1075. ht_letter = chr(ord("A") + (ams_id - 128))
  1076. return f"AMS-HT {ht_letter}{tray_id + 1}"
  1077. ams_letter = chr(ord("A") + ams_id)
  1078. return f"AMS {ams_letter}{tray_id + 1}"
  1079. def is_bambu_lab_spool(self, tray_uuid: str, tag_uid: str = "", tray_info_idx: str = "") -> bool:
  1080. """Return True if tray_uuid or tag_uid identifies a Bambu Lab spool; tray_info_idx is ignored."""
  1081. # Check tray_uuid (preferred - consistent across printer models)
  1082. if tray_uuid:
  1083. uuid = tray_uuid.strip()
  1084. if len(uuid) == 32 and uuid != "00000000000000000000000000000000":
  1085. try:
  1086. int(uuid, 16)
  1087. return True
  1088. except ValueError:
  1089. pass
  1090. # Fallback: check tag_uid (RFID tag - varies between printer readers)
  1091. # Bambu Lab RFID tags are 16 hex characters (8 bytes)
  1092. if tag_uid:
  1093. tag = tag_uid.strip()
  1094. if len(tag) == 16 and tag != "0000000000000000":
  1095. try:
  1096. int(tag, 16)
  1097. logger.debug("Identified Bambu Lab spool via tag_uid fallback: %s", tag)
  1098. return True
  1099. except ValueError:
  1100. pass
  1101. return False
  1102. def calculate_remaining_weight(self, remain_percent: int, spool_weight: int) -> float:
  1103. """Return remaining filament weight in grams given a percentage and total spool weight."""
  1104. return (remain_percent / 100.0) * spool_weight
  1105. async def sync_ams_tray(
  1106. self,
  1107. tray: AMSTray,
  1108. printer_name: str,
  1109. disable_weight_sync: bool = False,
  1110. cached_spools: list[dict] | None = None,
  1111. inventory_remaining: float | None = None,
  1112. spoolman_spool_id_hint: int | None = None,
  1113. auto_add_unknown_rfid: bool = True,
  1114. ) -> dict | None:
  1115. """Sync one AMS tray to Spoolman; creates the spool on first sight, updates weight otherwise."""
  1116. logger.debug(
  1117. f"Processing {printer_name} AMS {tray.ams_id} tray {tray.tray_id}: "
  1118. f"type={tray.tray_type}, idx={tray.tray_info_idx or 'none'}, "
  1119. f"uuid={tray.tray_uuid[:16] if tray.tray_uuid else 'none'}, "
  1120. f"tag={tray.tag_uid[:8] if tray.tag_uid else 'none'}..."
  1121. )
  1122. # Determine which identifier to use for Spoolman (prefer tray_uuid, fallback to tag_uid)
  1123. # Zero-filled values mean the AMS hasn't read the RFID tag — treat as no tag
  1124. zero_uuid = "00000000000000000000000000000000"
  1125. zero_tag = "0000000000000000"
  1126. spool_tag = None
  1127. if tray.tray_uuid and tray.tray_uuid != zero_uuid:
  1128. spool_tag = tray.tray_uuid
  1129. elif tray.tag_uid and tray.tag_uid != zero_tag:
  1130. spool_tag = tray.tag_uid
  1131. # Calculate remaining weight
  1132. # Primary: AMS MQTT data (remain percentage + tray_weight)
  1133. # Fallback: Built-in inventory tracked weight (when firmware sends invalid remain/tray_weight)
  1134. if tray.remain >= 0 and tray.tray_weight > 0:
  1135. remaining = self.calculate_remaining_weight(tray.remain, tray.tray_weight)
  1136. elif inventory_remaining is not None:
  1137. remaining = inventory_remaining
  1138. logger.debug(
  1139. "Using inventory weight fallback for %s AMS %s tray %s: %.1fg",
  1140. printer_name,
  1141. tray.ams_id,
  1142. tray.tray_id,
  1143. remaining,
  1144. )
  1145. else:
  1146. remaining = None
  1147. if spool_tag:
  1148. # Primary path: match by RFID tag
  1149. existing = await self.find_spool_by_tag(spool_tag, cached_spools=cached_spools)
  1150. if existing:
  1151. logger.info("Updating existing spool %s for tag %s...", existing["id"], spool_tag[:16])
  1152. return await self.update_spool(
  1153. spool_id=existing["id"],
  1154. remaining_weight=None if disable_weight_sync else remaining,
  1155. )
  1156. # Spool not found by tag - auto-create it, unless the user has
  1157. # opted out of auto-adding unknown RFIDs (settings.auto_add_unknown_rfid).
  1158. # Caller broadcasts unknown_tag on the resulting None so the UI can
  1159. # surface a "+ Add to inventory" affordance on the slot.
  1160. if not auto_add_unknown_rfid:
  1161. logger.info(
  1162. "Auto-add disabled; skipping Spoolman spool create for %s (tag: %s...)",
  1163. tray.tray_sub_brands,
  1164. spool_tag[:16],
  1165. )
  1166. return None
  1167. logger.info("Creating new spool in Spoolman for %s (tag: %s...)", tray.tray_sub_brands, spool_tag[:16])
  1168. if self.is_bambu_lab_spool(tray.tray_uuid, tray.tag_uid, tray.tray_info_idx):
  1169. filament = await self._find_or_create_filament(tray)
  1170. filament_id = filament["id"] if filament else None
  1171. else:
  1172. # Non-BL spool with custom RFID: use generic vendor lookup
  1173. brand = tray.tray_sub_brands if tray.tray_sub_brands != tray.tray_type else None
  1174. try:
  1175. filament_id = await self.find_or_create_filament(
  1176. material=tray.tray_type,
  1177. subtype="",
  1178. brand=brand,
  1179. color_hex=tray.tray_color,
  1180. label_weight=tray.tray_weight,
  1181. )
  1182. except (SpoolmanNotFoundError, SpoolmanUnavailableError, SpoolmanClientError):
  1183. logger.warning("Could not find or create filament for non-BL spool %s", tray.tray_sub_brands)
  1184. return None
  1185. if not filament_id:
  1186. logger.error("Failed to find or create filament for %s", tray.tray_sub_brands)
  1187. return None
  1188. return await self.create_spool(
  1189. filament_id=filament_id,
  1190. remaining_weight=remaining,
  1191. comment="Created by Bambuddy",
  1192. extra={"tag": json.dumps(spool_tag)},
  1193. )
  1194. # No-RFID fallback: use the spool ID resolved from the local slot-assignment table.
  1195. # Never create new spools without a tag to avoid duplicates.
  1196. if spoolman_spool_id_hint is not None:
  1197. existing = next((s for s in (cached_spools or []) if s.get("id") == spoolman_spool_id_hint), None)
  1198. if existing is None:
  1199. try:
  1200. existing = await self.get_spool(spoolman_spool_id_hint)
  1201. except (SpoolmanNotFoundError, SpoolmanUnavailableError):
  1202. existing = None
  1203. if existing:
  1204. logger.info(
  1205. "Updating spool %s by slot-assignment hint (no RFID tag available)",
  1206. existing["id"],
  1207. )
  1208. return await self.update_spool(
  1209. spool_id=existing["id"],
  1210. remaining_weight=None if disable_weight_sync else remaining,
  1211. )
  1212. logger.info(
  1213. "%s AMS %s tray %s — skipping (no RFID tag and no slot-assignment hint)",
  1214. printer_name,
  1215. tray.ams_id,
  1216. tray.tray_id,
  1217. )
  1218. return None
  1219. async def _find_or_create_filament(self, tray: AMSTray) -> dict | None:
  1220. """Return a Bambu Lab filament matching the tray's material/color, creating it if absent."""
  1221. bambu_vendor_id = await self.ensure_bambu_vendor()
  1222. material_upper = tray.tray_type.upper()
  1223. # Same single value as the user-driven path: the match key is the stored
  1224. # shape. That is what lets an opaque tray still find the six-character
  1225. # filaments every existing instance is full of, while a clear tray keys
  1226. # to eight and gets its own record (#2912).
  1227. color = color_match_key(tray.tray_color)
  1228. # Search internal filaments - only match Bambu Lab vendor
  1229. filaments = await self.get_filaments()
  1230. for filament in filaments:
  1231. fil_vendor_id = filament.get("vendor_id") or filament.get("vendor", {}).get("id")
  1232. if fil_vendor_id != bambu_vendor_id:
  1233. continue
  1234. fil_material = filament.get("material") or ""
  1235. if fil_material.upper() == material_upper and color_match_key(filament.get("color_hex")) == color:
  1236. return filament
  1237. # Search external filaments (SpoolmanDB) — restrict to Bambu Lab only.
  1238. # The /api/v1/external/filament endpoint returns the full multi-vendor catalog
  1239. # with no server-side filter, so without a manufacturer check the first PLA/black
  1240. # hit is typically 3DJAKE or 3DXTECH, not Bambu Lab.
  1241. external = await self.get_external_filaments()
  1242. sub_brand = (tray.tray_sub_brands or "").strip().lower()
  1243. bambu_candidates = []
  1244. for filament in external:
  1245. manufacturer = (filament.get("manufacturer") or "").strip().lower()
  1246. ext_id = (filament.get("id") or "").strip().lower()
  1247. if manufacturer != "bambu lab" and not ext_id.startswith("bambulab_"):
  1248. continue
  1249. fil_material = filament.get("material") or ""
  1250. if fil_material.upper() == material_upper and color_match_key(filament.get("color_hex")) == color:
  1251. bambu_candidates.append(filament)
  1252. if bambu_candidates:
  1253. # Prefer the entry whose `name` matches the AMS `tray_sub_brands`
  1254. # (e.g. "PLA Basic", "Support for PLA/PETG Black") so the more specific
  1255. # variant wins over a generic "Black" entry when both are present.
  1256. chosen = next(
  1257. (f for f in bambu_candidates if (f.get("name") or "").strip().lower() == sub_brand),
  1258. bambu_candidates[0],
  1259. )
  1260. return await self._create_filament_from_external(chosen, tray)
  1261. # Not found in either source - create a new Bambu Lab filament from scratch.
  1262. return await self.create_filament(
  1263. name=tray.tray_sub_brands or tray.tray_type,
  1264. vendor_id=bambu_vendor_id,
  1265. material=tray.tray_type,
  1266. color_hex=color,
  1267. weight=tray.tray_weight,
  1268. )
  1269. async def _create_filament_from_external(self, external: dict, tray: AMSTray) -> dict | None:
  1270. """Create an internal Spoolman filament from an external library entry."""
  1271. vendor_id = await self.ensure_bambu_vendor()
  1272. return await self.create_filament(
  1273. name=external.get("name", tray.tray_sub_brands),
  1274. vendor_id=vendor_id,
  1275. material=external.get("material", tray.tray_type),
  1276. # `or`, not a two-argument get: an entry that carries the key with an
  1277. # explicit null would hand None to create_filament rather than reach
  1278. # the tray fallback. Only a candidate when the tray colour is empty
  1279. # too, so this is a correctness tidy, not a fix for a live path.
  1280. color_hex=external.get("color_hex") or color_match_key(tray.tray_color),
  1281. weight=external.get("weight", tray.tray_weight),
  1282. density=external.get("density"),
  1283. )
  1284. # Global client instance (initialized when settings are loaded)
  1285. _spoolman_client: SpoolmanClient | None = None
  1286. async def get_spoolman_client() -> SpoolmanClient | None:
  1287. """Return the global SpoolmanClient, or None if not configured."""
  1288. return _spoolman_client
  1289. async def init_spoolman_client(url: str) -> SpoolmanClient:
  1290. """Initialise (or reinitialise) the global SpoolmanClient; raises ValueError if url fails SSRF guard."""
  1291. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  1292. assert_safe_spoolman_url(url)
  1293. global _spoolman_client
  1294. if _spoolman_client:
  1295. await _spoolman_client.close()
  1296. _spoolman_client = SpoolmanClient(url)
  1297. return _spoolman_client
  1298. async def close_spoolman_client():
  1299. """Close the global Spoolman client."""
  1300. global _spoolman_client
  1301. if _spoolman_client:
  1302. await _spoolman_client.close()
  1303. _spoolman_client = None