_spoolman_helpers.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. """Pure helper functions for Spoolman spool mapping.
  2. No heavy dependencies — importable in unit tests without the full backend stack.
  3. """
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import math
  8. import re
  9. from typing import Any
  10. from typing_extensions import TypedDict
  11. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  12. logger = logging.getLogger(__name__)
  13. class MappedSpoolFields(TypedDict):
  14. """Full shape of the dict returned by _map_spoolman_spool (InventorySpool-compatible)."""
  15. id: int
  16. material: str | None
  17. subtype: str | None
  18. brand: str | None
  19. color_name: str | None
  20. color_name_is_synthesized: bool
  21. rgba: str | None
  22. extra_colors: str | None
  23. effect_type: None
  24. label_weight: int | None
  25. core_weight: int | None
  26. core_weight_is_inherited: bool
  27. core_weight_catalog_id: None
  28. weight_used: float | None
  29. weight_used_baseline: float | None
  30. weight_locked: bool
  31. last_scale_weight: None
  32. last_weighed_at: None
  33. slicer_filament: None
  34. slicer_filament_name: str | None
  35. nozzle_temp_min: int | None
  36. nozzle_temp_max: None
  37. note: str | None
  38. added_full: None
  39. last_used: str | None
  40. # Last drying (#2863), stored under the bambu_last_dried_* extra keys.
  41. last_dried_at: str | None
  42. last_dried_temp: int | None
  43. last_dried_hours: float | None
  44. encode_time: str | None
  45. tag_uid: str | None
  46. tray_uuid: str | None
  47. data_origin: str | None
  48. tag_type: str | None
  49. archived_at: str | None
  50. created_at: str | None # None when Spoolman spool has no registered timestamp
  51. updated_at: str | None
  52. cost_per_kg: float | None
  53. # Spoolman's native filament.article_number, surfaced as the internal
  54. # material number (#2870). Read-only in Spoolman mode — the number is
  55. # filament-level there and maintained in Spoolman itself.
  56. material_number: str | None
  57. storage_location: str | None
  58. location_id: int | None
  59. k_profiles: list[Any]
  60. class NormalizedVendorRef(TypedDict):
  61. """Vendor reference embedded in a NormalizedFilament."""
  62. id: int
  63. name: str
  64. class NormalizedFilament(TypedDict):
  65. """Normalised Spoolman filament dict returned by the /filaments catalog endpoint."""
  66. id: int
  67. name: str
  68. material: str | None
  69. color_hex: str | None
  70. color_name: str | None
  71. weight: int | None
  72. spool_weight: float | None
  73. vendor: NormalizedVendorRef | None
  74. def assert_safe_spoolman_url(url: str) -> None:
  75. """Raise ValueError if the Spoolman *url* should be blocked as an SSRF risk.
  76. Thin wrapper over the shared LAN-service policy — see
  77. ``_url_safety.assert_safe_lan_service_url`` for what is and isn't
  78. rejected, and why loopback/RFC-1918 are deliberately permitted (running
  79. Spoolman on the same host or home LAN is THE normal topology).
  80. Kept as a named function because the "Spoolman URL …" wording in its
  81. errors is user-facing and asserted by existing tests.
  82. """
  83. assert_safe_lan_service_url(url, label="Spoolman URL")
  84. # Six characters, or eight when the filament carries an alpha byte. The write
  85. # side stores eight only for genuinely translucent spools (#2912); rejecting
  86. # them here turned every clear spool into neutral grey on read.
  87. _COLOR_HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$")
  88. _TAG_HEX_RE = re.compile(r"^[0-9A-F]+$")
  89. def _safe_int(value: object, fallback: int) -> int:
  90. """Convert value to int, returning fallback for None/NaN/Inf/non-numeric."""
  91. try:
  92. f = float(value) # type: ignore[arg-type]
  93. if math.isfinite(f):
  94. return int(f)
  95. except (TypeError, ValueError):
  96. pass
  97. return fallback
  98. def _safe_float(value: object, fallback: float) -> float:
  99. """Convert value to float, returning fallback for None/NaN/Inf/non-numeric."""
  100. try:
  101. f = float(value) # type: ignore[arg-type]
  102. if math.isfinite(f):
  103. return f
  104. except (TypeError, ValueError):
  105. pass
  106. return fallback
  107. def _safe_optional_float(value: object) -> float | None:
  108. """Convert value to finite float, or None if missing/NaN/Infinite/non-numeric.
  109. Used for optional monetary fields (price) to prevent Infinity/NaN from
  110. reaching JSON serialisation, which raises ValueError with allow_nan=False.
  111. """
  112. if value is None:
  113. return None
  114. try:
  115. f = float(value) # type: ignore[arg-type]
  116. if math.isfinite(f):
  117. return f
  118. except (TypeError, ValueError):
  119. pass
  120. return None
  121. # Used only when Spoolman has no empty-spool weight at any level.
  122. SPOOLMAN_FALLBACK_TARE = 250.0
  123. def spoolman_tare(spool: dict) -> tuple[float, str]:
  124. """The empty-spool weight of a Spoolman spool, and where it came from.
  125. Spoolman resolves the tare as the spool's own ``spool_weight``, then the
  126. filament's ``spool_weight``, then the vendor's ``empty_spool_weight``, and
  127. its own ``/measure`` endpoint follows that order. Skipping the vendor
  128. level made a spool whose tare lives only on its vendor weigh against
  129. 250 g instead (#3195). Every Spoolman-mode tare in Bambuddy goes through
  130. here so the weigh endpoints and the displayed core weight cannot drift
  131. apart again.
  132. Returns ``(grams, source)`` with source one of ``"spool"``,
  133. ``"filament"``, ``"vendor"`` or ``"fallback"``. 0 is a real tare, not a
  134. missing one; a value that is not a finite number counts as missing.
  135. """
  136. filament = spool.get("filament") or {}
  137. vendor = filament.get("vendor") or {}
  138. for source, raw in (
  139. ("spool", spool.get("spool_weight")),
  140. ("filament", filament.get("spool_weight")),
  141. ("vendor", vendor.get("empty_spool_weight")),
  142. ):
  143. value = _safe_optional_float(raw)
  144. if value is not None:
  145. return value, source
  146. return SPOOLMAN_FALLBACK_TARE, "fallback"
  147. def spoolman_net_weight(spool: dict) -> float | None:
  148. """The net filament weight of a full Spoolman spool (its label weight).
  149. Spoolman keeps it on the spool as ``initial_weight`` and falls back to the
  150. filament's catalogue ``weight``, so one filament can have spools of
  151. different sizes. Reading only the filament made a 250 g spool of a 1000 g
  152. filament look four times its size (#3194). Like Spoolman, an
  153. ``initial_weight`` of 0 counts as unset.
  154. Returns None when neither level has a finite number (a bool is not
  155. one); the filament's value is otherwise returned as stored, 0 included,
  156. so callers keep their own handling of a filament without a weight.
  157. """
  158. initial = _weight_or_none(spool.get("initial_weight"))
  159. if initial is not None and initial > 0:
  160. return initial
  161. filament = spool.get("filament")
  162. return _weight_or_none(filament.get("weight")) if isinstance(filament, dict) else None
  163. def _weight_or_none(value: object) -> float | None:
  164. # A bool is an int in Python; True must not read as a 1 g spool.
  165. return None if isinstance(value, bool) else _safe_optional_float(value)
  166. def spoolman_price_to_cost_per_kg(price: object, net_weight: float) -> float | None:
  167. """A Spoolman spool price as a price per kilogram.
  168. Spoolman's ``price`` on a spool is what that spool cost, not a rate; the
  169. spool form edits a rate, so the two are converted at the spool's net
  170. weight. They agree only for 1000 g spools (#3194). Rounded to 4 places so
  171. a round trip through the form doesn't drift by float noise.
  172. """
  173. value = _safe_optional_float(price)
  174. if value is None or net_weight <= 0:
  175. return None
  176. return round(value * 1000.0 / net_weight, 4)
  177. def cost_per_kg_to_spoolman_price(cost_per_kg: float, net_weight: float) -> float:
  178. """Inverse of spoolman_price_to_cost_per_kg: the price of a spool of ``net_weight`` grams."""
  179. return round(cost_per_kg * net_weight / 1000.0, 4)
  180. def spoolman_price_weight(spool: dict) -> float:
  181. """The weight a Spoolman spool's price is converted at.
  182. The spool's exact net weight, not the whole-gram label weight, so a
  183. 250.7 g spool is not re-priced by a no-op edit. A spool with no usable
  184. weight keeps the old 1:1 reading of its price as a per-kg rate.
  185. """
  186. net = spoolman_net_weight(spool)
  187. return net if net is not None and net > 0 else 1000.0
  188. def spoolman_cost_per_kg(spool: dict) -> float | None:
  189. """The spool form's cost per kg for a Spoolman spool (#3194)."""
  190. return spoolman_price_to_cost_per_kg(spool.get("price"), spoolman_price_weight(spool))
  191. def _extract_extra_str(extra: dict, key: str) -> str:
  192. """Extract a JSON-encoded string from a Spoolman extra dict.
  193. Spoolman stores extra values as JSON-stringified text — a stored string
  194. "GFL05" appears as `'"GFL05"'` (six chars including the quotes). This
  195. unwraps that, returning the bare string. Returns "" for missing keys,
  196. non-strings, or invalid JSON.
  197. """
  198. raw = extra.get(key)
  199. if not isinstance(raw, str):
  200. return ""
  201. try:
  202. decoded = json.loads(raw)
  203. except (json.JSONDecodeError, ValueError):
  204. # Tolerate bare-string values written without JSON encoding.
  205. return raw
  206. return decoded if isinstance(decoded, str) else ""
  207. # Spool.extra key holding the consumed-counter baseline: the value Spoolman's
  208. # used_weight had when the user last pressed "Reset usage to 0". Displayed
  209. # consumed is used_weight minus this, which is what internal mode has always
  210. # done with its own weight_used_baseline column (#1644). See #2906.
  211. BAMBU_WEIGHT_USED_BASELINE_KEY = "bambu_weight_used_baseline"
  212. # Spool.extra keys holding when the spool was last dried, the target °C and the
  213. # hours the cycle ran (#2863). Written by services/spool_drying.py and the
  214. # spool update route; an empty string means unknown or cleared.
  215. BAMBU_LAST_DRIED_AT_KEY = "bambu_last_dried_at"
  216. BAMBU_LAST_DRIED_TEMP_KEY = "bambu_last_dried_temp"
  217. BAMBU_LAST_DRIED_HOURS_KEY = "bambu_last_dried_hours"
  218. def _extract_extra_float(extra: dict, key: str) -> float | None:
  219. """Extract a JSON-encoded number from a Spoolman extra dict.
  220. Same storage convention as :func:`_extract_extra_str` — Spoolman keeps
  221. extra values as JSON text, so 250.0 is stored as ``"250.0"``. Returns
  222. ``None`` for missing keys, non-finite values, or anything that does not
  223. decode to a number, so the caller can tell "no baseline recorded" from
  224. "a baseline of zero".
  225. """
  226. raw = extra.get(key)
  227. if raw is None:
  228. return None
  229. if isinstance(raw, (int, float)) and not isinstance(raw, bool):
  230. value = float(raw)
  231. elif isinstance(raw, str):
  232. try:
  233. decoded = json.loads(raw)
  234. except (json.JSONDecodeError, ValueError):
  235. return None
  236. if isinstance(decoded, str):
  237. # Spoolman's extra fields default to field_type "text", which only
  238. # accepts values that decode to a str, so numbers written through
  239. # it arrive as '"263.0"' rather than '263.0'. Both spellings have
  240. # to read back the same, or a baseline written by the reset would
  241. # be invisible to the code that subtracts it.
  242. try:
  243. value = float(decoded)
  244. except ValueError:
  245. return None
  246. elif isinstance(decoded, (int, float)) and not isinstance(decoded, bool):
  247. value = float(decoded)
  248. else:
  249. return None
  250. else:
  251. return None
  252. return value if math.isfinite(value) else None
  253. def parse_spoolman_multi_colors(filament: dict) -> list[str]:
  254. """Spoolman's ``multi_color_hexes`` as a list of bare 6/8-char hex tokens.
  255. Spoolman stores the extra stops of a gradient / dual / multi-colour
  256. filament here, and writes the field as a comma-separated string in some
  257. releases and a list in others -- both shapes are accepted. Tokens keep the
  258. case they arrived in and lose any leading ``#``, which is the form
  259. ``Spool.extra_colors`` stores and ``parseStops`` on the client expects.
  260. Shared with the label renderer rather than parsed twice: the two read the
  261. same field for the same purpose, and a swatch on a printer card that
  262. disagreed with the swatch on the printed label would be worse than either
  263. being wrong on its own.
  264. """
  265. raw = filament.get("multi_color_hexes")
  266. if isinstance(raw, str):
  267. tokens = raw.split(",")
  268. elif isinstance(raw, list):
  269. tokens = [str(token) for token in raw]
  270. else:
  271. return []
  272. return [cleaned for token in tokens if (cleaned := token.strip().lstrip("#"))]
  273. def _last_dried_temp(extra: dict) -> int | None:
  274. value = _extract_extra_float(extra, BAMBU_LAST_DRIED_TEMP_KEY)
  275. return int(round(value)) if value is not None and value > 0 else None
  276. def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
  277. """Convert a raw Spoolman spool dict to the InventorySpool-compatible format.
  278. Fields not supported by Spoolman (k_profiles, slicer_filament, …) are
  279. returned as None / empty so the frontend can still render them without
  280. errors. The ``data_origin`` field is set to ``"spoolman"`` so UI code can
  281. distinguish these spools from local ones.
  282. """
  283. raw_id = spool.get("id")
  284. if raw_id is None:
  285. raise ValueError("Spoolman spool is missing required 'id' field")
  286. try:
  287. spool_id: int = int(raw_id)
  288. except (TypeError, ValueError):
  289. raise ValueError(f"Spoolman spool 'id' is not a valid integer: {raw_id!r}")
  290. if spool_id <= 0:
  291. raise ValueError(f"Spoolman spool 'id' must be a positive integer, got {spool_id}")
  292. filament: dict = spool.get("filament") or {}
  293. if not filament:
  294. logger.warning(
  295. "Spoolman spool %s has no filament data — all filament fields will use defaults",
  296. spool_id,
  297. )
  298. vendor: dict = filament.get("vendor") or {}
  299. extra: dict = spool.get("extra") or {}
  300. # RFID tag stored as JSON-encoded string in Spoolman extra.tag.
  301. # 32-char hex → Bambu Lab tray UUID; 8–30-char hex → NFC tag UID.
  302. # Accepting the full realistic UID range (4-byte = 8 chars, 7-byte = 14 chars,
  303. # 10-byte = 20 chars) avoids silently dropping valid SpoolBuddy-written tags.
  304. raw_tag: str = (extra.get("tag") or "").strip('"').upper()
  305. _raw_is_hex = bool(_TAG_HEX_RE.match(raw_tag))
  306. tag_uid = raw_tag if _raw_is_hex and 8 <= len(raw_tag) <= 30 else None
  307. tray_uuid = raw_tag if _raw_is_hex and len(raw_tag) == 32 else None
  308. # Spoolman 0.27+ native tags fill whichever of the two extra.tag left empty,
  309. # so a spool linked there shows as tagged here as well.
  310. for native in spool.get("tags") or []:
  311. uid = str(native.get("uid") or "").upper()
  312. if not _TAG_HEX_RE.match(uid):
  313. continue
  314. if len(uid) == 32:
  315. tray_uuid = tray_uuid or uid
  316. elif 8 <= len(uid) <= 30:
  317. tag_uid = tag_uid or uid
  318. # Subtype = filament name with material prefix stripped
  319. material: str = (filament.get("material") or "").strip()
  320. filament_name: str = (filament.get("name") or "").strip()
  321. if material and filament_name.upper().startswith(material.upper()):
  322. subtype: str | None = filament_name[len(material) :].strip() or None
  323. else:
  324. subtype = filament_name or None
  325. # Colour: validate as 6- or 8-char hex; fall back to neutral grey for invalid
  326. # values. An 8-char value already carries its alpha, so appending the opaque
  327. # byte would push it to ten and lose the translucency it was stored to keep.
  328. raw_color = (filament.get("color_hex") or "").upper().removeprefix("#")
  329. color_hex: str = raw_color if _COLOR_HEX_RE.match(raw_color) else "808080"
  330. rgba: str = color_hex if len(color_hex) == 8 else color_hex + "FF"
  331. # Spoolman carries the extra stops but has no concept of a surface effect
  332. # -- its only neighbouring field is `multi_color_direction`, which says how
  333. # the stops are laid out, not that the filament is silk or glitter. So a
  334. # Spoolman spool can render its gradient and never an effect overlay, and
  335. # `effect_type` is pinned to None rather than guessed at.
  336. extra_stops = parse_spoolman_multi_colors(filament)
  337. extra_colors: str | None = ",".join(extra_stops) if extra_stops else None
  338. label_weight: int = _safe_int(spoolman_net_weight(spool), 1000)
  339. real_used_weight: float = _safe_float(spool.get("used_weight"), 0.0)
  340. # Parity with internal mode (#1390): the InventorySpool shape lets the
  341. # frontend compute `remaining = label_weight - weight_used` and
  342. # `consumed = weight_used - weight_used_baseline`. Map Spoolman's two
  343. # independent fields (used_weight, remaining_weight) onto that shape:
  344. # weight_used = label_weight - remaining_weight (so remaining matches)
  345. # baseline = weight_used - used_weight (so consumed matches)
  346. # When remaining_weight is unset (legacy spools, or filament linked but
  347. # never primed), fall back to the old behaviour: weight_used =
  348. # used_weight, baseline = 0.
  349. #
  350. # A "Reset usage to 0" records the then-current used_weight under
  351. # BAMBU_WEIGHT_USED_BASELINE_KEY in spool.extra and touches nothing else,
  352. # so displayed consumed is used_weight minus that. It is folded into the
  353. # baseline here because the frontend's arithmetic is fixed: it always shows
  354. # `weight_used - weight_used_baseline`. The reset used to PATCH Spoolman's
  355. # used_weight to 0 instead, and Spoolman recomputes remaining from initial
  356. # minus used, so the spool jumped back to full (#2906).
  357. # `or 0.0` would collapse None and 0.0, which is the one distinction
  358. # _extract_extra_float exists to preserve; spell the absent case out.
  359. # Clamp the low end too: the write side already refuses a negative
  360. # baseline, and without the same rule here a negative value stored by hand
  361. # would be subtracted, inflating the displayed counter. min() below only
  362. # bounds the other end.
  363. stored = _extract_extra_float(extra, BAMBU_WEIGHT_USED_BASELINE_KEY)
  364. stored_baseline = 0.0 if stored is None else max(0.0, stored)
  365. remaining_raw = spool.get("remaining_weight")
  366. if remaining_raw is not None:
  367. remaining_weight: float = _safe_float(remaining_raw, 0.0)
  368. used_weight: float = max(0.0, float(label_weight) - remaining_weight)
  369. weight_used_baseline: float = max(0.0, used_weight - real_used_weight + stored_baseline)
  370. else:
  371. used_weight = real_used_weight
  372. weight_used_baseline = stored_baseline # already clamped to >= 0 above
  373. # Never let the displayed counter read negative. used_weight can fall below
  374. # the baseline after a reset without anyone touching it: the AMS sync
  375. # writes remaining_weight from the tray percentage, and Spoolman derives
  376. # used_weight from that. The counter then reads 0 until consumption climbs
  377. # past the baseline again. Internal mode behaves the same way, and it is
  378. # far better than before #2906, when the next sync undid the reset outright.
  379. weight_used_baseline = min(weight_used_baseline, used_weight)
  380. # Archived state – Spoolman uses a boolean ``archived`` field
  381. archived: bool = spool.get("archived", False)
  382. archived_at: str | None = None
  383. if archived:
  384. archived_at = spool.get("last_used") or spool.get("registered") or None
  385. created_at: str | None = spool.get("registered") or None
  386. # Spoolman has no `color_name` field on Filament — confirmed against the
  387. # FilamentUpdateParameters schema in 0.23.1: name/vendor_id/material/price/
  388. # density/diameter/weight/spool_weight/article_number/comment/extruder_temp/
  389. # bed_temp/color_hex/multi_color_hexes/multi_color_direction/external_id/
  390. # extra, no color_name (#1357). The previous attempt (b8e350c3) was
  391. # PATCHing a key Spoolman silently discards, which is why color_name
  392. # never actually persisted from the user's edits.
  393. #
  394. # We persist it ourselves under spool.extra.bambu_color_name (JSON-encoded
  395. # string, same pattern as bambu_slicer_filament). Read order:
  396. # 1. spool.extra.bambu_color_name (the canonical store)
  397. # 2. filament.color_name (forward-compat — picks up the value if a
  398. # future Spoolman release adds the field, or if an admin populated
  399. # it via a custom extra-field they registered themselves)
  400. # 3. subtype (synth fallback so the inventory list isn't a sea of
  401. # "Unknown color" entries on installs with neither field set)
  402. #
  403. # color_name_is_synthesized = True only when we fell back to subtype.
  404. # The edit form uses it to leave the input blank, so the user doesn't
  405. # round-trip the synth value back as if they had set it.
  406. extra_color_name = _extract_extra_str(extra, "bambu_color_name") or None
  407. stored_color_name = extra_color_name or (filament.get("color_name") or None)
  408. color_name: str | None = stored_color_name or subtype or None
  409. color_name_is_synthesized: bool = stored_color_name is None and color_name is not None
  410. nozzle_temp_raw = filament.get("settings_extruder_temp")
  411. nozzle_temp_min: int | None = _safe_int(nozzle_temp_raw, 0) or None
  412. return {
  413. "id": spool_id,
  414. "material": material,
  415. "subtype": subtype,
  416. "color_name": color_name,
  417. "color_name_is_synthesized": color_name_is_synthesized,
  418. "rgba": rgba,
  419. "extra_colors": extra_colors,
  420. "effect_type": None,
  421. "brand": vendor.get("name") or None,
  422. "label_weight": label_weight,
  423. "core_weight": _safe_int(spoolman_tare(spool)[0], 250),
  424. # True when the spool has no spool_weight of its own and core_weight is
  425. # the filament type's, the vendor's or the 250 g fallback. The spool form needs it
  426. # to copy a spool without dropping an own tare or stamping an
  427. # inherited one (#2908).
  428. "core_weight_is_inherited": spool.get("spool_weight") is None,
  429. "core_weight_catalog_id": None,
  430. "weight_used": used_weight,
  431. "weight_used_baseline": weight_used_baseline,
  432. "weight_locked": False,
  433. "last_scale_weight": None,
  434. "last_weighed_at": None,
  435. # BambuStudio slicer preset — Spoolman has no native field, so the
  436. # update endpoint persists these under bambu_slicer_filament[_name]
  437. # in the spool's extra dict. Values are JSON-encoded strings; an
  438. # empty string ("") means cleared. Falls back to Spoolman's
  439. # filament_name for slicer_filament_name when nothing is stored.
  440. "slicer_filament": (_extract_extra_str(extra, "bambu_slicer_filament") or None),
  441. "slicer_filament_name": (_extract_extra_str(extra, "bambu_slicer_filament_name") or (filament_name or None)),
  442. "nozzle_temp_min": nozzle_temp_min,
  443. "nozzle_temp_max": None,
  444. "note": spool.get("comment") or None,
  445. "added_full": None,
  446. "last_used": spool.get("last_used"),
  447. "last_dried_at": _extract_extra_str(extra, BAMBU_LAST_DRIED_AT_KEY) or None,
  448. "last_dried_temp": _last_dried_temp(extra),
  449. "last_dried_hours": _extract_extra_float(extra, BAMBU_LAST_DRIED_HOURS_KEY),
  450. # encode_time semantics differ: local records NFC write time; Spoolman first_used
  451. # records first print use — different events; using first_used as best available proxy.
  452. "encode_time": spool.get("first_used"),
  453. "tag_uid": tag_uid,
  454. "tray_uuid": tray_uuid,
  455. "data_origin": "spoolman",
  456. "tag_type": "spoolman",
  457. "archived_at": archived_at,
  458. "created_at": created_at,
  459. # Spoolman has no updated_at field; use registered timestamp as best available proxy
  460. "updated_at": created_at,
  461. # Spoolman's spool price is what the whole spool cost (#3194).
  462. "cost_per_kg": spoolman_cost_per_kg(spool),
  463. # Spoolman's filament.article_number maps 1:1 onto the internal
  464. # material number (#2870): both identify the purchasable product.
  465. # Trimmed for the same reason the schema validator trims the internal
  466. # one — the filter chip builds its options from trimmed values and
  467. # matches exactly, so a padded number would list and match nothing.
  468. "material_number": ((filament.get("article_number") or "").strip() or None),
  469. "storage_location": spool.get("location") or None,
  470. "location_id": None,
  471. "k_profiles": [],
  472. }