spoolman_tracking.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. """Spoolman per-filament usage tracking for active prints.
  2. Captures AMS tray state and G-code data at print start, then reports
  3. per-filament usage to the correct Spoolman spools at print completion.
  4. Supports accurate partial usage reporting for failed/cancelled prints.
  5. """
  6. import json
  7. import logging
  8. from sqlalchemy import delete, select
  9. from backend.app.core.config import settings as app_settings
  10. from backend.app.core.database import async_session
  11. from backend.app.services.spoolman import (
  12. SpoolmanClientError,
  13. SpoolmanNotFoundError,
  14. SpoolmanUnavailableError,
  15. get_spoolman_client,
  16. init_spoolman_client,
  17. )
  18. logger = logging.getLogger(__name__)
  19. # Zero UUID used by Bambu printers for empty/unset tray_uuid
  20. _ZERO_UUID = "00000000000000000000000000000000"
  21. _ZERO_TAG_UID = "0000000000000000"
  22. # Highest global tray id that names a real slot. 255 does not: it is
  23. # ``PrinterState.tray_now``'s initial value, what an unparseable reading falls
  24. # back to, and what the field reads while nothing is loaded. The external spool
  25. # reports 254 when it is actually in use, and ``bambu_mqtt`` applies the same
  26. # cut-off when it seeds the tray-change log. Treating 255 as a slot would put
  27. # ``(255, 1)`` into the "slots this print used" evidence and exclude every real
  28. # one -- silently disabling the very fallback this guard protects (#1820).
  29. #
  30. # Applied to ``tray_now`` only. A 255 in the print's mapping or its tray-change
  31. # log was written there by a print and is evidence, however odd; a 255 in
  32. # ``tray_now`` is the field at rest, which is the absence of evidence.
  33. _MAX_REAL_TRAY_ID = 254
  34. def _is_real_tray_id(value) -> bool:
  35. """True when ``value`` names a physical slot rather than "nothing loaded"."""
  36. return isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= _MAX_REAL_TRAY_ID
  37. def _is_non_zero_identifier(value: str) -> bool:
  38. """Return True when identifier is non-empty and not all zeros."""
  39. if not value:
  40. return False
  41. return set(value) != {"0"}
  42. def _to_fixed_hex(value: int, width: int) -> str:
  43. """Mirror frontend toFixedHex(): uppercase, zero-padded, fixed width."""
  44. safe = max(0, int(value))
  45. return format(safe, "X").zfill(width)[-width:]
  46. def _hash_serial_to_hex32(serial: str) -> str:
  47. """Mirror frontend hashSerialToHex32() exactly (32-bit FNV-1a)."""
  48. input_str = (serial or "").strip().upper()
  49. hash_value = 0x811C9DC5
  50. for char in input_str:
  51. hash_value ^= ord(char)
  52. hash_value = (hash_value * 0x01000193) & 0xFFFFFFFF
  53. return format(hash_value, "X").zfill(8)
  54. def _global_tray_id_to_ams_slot(global_tray_id: int) -> tuple[int, int]:
  55. """Convert global tray id to (ams_id, tray_id) tuple for fallback tag generation."""
  56. # External spool slots use IDs 254/255 and map to ams_id=255 tray_id=0/1.
  57. if global_tray_id >= 254:
  58. return 255, max(0, global_tray_id - 254)
  59. # AMS-HT units are addressed by ams_id directly and have a single tray.
  60. if global_tray_id >= 128:
  61. return global_tray_id, 0
  62. # Standard AMS units: four trays each.
  63. return global_tray_id // 4, global_tray_id % 4
  64. def _get_fallback_spool_tag(printer_serial: str, global_tray_id: int) -> str:
  65. """Mirror frontend getFallbackSpoolTag(serial, amsId, trayId) exactly."""
  66. if not printer_serial:
  67. return ""
  68. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  69. return get_fallback_spool_tag_for_slot(printer_serial, ams_id, tray_id)
  70. def get_fallback_spool_tag_for_slot(printer_serial: str, ams_id: int, tray_id: int) -> str:
  71. """Public helper matching frontend getFallbackSpoolTag(serial, amsId, trayId).
  72. Used by stale-tag cleanup (#1457) to detect Spoolman spools still holding
  73. this slot's deterministic fallback tag in extra.tag.
  74. """
  75. if not printer_serial:
  76. return ""
  77. return f"{_hash_serial_to_hex32(printer_serial)}{_to_fixed_hex(ams_id, 4)}{_to_fixed_hex(tray_id, 4)}"
  78. def _resolve_spool_tag(tray_info: dict, printer_serial: str = "", global_tray_id: int | None = None) -> str:
  79. """Get the best spool identifier from tray info (prefer tray_uuid over tag_uid).
  80. Returns empty string if no usable identifier is found.
  81. """
  82. tray_uuid = str(tray_info.get("tray_uuid", "") or "")
  83. tag_uid = str(tray_info.get("tag_uid", "") or "")
  84. if tray_uuid and tray_uuid != _ZERO_UUID and _is_non_zero_identifier(tray_uuid):
  85. return tray_uuid
  86. if tag_uid and tag_uid != _ZERO_TAG_UID and _is_non_zero_identifier(tag_uid):
  87. return tag_uid
  88. if global_tray_id is not None:
  89. return _get_fallback_spool_tag(printer_serial, global_tray_id)
  90. return ""
  91. async def _get_printer_serial(printer_id: int) -> str:
  92. """Get printer serial for deterministic fallback tag generation."""
  93. from backend.app.models.printer import Printer
  94. from backend.app.services.printer_manager import printer_manager
  95. printer_info = printer_manager.get_printer(printer_id)
  96. if printer_info and printer_info.serial_number:
  97. return printer_info.serial_number
  98. async with async_session() as db:
  99. result = await db.execute(select(Printer.serial_number).where(Printer.id == printer_id))
  100. serial_number = result.scalar_one_or_none()
  101. return serial_number or ""
  102. def _resolve_global_tray_id(slot_id: int, slot_to_tray: list | None, ams_trays: dict | None = None) -> int:
  103. """Map a 1-based slot_id to a global_tray_id using optional custom mapping.
  104. Custom mapping: slot_to_tray[slot_id - 1] is used when >= 0.
  105. A value of -1 in the custom mapping means the slicer routed this slot to
  106. the external spool. BambuStudio converts virtual tray IDs (254/255) to -1
  107. in the flat ams_mapping array before sending to the printer — see
  108. start_print() in bambu_mqtt.py which documents this convention. We mirror
  109. it here: when -1 is seen, look up the external spool's actual
  110. global_tray_id (254/255) in ams_trays rather than falling through to the
  111. position-based default (which would map slot_id=1 to the first AMS tray
  112. and credit an unrelated spool — see #1276, regression of #853).
  113. Position-based default: uses sorted ams_trays keys so external spools (ID 254/255)
  114. naturally follow standard AMS trays, matching the slicer's slot numbering.
  115. Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools).
  116. """
  117. if slot_to_tray and slot_id <= len(slot_to_tray):
  118. mapped_tray = slot_to_tray[slot_id - 1]
  119. if mapped_tray >= 0:
  120. return mapped_tray
  121. if mapped_tray == -1 and ams_trays:
  122. # -1 means external spool. 254 = VIRTUAL_TRAY_DEPUTY_ID (main on
  123. # single-nozzle, left/deputy on H2D dual-nozzle); 255 =
  124. # VIRTUAL_TRAY_MAIN_ID. Prefer 254 when both exist since that's
  125. # what single-nozzle printers report via tray_now.
  126. for ext_id in (254, 255):
  127. if ext_id in ams_trays:
  128. return ext_id
  129. # Position-based default: sort available tray IDs so external spools (254/255)
  130. # come after standard AMS trays, matching the slicer's slot assignment order.
  131. if ams_trays:
  132. sorted_tray_ids = sorted(ams_trays.keys())
  133. if slot_id <= len(sorted_tray_ids):
  134. return sorted_tray_ids[slot_id - 1]
  135. return slot_id - 1
  136. def _single_slot_tray_from_state(
  137. state,
  138. filament_usage: list[dict],
  139. tray_now_at_start: int | None = None,
  140. ) -> tuple[int, int] | None:
  141. """The tray a single-slot print actually drew from, read off the printer.
  142. A1, A1 mini, P1S and P2S publish no ``mapping`` field and drop the MQTT
  143. connection when we subscribe to their request topic, so neither of the
  144. other two fallbacks can answer for them. What they do report is which tray
  145. the extruder is fed from, and for a print that uses exactly one filament
  146. slot that is the same question: the one slot came from the one tray.
  147. The ladder mirrors ``usage_tracker.on_print_complete`` step 5, which has
  148. consulted these same fields since it started resolving mappings at
  149. completion. Spoolman users were the only ones not getting them (#2953).
  150. Gated on exactly one slot with usage, like the internal writer: on a
  151. multi-colour print every filament change moves ``tray_now``, so a single
  152. tray reading says nothing about which slot it belongs to.
  153. More than one tray-change entry means the print switched trays mid-run
  154. (AMS backup on runout, #957). ``report_usage`` splits those per segment
  155. and must not be handed a single-tray mapping instead, so this declines.
  156. Returns ``(slot_id, global_tray_id)``, or None when the printer offered no
  157. usable reading and the positional default stands.
  158. """
  159. nonzero = [u for u in filament_usage or [] if u.get("used_g", 0) > 0]
  160. if len(nonzero) != 1:
  161. return None
  162. slot_id = nonzero[0].get("slot_id", 0)
  163. if slot_id <= 0:
  164. return None
  165. changes = list(getattr(state, "tray_change_log", None) or [])
  166. if len(changes) > 1:
  167. return None
  168. if len(changes) == 1:
  169. entry = changes[0]
  170. if isinstance(entry, (tuple, list)) and entry and _is_real_tray_id(entry[0]):
  171. # Strongest evidence there is: the printer announced this switch
  172. # while the job was running, so it describes this print and no
  173. # other. On the reporter's A1 it read (3, 0) -- tray 3 at layer 0
  174. # -- while the positional default was charging tray 0.
  175. return slot_id, entry[0]
  176. # No mid-print switch recorded. Fall back to the standing tray readings,
  177. # newest evidence first. ``tray_now`` is 255 both at rest and while
  178. # nothing is loaded, which is why _MAX_REAL_TRAY_ID excludes it; A1
  179. # firmware parks there the moment a print ends, leaving last_loaded_tray
  180. # as the only survivor.
  181. for candidate in (
  182. tray_now_at_start,
  183. getattr(state, "tray_now", None),
  184. getattr(state, "last_loaded_tray", None),
  185. ):
  186. if _is_real_tray_id(candidate):
  187. return slot_id, candidate
  188. return None
  189. def _resolve_slot_to_tray_fallback(
  190. printer_id: int,
  191. filament_usage: list[dict],
  192. tray_now_at_start: int | None = None,
  193. ) -> tuple[list[int] | None, str]:
  194. """Recover a slot-to-tray mapping at completion when print start captured none.
  195. ``store_print_data`` can only learn the mapping from two sources: the
  196. ``ams_mapping`` Bambuddy intercepts on the printer's local request topic, and
  197. a queue item's stored mapping. Neither exists for a print dispatched from
  198. Bambu Studio while the printer is cloud-bound — the command travels through
  199. Bambu's broker and never appears on the local topic we subscribe to. With
  200. ``slot_to_tray`` left NULL, ``_resolve_global_tray_id`` guesses by position:
  201. slicer slot 1 to the first loaded tray, slot 2 to the second, and so on. An
  202. AMS that isn't loaded in slicer order then charges every slot to the wrong
  203. spool, and the archive's filament is rewritten to match, so the print
  204. silently changes colour when it finishes (#2768).
  205. The printer knows the real answer. Its ``mapping`` field carries the actual
  206. slot-to-tray assignment for the running job, and for the models that never
  207. publish it (A1, P1S, P2S) the 3MF's per-slot colours can be matched against
  208. the loaded trays instead. Failing both, a print that used a single filament
  209. slot can be pinned to the tray the printer reported feeding from
  210. (``_single_slot_tray_from_state``).
  211. The built-in inventory writer has consulted all three for as long as it has
  212. resolved mappings at completion. The first version of this function offered
  213. only the first two, which left A1-class printers -- no ``mapping`` field, no
  214. request topic -- with nothing but the colour match, and that needs the
  215. slicer's filament colour to equal the tray's exactly. A generic black
  216. profile against a tray set to #111111 does not match, and the print is
  217. charged to whichever spool happens to sit in the first tray (#2953).
  218. Deliberately at completion rather than inside ``store_print_data``: the
  219. printer keeps publishing ``mapping`` long after a job ends — it is still in
  220. the status payload while the printer sits idle — so reading it at print start
  221. risks stamping the *previous* job's mapping onto this one before the printer
  222. has pushed the update. At completion the field unambiguously describes the
  223. job that just ran.
  224. Args:
  225. printer_id: Printer whose live state is consulted.
  226. filament_usage: The 3MF's per-slot estimates. The colour match reads
  227. ``slot_id``/``color``; the tray-state fallback reads
  228. ``slot_id``/``used_g``.
  229. tray_now_at_start: The tray the printer was feeding from when the print
  230. began, as captured by ``store_print_data``. Only consulted by the
  231. tray-state fallback.
  232. Returns:
  233. ``(mapping, source)``, or ``(None, "none")`` when no fallback produced
  234. anything and the positional default stands.
  235. """
  236. from backend.app.services.printer_manager import printer_manager
  237. from backend.app.services.usage_tracker import _decode_mqtt_mapping, _match_slots_by_color
  238. state = printer_manager.get_status(printer_id)
  239. raw_data = getattr(state, "raw_data", None) if state else None
  240. # Both of the first two fallbacks read the status payload; the third reads
  241. # fields ``bambu_mqtt`` maintains on the state object itself, so an empty
  242. # payload must not short-circuit past it.
  243. if raw_data:
  244. decoded = _decode_mqtt_mapping(raw_data.get("mapping"))
  245. if decoded:
  246. return decoded, "mqtt"
  247. matched = _match_slots_by_color(filament_usage, raw_data.get("ams"))
  248. if matched:
  249. return matched, "color_match"
  250. single = _single_slot_tray_from_state(state, filament_usage, tray_now_at_start)
  251. if single is not None:
  252. slot_id, global_tray_id = single
  253. # Only the one slot is claimed. The -1 padding is the array's existing
  254. # "not an AMS tray" value, and the slots carrying it consumed nothing,
  255. # so no caller resolves them: ``_report_spool_usage_for_slots`` skips
  256. # zero-gram slots before resolving, ``_print_used_tray_keys`` skips
  257. # negatives, and report_usage's handled-set skips them too.
  258. mapping = [-1] * slot_id
  259. mapping[slot_id - 1] = global_tray_id
  260. return mapping, "tray_state"
  261. return None, "none"
  262. def build_ams_tray_lookup(raw_data: dict) -> dict[int, dict]:
  263. """Build lookup of global_tray_id -> tray info from printer state.
  264. Returns: {0: {"tray_uuid": "...", "tag_uid": "...", "tray_type": "..."}, ...}
  265. """
  266. lookup = {}
  267. ams_data = raw_data.get("ams", [])
  268. for ams_unit in ams_data:
  269. ams_id = int(ams_unit.get("id", 0))
  270. for tray in ams_unit.get("tray", []):
  271. tray_id = int(tray.get("id", 0))
  272. # AMS-HT units have IDs starting at 128 with a single tray
  273. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  274. lookup[global_tray_id] = {
  275. "tray_uuid": tray.get("tray_uuid", ""),
  276. "tag_uid": tray.get("tag_uid", ""),
  277. "tray_type": tray.get("tray_type", ""),
  278. }
  279. # External spool(s) (vt_tray is a list, global_tray_id from each entry's "id")
  280. for vt in raw_data.get("vt_tray") or []:
  281. if vt.get("tray_type"):
  282. tray_id = int(vt.get("id", 254))
  283. lookup[tray_id] = {
  284. "tray_uuid": vt.get("tray_uuid", ""),
  285. "tag_uid": vt.get("tag_uid", ""),
  286. "tray_type": vt.get("tray_type", ""),
  287. }
  288. return lookup
  289. def _snapshot_tray_remain(raw_data: dict, skipped_out: list[str] | None = None) -> dict[str, dict]:
  290. """Capture per-slot ``remain%`` + ``tray_uuid`` at print start so the
  291. completion path can compute a remain-delta when 3MF data doesn't cover
  292. the slot (or there's no 3MF at all — #1820).
  293. Returns ``{"<ams_id>-<tray_id>": {"remain": int, "tray_uuid": str}}``.
  294. Only slots whose ``remain`` is a valid 0..100 int are included; invalid
  295. values mean the AMS hasn't read the spool yet and a delta would be
  296. meaningless. Mirrors the gate in
  297. ``usage_tracker.on_print_start:309``.
  298. A rejected slot is appended to *skipped_out* when one is supplied, so the
  299. caller can say which slots this print will not be able to charge. That is
  300. not hypothetical: an AMS reports a negative ``remain`` on a nearly empty
  301. spool, so the gate can drop the one slot that is about to do the printing
  302. (#1820).
  303. """
  304. snapshot: dict[str, dict] = {}
  305. ams_raw = raw_data.get("ams", [])
  306. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  307. for ams_unit in ams_data:
  308. if not isinstance(ams_unit, dict):
  309. continue
  310. ams_id = int(ams_unit.get("id", 0))
  311. for tray in ams_unit.get("tray", []):
  312. if not isinstance(tray, dict):
  313. continue
  314. tray_id = int(tray.get("id", 0))
  315. remain = tray.get("remain", -1)
  316. if isinstance(remain, int) and 0 <= remain <= 100:
  317. snapshot[f"{ams_id}-{tray_id}"] = {
  318. "remain": remain,
  319. "tray_uuid": tray.get("tray_uuid", "") or "",
  320. }
  321. elif skipped_out is not None:
  322. skipped_out.append(f"AMS{ams_id}-T{tray_id}(remain={remain})")
  323. vt_tray_raw = raw_data.get("vt_tray") or []
  324. if isinstance(vt_tray_raw, dict):
  325. vt_tray_raw = [vt_tray_raw]
  326. for vt in vt_tray_raw:
  327. if not isinstance(vt, dict):
  328. continue
  329. vt_id = int(vt.get("id", 254))
  330. # 254 → (255, 0), 255 → (255, 1) — matches usage_tracker's encoding.
  331. vt_tray_id = vt_id - 254
  332. remain = vt.get("remain", -1)
  333. if isinstance(remain, int) and 0 <= remain <= 100:
  334. snapshot[f"255-{vt_tray_id}"] = {
  335. "remain": remain,
  336. "tray_uuid": vt.get("tray_uuid", "") or "",
  337. }
  338. elif skipped_out is not None:
  339. skipped_out.append(f"VT{vt_id}(remain={remain})")
  340. return snapshot
  341. async def store_print_data(
  342. printer_id: int,
  343. archive_id: int,
  344. file_path: str,
  345. db,
  346. printer_manager,
  347. ams_mapping: list[int] | None = None,
  348. plate_id: int | None = None,
  349. ):
  350. """Store Spoolman tracking data at print start (persisted to database).
  351. Per-print tracking is the primary weight-update path for Spoolman, mirroring
  352. how the internal Filament Inventory works. The legacy AMS-remain%-based sync
  353. is no longer used as a weight writer (#1119), so this runs whenever Spoolman
  354. is enabled regardless of the deprecated `spoolman_disable_weight_sync` flag.
  355. ``plate_id``, when set, scopes the 3MF filament extract to a single plate so
  356. queue / direct-Print dispatch of plate N of a multi-plate file doesn't
  357. attribute every plate's filament to the printed spool (#1697). When unset,
  358. the queue item's plate_id (if any) is used; otherwise the whole-file sum is
  359. extracted, which is correct for direct prints that target the first/only
  360. plate of a single-plate file.
  361. """
  362. from backend.app.api.routes.settings import get_setting
  363. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  364. from backend.app.models.print_queue import PrintQueueItem
  365. from backend.app.utils.threemf_tools import (
  366. extract_filament_properties_from_3mf,
  367. extract_filament_usage_from_3mf,
  368. extract_layer_filament_usage_from_3mf,
  369. )
  370. # Check if Spoolman is enabled
  371. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  372. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  373. return
  374. # Get current AMS tray state up front — needed both for the 3MF path's
  375. # ams_trays field and for the remain%-delta snapshot (#1820 fallback for
  376. # no-3MF "Untitled" prints, mirroring usage_tracker.on_print_start).
  377. state = printer_manager.get_status(printer_id)
  378. ams_trays: dict[int, dict] = {}
  379. tray_remain_start: dict[str, dict] = {}
  380. if state and state.raw_data:
  381. ams_trays = build_ams_tray_lookup(state.raw_data)
  382. skipped_slots: list[str] = []
  383. tray_remain_start = _snapshot_tray_remain(state.raw_data, skipped_slots)
  384. if skipped_slots:
  385. # Matches what usage_tracker.on_print_start reports for the
  386. # internal inventory, so both backends name the slots that this
  387. # print will not be able to charge at AMS granularity.
  388. logger.info(
  389. "[SPOOLMAN] Printer %s: slots with no usable remain%% at print start: %s",
  390. printer_id,
  391. ", ".join(skipped_slots),
  392. )
  393. # Try to read per-slot filament estimates from the 3MF. Two paths can
  394. # leave ``filament_usage`` empty: (1) fallback archive (no .gcode.3mf
  395. # was downloadable from the printer — "Untitled" prints, see #1820),
  396. # (2) 3MF present but slice_info missing per-filament estimates.
  397. # Both fall through to the remain%-delta path at completion.
  398. filament_usage: list | None = None
  399. layer_usage_json: dict | None = None
  400. filament_properties: dict | None = None
  401. full_path = (
  402. app_settings.base_dir / file_path
  403. ) # SEC-PATH-OK: file_path is archive.file_path / library_file.file_path — DB-stored, internally generated
  404. threemf_available = bool(file_path) and full_path.exists()
  405. queue_item = None
  406. if threemf_available:
  407. # Resolve the queue item once — used both for the plate-scoped 3MF parsing
  408. # fallback (#1697: multi-plate file dispatched for one plate must only count
  409. # that plate's filament) and for the ams_mapping fallback below.
  410. queue_result = await db.execute(
  411. select(PrintQueueItem)
  412. .where(PrintQueueItem.archive_id == archive_id)
  413. .where(PrintQueueItem.status == "printing")
  414. )
  415. queue_item = queue_result.scalar_one_or_none()
  416. # Caller-supplied plate_id wins (direct-Print path); fall back to the queue
  417. # item's plate_id (queue dispatch path).
  418. effective_plate_id = (
  419. plate_id if plate_id is not None else (queue_item.plate_id if queue_item is not None else None)
  420. )
  421. filament_usage = extract_filament_usage_from_3mf(full_path, effective_plate_id) or None
  422. layer_usage = extract_layer_filament_usage_from_3mf(full_path, effective_plate_id)
  423. if layer_usage:
  424. # Convert int keys to string for JSON serialization
  425. layer_usage_json = {str(k): v for k, v in layer_usage.items()}
  426. logger.debug("[SPOOLMAN] Parsed %s layers from G-code", len(layer_usage))
  427. filament_properties = extract_filament_properties_from_3mf(full_path)
  428. else:
  429. # No 3MF on disk — common for "Untitled" prints whose .gcode.3mf
  430. # was never on the printer's FTP. Logged at debug since the
  431. # fallback path below picks up the slack when remain% is available.
  432. logger.debug("[SPOOLMAN] 3MF file not available: %s", full_path)
  433. # If neither path has anything useful, there's nothing to track.
  434. if not filament_usage and not tray_remain_start:
  435. if threemf_available:
  436. logger.debug("[SPOOLMAN] No filament usage data in 3MF for archive %s", archive_id)
  437. return
  438. # Prefer the explicit mapping captured from the print command, then fall back
  439. # to any queue mapping stored for scheduled/reprint jobs.
  440. slot_to_tray = ams_mapping if ams_mapping is not None else None
  441. mapping_source = "print_cmd" if slot_to_tray else None
  442. if not slot_to_tray and queue_item and queue_item.ams_mapping:
  443. try:
  444. slot_to_tray = json.loads(queue_item.ams_mapping)
  445. mapping_source = "queue"
  446. except json.JSONDecodeError:
  447. pass # Ignore malformed AMS mapping; fall back to default slot assignment
  448. # Delete any existing row for this printer/archive (shouldn't exist, but just in case)
  449. await db.execute(
  450. delete(ActivePrintSpoolman)
  451. .where(ActivePrintSpoolman.printer_id == printer_id)
  452. .where(ActivePrintSpoolman.archive_id == archive_id)
  453. )
  454. # Insert new tracking data. ``filament_usage`` may be None for the
  455. # no-3MF case; report_usage falls back to ``tray_remain_start``.
  456. tracking = ActivePrintSpoolman(
  457. printer_id=printer_id,
  458. archive_id=archive_id,
  459. filament_usage=filament_usage,
  460. ams_trays=ams_trays,
  461. slot_to_tray=slot_to_tray,
  462. layer_usage=layer_usage_json,
  463. filament_properties=filament_properties,
  464. tray_remain_start=tray_remain_start or None,
  465. # Which slot the printer was drawing from when this print began. For a
  466. # print with no ams_mapping -- one started from the printer's own
  467. # screen, which is the case this whole fallback exists for -- it is the
  468. # only evidence of which slot the print used (#1820).
  469. tray_now_at_start=getattr(state, "tray_now", None) if state else None,
  470. )
  471. db.add(tracking)
  472. await db.commit()
  473. logger.info(
  474. "[SPOOLMAN] Stored tracking data for print: printer=%s, archive=%s (3mf=%s, remain_snapshot=%d slot(s))",
  475. printer_id,
  476. archive_id,
  477. "yes" if filament_usage else "no",
  478. len(tray_remain_start),
  479. )
  480. logger.debug("[SPOOLMAN] Filament usage: %s", filament_usage)
  481. logger.debug("[SPOOLMAN] AMS trays: %s", list(ams_trays.keys()))
  482. # Logged at info even when there is no mapping: "source: none" here is the
  483. # signal that completion will have to fall back, which is the single most
  484. # useful line in the log when a print is charged to the wrong spool (#2768).
  485. logger.info(
  486. "[SPOOLMAN] Print start: archive %s slot_to_tray=%s (source: %s)",
  487. archive_id,
  488. slot_to_tray,
  489. mapping_source or "none",
  490. )
  491. if layer_usage_json:
  492. logger.debug("[SPOOLMAN] Layer usage data available for partial tracking")
  493. async def cleanup_tracking(
  494. printer_id: int,
  495. archive_id: int,
  496. db,
  497. last_layer_num: int | None = None,
  498. last_progress: int | None = None,
  499. ):
  500. """Report partial usage and clean up Spoolman tracking data for failed/aborted prints."""
  501. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  502. # Get tracking data first (needed for partial usage reporting)
  503. result = await db.execute(
  504. select(ActivePrintSpoolman)
  505. .where(ActivePrintSpoolman.printer_id == printer_id)
  506. .where(ActivePrintSpoolman.archive_id == archive_id)
  507. )
  508. tracking = result.scalar_one_or_none()
  509. if not tracking:
  510. logger.debug("[SPOOLMAN] No tracking data to clean up for printer=%s, archive=%s", printer_id, archive_id)
  511. return
  512. # Try to report partial usage before cleanup
  513. try:
  514. await _report_partial_usage(
  515. printer_id,
  516. tracking,
  517. last_layer_num=last_layer_num,
  518. last_progress=last_progress,
  519. )
  520. except Exception as e:
  521. logger.warning("[SPOOLMAN] Partial usage report failed: %s", e)
  522. # Delete tracking data
  523. await db.execute(
  524. delete(ActivePrintSpoolman)
  525. .where(ActivePrintSpoolman.printer_id == printer_id)
  526. .where(ActivePrintSpoolman.archive_id == archive_id)
  527. )
  528. await db.commit()
  529. logger.debug("[SPOOLMAN] Cleaned up tracking data for printer=%s, archive=%s", printer_id, archive_id)
  530. async def _get_spoolman_client_with_fallback():
  531. """Get Spoolman client, initializing from settings if needed.
  532. Returns (client, is_healthy) tuple. Client may be None.
  533. """
  534. client = await get_spoolman_client()
  535. if not client:
  536. async with async_session() as db:
  537. from backend.app.api.routes.settings import get_setting
  538. spoolman_url = await get_setting(db, "spoolman_url")
  539. if spoolman_url:
  540. try:
  541. client = await init_spoolman_client(spoolman_url)
  542. except ValueError as exc:
  543. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  544. return None
  545. if not client:
  546. return None
  547. if not await client.health_check():
  548. logger.warning("Spoolman health check failed; skipping usage reporting")
  549. return None
  550. return client
  551. async def _resolve_spool_id_via_slot_assignment(printer_id: int, ams_id: int, tray_id: int) -> int | None:
  552. """Look up the Spoolman spool ID locally bound to (printer, ams, tray).
  553. Fallback path for #1459: when a tag-less spool was assigned via the
  554. Bambuddy UI, the user's deterministic fallback tag is intentionally NOT
  555. written to Spoolman's extra.tag (kept clean per #1457), so
  556. find_spool_by_tag misses. The local spoolman_slot_assignments table is
  557. the authoritative binding for those spools.
  558. """
  559. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  560. async with async_session() as db:
  561. result = await db.execute(
  562. select(SpoolmanSlotAssignment.spoolman_spool_id).where(
  563. SpoolmanSlotAssignment.printer_id == printer_id,
  564. SpoolmanSlotAssignment.ams_id == ams_id,
  565. SpoolmanSlotAssignment.tray_id == tray_id,
  566. )
  567. )
  568. return result.scalar_one_or_none()
  569. async def _report_spool_usage_for_slots(
  570. client,
  571. filament_usage_items: list[tuple[int, float]],
  572. ams_trays: dict[int, dict],
  573. slot_to_tray: list | None,
  574. method_label: str,
  575. printer_serial: str = "",
  576. printer_id: int | None = None,
  577. slot_colors_out: dict[int, str] | None = None,
  578. slot_materials_out: dict[int, str] | None = None,
  579. ) -> int:
  580. """Report usage to Spoolman for a list of (slot_id, grams) pairs.
  581. Resolution order per slot: (1) Spoolman extra.tag match against the
  582. tray's RFID or deterministic fallback tag, (2) #1459 fallback —
  583. local spoolman_slot_assignments table keyed by (printer_id, ams_id,
  584. tray_id). Without (2), tag-less spools assigned via the Bambuddy UI
  585. never get their weight decremented because their extra.tag is empty
  586. on the Spoolman side.
  587. When ``slot_colors_out`` is provided it is populated with
  588. ``{slot_id: color_hex}`` for every resolved spool — used by
  589. :func:`report_usage` to stamp the archive's filament colour from the
  590. Spoolman spool rather than the slicer's 3MF value (#1494).
  591. Returns number of spools successfully updated.
  592. """
  593. spools_updated = 0
  594. for slot_id, grams_used in filament_usage_items:
  595. if grams_used <= 0:
  596. continue
  597. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  598. tray_info = ams_trays.get(global_tray_id)
  599. if not tray_info:
  600. logger.debug("[SPOOLMAN] Slot %s: no tray at global_tray_id %s", slot_id, global_tray_id)
  601. continue
  602. is_external = global_tray_id >= 254
  603. tray_type = tray_info.get("tray_type", "")
  604. logger.debug(
  605. "[SPOOLMAN] Slot %s resolved to global_tray_id %s (tray_type=%s, external=%s)",
  606. slot_id,
  607. global_tray_id,
  608. tray_type or "unknown",
  609. is_external,
  610. )
  611. spool_id_to_use: int | None = None
  612. resolution_path = ""
  613. # color_hex + material of the resolved spool's filament, for the #1494
  614. # archive colour rewrite and the #2563 type rewrite. The tag path
  615. # already has the full spool object; the slot-assignment path only
  616. # yields an id and is fetched below.
  617. spool_color_hex: str | None = None
  618. spool_material: str | None = None
  619. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  620. if spool_tag:
  621. spool = await client.find_spool_by_tag(spool_tag)
  622. if spool:
  623. spool_id_to_use = spool["id"]
  624. resolution_path = "tag"
  625. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  626. spool_material = (spool.get("filament") or {}).get("material")
  627. if spool_id_to_use is None and printer_id is not None:
  628. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  629. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  630. if spool_id_to_use is not None:
  631. resolution_path = "slot-assignment"
  632. if spool_id_to_use is None:
  633. logger.debug(
  634. "[SPOOLMAN] Slot %s: no spool resolved (tag=%s, no slot-assignment)",
  635. slot_id,
  636. spool_tag[:16] if spool_tag else "none",
  637. )
  638. continue
  639. # Record the spool's filament colour + material for the archive
  640. # rewrites (#1494, #2563). The slot-assignment path resolved only an
  641. # id, so fetch the spool once for whichever value is still missing.
  642. # Strictly best-effort: a fetch failure must never abort the weight
  643. # reporting for the remaining slots, so the catch is broad.
  644. if slot_colors_out is not None or slot_materials_out is not None:
  645. need_color = slot_colors_out is not None and spool_color_hex is None
  646. need_material = slot_materials_out is not None and spool_material is None
  647. if need_color or need_material:
  648. try:
  649. _fil = (await client.get_spool(spool_id_to_use)).get("filament") or {}
  650. if need_color:
  651. spool_color_hex = _fil.get("color_hex")
  652. if need_material:
  653. spool_material = _fil.get("material")
  654. except Exception as exc: # noqa: BLE001 — colour/material are non-critical
  655. logger.debug("[SPOOLMAN] Slot %s: could not fetch spool filament: %s", slot_id, exc)
  656. if slot_colors_out is not None and spool_color_hex:
  657. slot_colors_out[slot_id] = spool_color_hex
  658. if slot_materials_out is not None and spool_material:
  659. slot_materials_out[slot_id] = spool_material
  660. try:
  661. await client.use_spool(spool_id_to_use, grams_used)
  662. logger.info(
  663. "[SPOOLMAN] %s: slot %s: %sg -> spool %s (via %s)",
  664. method_label,
  665. slot_id,
  666. grams_used,
  667. spool_id_to_use,
  668. resolution_path,
  669. )
  670. spools_updated += 1
  671. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  672. logger.warning("[SPOOLMAN] Failed to record usage for spool %s: %s", spool_id_to_use, exc)
  673. return spools_updated
  674. async def _report_spool_usage_split_by_tray_changes(
  675. client,
  676. filament_usage: list[dict],
  677. tray_changes: list[tuple[int, int]],
  678. ams_trays: dict[int, dict],
  679. layer_usage: dict[int, dict[int, float]] | None,
  680. filament_properties: dict | None,
  681. total_layers: int,
  682. last_layer_num: int,
  683. method_label: str,
  684. printer_serial: str,
  685. printer_id: int,
  686. slot_colors_out: dict[int, str] | None = None,
  687. slot_materials_out: dict[int, str] | None = None,
  688. ) -> tuple[int, set[int]]:
  689. """Split each slot's grams across ``tray_changes`` and charge per-segment.
  690. Mirrors ``usage_tracker`` Path 1's tray-switch branch so Spoolman and
  691. the internal Spool inventory attribute mid-print AMS-backup switches
  692. identically (#1793 — reporter's origin spool was over-charged the
  693. whole print because this path didn't exist). ``compute_tray_split_grams``
  694. holds the shared segment-math; this function wraps the per-segment
  695. spool resolution + ``use_spool`` sink for the Spoolman side.
  696. Returns ``(spools_updated, handled_global_tray_ids)`` — the caller
  697. passes ``handled_global_tray_ids`` into the remain-delta fallback so
  698. a tray attributed here is not double-charged there.
  699. """
  700. from backend.app.utils.tray_split import compute_tray_split_grams
  701. spools_updated = 0
  702. handled_global_tray_ids: set[int] = set()
  703. for usage in filament_usage:
  704. slot_id = usage.get("slot_id", 0)
  705. total_weight = usage.get("used_g", 0)
  706. if total_weight <= 0 or slot_id <= 0:
  707. continue
  708. props = (filament_properties or {}).get(str(slot_id)) or (filament_properties or {}).get(slot_id) or {}
  709. segments = compute_tray_split_grams(
  710. tray_changes=tray_changes,
  711. total_weight=float(total_weight),
  712. slot_id=slot_id,
  713. layer_usage=layer_usage,
  714. density=float(props.get("density", 1.24)),
  715. diameter=float(props.get("diameter", 1.75)),
  716. total_layers=total_layers,
  717. last_layer_num=last_layer_num,
  718. )
  719. for seg_idx, tray_global, segment_grams in segments:
  720. if segment_grams <= 0:
  721. continue
  722. # Mark this tray as handled BEFORE the resolution attempt so
  723. # remain-delta doesn't double-charge it, even if we fail to
  724. # find a spool below. Matches usage_tracker behaviour: the
  725. # tray was physically fed from during this print, whether or
  726. # not Spoolman happens to have a matching row.
  727. handled_global_tray_ids.add(tray_global)
  728. tray_info = ams_trays.get(tray_global) or {}
  729. spool_id_to_use: int | None = None
  730. resolution_path = ""
  731. spool_color_hex: str | None = None
  732. spool_material: str | None = None
  733. spool_tag = _resolve_spool_tag(tray_info, printer_serial, tray_global) if tray_info else ""
  734. if spool_tag:
  735. spool = await client.find_spool_by_tag(spool_tag)
  736. if spool:
  737. spool_id_to_use = spool["id"]
  738. resolution_path = "tag"
  739. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  740. spool_material = (spool.get("filament") or {}).get("material")
  741. if spool_id_to_use is None:
  742. seg_ams_id, seg_tray_id = _global_tray_id_to_ams_slot(tray_global)
  743. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, seg_ams_id, seg_tray_id)
  744. if spool_id_to_use is not None:
  745. resolution_path = "slot-assignment"
  746. if spool_id_to_use is None:
  747. logger.info(
  748. "[SPOOLMAN] Split slot %s seg %s tray=%d: no spool resolved — %.2fg lost from split accounting",
  749. slot_id,
  750. seg_idx,
  751. tray_global,
  752. segment_grams,
  753. )
  754. continue
  755. # Colour (#1494) + material (#2563) rewrite — first segment for a
  756. # slot wins. The UI displays a single colour/type per slot, so
  757. # later segments on the same slot don't overwrite (a backup swap
  758. # can differ but the archive card stays consistent with the origin).
  759. need_color = slot_colors_out is not None and slot_id not in slot_colors_out and spool_color_hex is None
  760. need_material = (
  761. slot_materials_out is not None and slot_id not in slot_materials_out and spool_material is None
  762. )
  763. if need_color or need_material:
  764. try:
  765. _fil = (await client.get_spool(spool_id_to_use)).get("filament") or {}
  766. if need_color:
  767. spool_color_hex = _fil.get("color_hex")
  768. if need_material:
  769. spool_material = _fil.get("material")
  770. except Exception as exc: # noqa: BLE001 — colour/material are non-critical
  771. logger.debug("[SPOOLMAN] Split slot %s: could not fetch spool filament: %s", slot_id, exc)
  772. if slot_colors_out is not None and slot_id not in slot_colors_out and spool_color_hex:
  773. slot_colors_out[slot_id] = spool_color_hex
  774. if slot_materials_out is not None and slot_id not in slot_materials_out and spool_material:
  775. slot_materials_out[slot_id] = spool_material
  776. try:
  777. await client.use_spool(spool_id_to_use, round(segment_grams, 2))
  778. logger.info(
  779. "[SPOOLMAN] %s: slot %s seg %s tray=%d: %.2fg -> spool %s (via %s)",
  780. method_label,
  781. slot_id,
  782. seg_idx,
  783. tray_global,
  784. segment_grams,
  785. spool_id_to_use,
  786. resolution_path,
  787. )
  788. spools_updated += 1
  789. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  790. logger.warning(
  791. "[SPOOLMAN] Split slot %s seg %s: failed to record usage for spool %s: %s",
  792. slot_id,
  793. seg_idx,
  794. spool_id_to_use,
  795. exc,
  796. )
  797. return spools_updated, handled_global_tray_ids
  798. async def _report_partial_usage(
  799. printer_id: int,
  800. tracking,
  801. last_layer_num: int | None = None,
  802. last_progress: int | None = None,
  803. ):
  804. """Report partial filament usage based on actual G-code layer data.
  805. Uses per-layer cumulative extrusion from G-code parsing for accurate
  806. multi-material tracking. Falls back to linear interpolation if G-code
  807. data is unavailable.
  808. """
  809. from backend.app.services.printer_manager import printer_manager
  810. from backend.app.utils.threemf_tools import get_cumulative_usage_at_layer, mm_to_grams
  811. async with async_session() as db:
  812. from backend.app.api.routes.settings import get_setting
  813. # Check if partial usage reporting is enabled (default: true)
  814. report_partial = await get_setting(db, "spoolman_report_partial_usage")
  815. if report_partial and report_partial.lower() == "false":
  816. logger.debug("[SPOOLMAN] Partial usage reporting disabled by setting")
  817. return
  818. # Check if Spoolman is enabled
  819. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  820. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  821. return
  822. # Get current printer state for layer progress.
  823. # On failed/aborted prints the firmware may already reset to IDLE with layer=0,
  824. # so we fall back to completion-time hints captured from MQTT.
  825. state = printer_manager.get_status(printer_id)
  826. current_layer = state.layer_num if state else None
  827. total_layers = state.total_layers if state else None
  828. if (not current_layer or current_layer <= 0) and last_layer_num and last_layer_num > 0:
  829. current_layer = last_layer_num
  830. logger.debug("[SPOOLMAN] Using captured last_layer_num=%s for partial usage", current_layer)
  831. progress_ratio_from_event = None
  832. if last_progress is not None:
  833. try:
  834. progress_ratio_from_event = min(max(float(last_progress), 0.0), 100.0) / 100.0
  835. except (TypeError, ValueError):
  836. progress_ratio_from_event = None
  837. if (not current_layer or current_layer <= 0) and progress_ratio_from_event and total_layers and total_layers > 0:
  838. current_layer = max(1, int(round(total_layers * progress_ratio_from_event)))
  839. logger.debug(
  840. "[SPOOLMAN] Estimated layer from last_progress=%s%% and total_layers=%s -> %s",
  841. last_progress,
  842. total_layers,
  843. current_layer,
  844. )
  845. if not current_layer or current_layer <= 0:
  846. logger.debug(
  847. "[SPOOLMAN] No progress to report (layer 0/unknown, last_layer_num=%s, last_progress=%s)",
  848. last_layer_num,
  849. last_progress,
  850. )
  851. return
  852. logger.info("[SPOOLMAN] Reporting partial usage at layer %s/%s", current_layer, total_layers or "?")
  853. # Get tracking data
  854. layer_usage = tracking.layer_usage
  855. filament_properties = tracking.filament_properties or {}
  856. filament_usage = tracking.filament_usage or []
  857. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  858. slot_to_tray = tracking.slot_to_tray
  859. tray_remain_start = tracking.tray_remain_start or {}
  860. printer_serial = await _get_printer_serial(printer_id)
  861. client = await _get_spoolman_client_with_fallback()
  862. if not client:
  863. logger.warning("[SPOOLMAN] Not reachable for partial usage reporting")
  864. return
  865. # No-3MF aborted print (#1820 mirror of the completion path): nothing in
  866. # filament_usage or layer_usage to base partial estimates on, but the
  867. # remain%-delta snapshot we captured at start still describes consumption
  868. # up to the abort moment. Write it the same way report_usage's fallback
  869. # does, then return — there's no 3MF-derived partial to layer on top.
  870. # ``state`` was already fetched at the top of the function for current_layer.
  871. if not filament_usage and not layer_usage and tray_remain_start:
  872. current_lookup = _snapshot_tray_remain(state.raw_data) if state and state.raw_data else {}
  873. await _report_remain_delta_for_slots(
  874. client,
  875. printer_id=printer_id,
  876. tray_remain_start=tray_remain_start,
  877. current_lookup=current_lookup,
  878. handled_global_tray_ids=set(),
  879. archive_id=getattr(tracking, "archive_id", -1),
  880. print_used_keys=_print_used_tray_keys(slot_to_tray, getattr(tracking, "tray_now_at_start", None), state),
  881. )
  882. return
  883. # Same recovery the completion path does, for the same reason: a print
  884. # dispatched from Studio over the cloud left print start with no mapping to
  885. # store, and both paths below feed ``slot_to_tray`` to
  886. # ``_resolve_global_tray_id`` (#2768). An aborted print charges the wrong
  887. # spool just as readily as a finished one.
  888. if not slot_to_tray:
  889. slot_to_tray, _partial_mapping_source = _resolve_slot_to_tray_fallback(
  890. printer_id,
  891. filament_usage,
  892. getattr(tracking, "tray_now_at_start", None),
  893. )
  894. logger.info(
  895. "[SPOOLMAN] Partial usage: slot_to_tray=%s (source: %s)",
  896. slot_to_tray,
  897. _partial_mapping_source,
  898. )
  899. # Try to use accurate G-code parsed data
  900. if layer_usage:
  901. layer_usage_int = {
  902. int(layer): {int(fid): mm for fid, mm in filaments.items()} for layer, filaments in layer_usage.items()
  903. }
  904. usage_mm = get_cumulative_usage_at_layer(layer_usage_int, current_layer)
  905. if usage_mm:
  906. logger.info("[SPOOLMAN] Using G-code parsed data for layer %s", current_layer)
  907. # Build (slot_id, grams) list using Spoolman densities with 3MF fallback
  908. usage_items = []
  909. for filament_id, mm_used in usage_mm.items():
  910. slot_id = filament_id + 1 # filament_id is 0-based, slot_id is 1-based
  911. # Get density from Spoolman (most accurate), fall back to 3MF, then PLA default
  912. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  913. tray_info = ams_trays.get(global_tray_id)
  914. density = None
  915. diameter = 1.75
  916. if tray_info:
  917. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  918. if spool_tag:
  919. spool = await client.find_spool_by_tag(spool_tag)
  920. if spool:
  921. filament_data = spool.get("filament", {})
  922. density = filament_data.get("density")
  923. diameter = filament_data.get("diameter", 1.75)
  924. if not density:
  925. props = filament_properties.get(str(slot_id), filament_properties.get(slot_id, {}))
  926. density = props.get("density", 1.24)
  927. logger.debug("[SPOOLMAN] Using fallback density %s for slot %s", density, slot_id)
  928. grams_used = round(mm_to_grams(mm_used, diameter, density), 2)
  929. usage_items.append((slot_id, grams_used))
  930. spools_updated = await _report_spool_usage_for_slots(
  931. client,
  932. usage_items,
  933. ams_trays,
  934. slot_to_tray,
  935. "Partial (G-code)",
  936. printer_serial,
  937. printer_id=printer_id,
  938. )
  939. if spools_updated > 0:
  940. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using G-code data", spools_updated)
  941. return
  942. # Fallback: linear interpolation (if no G-code data available)
  943. progress_ratio = None
  944. if total_layers and total_layers > 0:
  945. progress_ratio = min(current_layer / total_layers, 1.0)
  946. elif progress_ratio_from_event is not None:
  947. progress_ratio = progress_ratio_from_event
  948. if progress_ratio is None:
  949. logger.debug(
  950. "[SPOOLMAN] Cannot use linear fallback: total_layers=%s, last_progress=%s",
  951. total_layers,
  952. last_progress,
  953. )
  954. return
  955. logger.info("[SPOOLMAN] Falling back to linear interpolation (%s)", progress_ratio)
  956. usage_items = []
  957. for usage in filament_usage:
  958. slot_id = usage.get("slot_id", 0)
  959. total_used_g = usage.get("used_g", 0)
  960. if total_used_g > 0:
  961. partial_used_g = round(total_used_g * progress_ratio, 2)
  962. usage_items.append((slot_id, partial_used_g))
  963. spools_updated = await _report_spool_usage_for_slots(
  964. client,
  965. usage_items,
  966. ams_trays,
  967. slot_to_tray,
  968. "Partial (linear)",
  969. printer_serial,
  970. printer_id=printer_id,
  971. )
  972. if spools_updated > 0:
  973. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using linear interpolation", spools_updated)
  974. async def report_usage(printer_id: int, archive_id: int):
  975. """Report filament usage to Spoolman after print completion.
  976. Two writers, mirroring the internal-inventory split in usage_tracker:
  977. 1. **3MF path (primary)** — per-filament slice estimates captured at
  978. print start drive a precise per-slot ``use_spool`` call.
  979. 2. **AMS remain%-delta (fallback)** — for slots the 3MF path didn't
  980. handle (including the no-3MF "Untitled" case from #1820): compute
  981. ``start_remain - current_remain``, multiply by the resolved
  982. Spoolman filament's reference weight, and write the delta. Mirrors
  983. ``usage_tracker.on_print_complete`` Path 2 (line 517).
  984. """
  985. async with async_session() as db:
  986. from backend.app.api.routes.settings import get_setting
  987. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  988. # Get tracking data stored at print start
  989. result = await db.execute(
  990. select(ActivePrintSpoolman)
  991. .where(ActivePrintSpoolman.printer_id == printer_id)
  992. .where(ActivePrintSpoolman.archive_id == archive_id)
  993. )
  994. tracking = result.scalar_one_or_none()
  995. if not tracking:
  996. logger.info("[SPOOLMAN] No tracking data for print (printer=%s, archive=%s)", printer_id, archive_id)
  997. return
  998. filament_usage = tracking.filament_usage or []
  999. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  1000. slot_to_tray = tracking.slot_to_tray
  1001. tray_remain_start = tracking.tray_remain_start or {}
  1002. # ``layer_usage`` and ``filament_properties`` were added later than
  1003. # the base tracking fields; use ``getattr`` so tests that stub
  1004. # ``tracking`` as a lightweight SimpleNamespace stay valid, and
  1005. # historic ORM rows loaded without these columns can't AttributeError
  1006. # on read.
  1007. layer_usage_raw = getattr(tracking, "layer_usage", None) or {}
  1008. filament_properties = getattr(tracking, "filament_properties", None) or {}
  1009. tray_now_at_start = getattr(tracking, "tray_now_at_start", None)
  1010. printer_serial = await _get_printer_serial(printer_id)
  1011. # Delete tracking row (we're done with it)
  1012. await db.delete(tracking)
  1013. await db.commit()
  1014. if not filament_usage and not tray_remain_start:
  1015. logger.debug("[SPOOLMAN] No usage data or remain-snapshot for archive %s", archive_id)
  1016. return
  1017. # Check if Spoolman is enabled
  1018. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1019. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1020. return
  1021. client = await _get_spoolman_client_with_fallback()
  1022. if not client:
  1023. logger.warning("[SPOOLMAN] Not reachable for usage reporting")
  1024. return
  1025. # Consult the live printer state for the tray-change log written by
  1026. # ``bambu_mqtt.py`` on every mid-print ``tray_now`` change (#957).
  1027. # When there's more than one entry, the print traversed >1 AMS tray
  1028. # and the split path attributes each segment to the tray that was
  1029. # loaded at the time — matches the internal Spool inventory writer
  1030. # in ``usage_tracker.py``. Without this, an AMS-backup runout switch
  1031. # charges the whole slot to the origin spool and pushes it past
  1032. # ``initial_weight`` (#1793).
  1033. #
  1034. # Split only for SINGLE-slot prints — same gate as
  1035. # ``usage_tracker.py:1002``. Multi-slot (multi-colour) prints
  1036. # naturally cycle trays for every colour change, so splitting each
  1037. # slot's grams across ALL tray_change_log entries would attribute
  1038. # slot 1's grams to the segments where slot 2's tray was loaded and
  1039. # vice versa. Multi-slot prints fall through to the existing
  1040. # single-tray path (which uses the stable ``slot_to_tray`` mapping).
  1041. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  1042. tray_changes: list[tuple[int, int]] = []
  1043. _state = None
  1044. if len(nonzero_slots) == 1:
  1045. from backend.app.services.printer_manager import printer_manager as _pm
  1046. _state = _pm.get_status(printer_id)
  1047. if _state is not None:
  1048. tray_changes = list(getattr(_state, "tray_change_log", []) or [])
  1049. _total_layers = int(getattr(_state, "total_layers", 0) or 0) if _state else 0
  1050. _current_layer = int(getattr(_state, "layer_num", 0) or 0) if _state else 0
  1051. # For the linear-fallback denominator when total_layers is 0 (P1S
  1052. # firmware resets it at print end). At completion the current layer
  1053. # is the print's last valid layer.
  1054. _layer_denom_hint = _total_layers or _current_layer
  1055. # Recover the mapping when print start had nothing to store — the
  1056. # cloud-dispatched Studio print of #2768. Only the 3MF path consumes
  1057. # ``slot_to_tray``; the remain-delta path below resolves spools from the
  1058. # AMS slot directly, so there is nothing to recover for it.
  1059. mapping_source = "stored" if slot_to_tray else "none"
  1060. if filament_usage and not slot_to_tray:
  1061. slot_to_tray, mapping_source = _resolve_slot_to_tray_fallback(printer_id, filament_usage, tray_now_at_start)
  1062. logger.info(
  1063. "[SPOOLMAN] Archive %s: slot_to_tray=%s (source: %s)",
  1064. archive_id,
  1065. slot_to_tray,
  1066. mapping_source,
  1067. )
  1068. # Nothing named a tray for this print and no fallback could recover
  1069. # one, so every slot is about to be resolved by position -- slicer slot
  1070. # 1 to the first loaded tray, and so on. That guess is right for an AMS
  1071. # loaded in slicer order and wrong for any other, and the caller has no
  1072. # way to tell which it got. Say so at a level that survives the default
  1073. # log filter, so a support bundle carries the reason (#2953).
  1074. #
  1075. # Excludes the tray-split path. It never reads ``slot_to_tray`` at all:
  1076. # it charges each segment to the tray the printer announced switching
  1077. # to, which is the same evidence the tray-state fallback is built on and
  1078. # is not a guess. Calling it one would suppress the archive rewrite for
  1079. # exactly the prints -- an AMS-backup runout on a Studio job (#1793 in
  1080. # #2768's conditions) -- whose attribution is best supported.
  1081. mapping_is_guess = bool(filament_usage) and mapping_source == "none" and len(tray_changes) <= 1
  1082. if mapping_is_guess:
  1083. logger.warning(
  1084. "[SPOOLMAN] Archive %s: no slot-to-tray mapping from any source -- "
  1085. "charging by tray position, which is a guess. Verify the spool weights "
  1086. "if the AMS is not loaded in slicer order.",
  1087. archive_id,
  1088. )
  1089. slot_colors: dict[int, str] = {}
  1090. slot_materials: dict[int, str] = {}
  1091. handled_global_tray_ids: set[int] = set()
  1092. spools_updated = 0
  1093. # --- Path 1: 3MF per-slot estimates -----------------------------
  1094. if filament_usage:
  1095. if len(tray_changes) > 1:
  1096. # Tray-split path — attribute per-segment to the tray that
  1097. # was loaded at that time.
  1098. logger.info(
  1099. "[SPOOLMAN] Reporting per-filament usage for archive %s with tray-split "
  1100. "(tray_change_log=%s, denom_layers=%d)",
  1101. archive_id,
  1102. tray_changes,
  1103. _layer_denom_hint,
  1104. )
  1105. # ``tracking.layer_usage`` was serialized to JSON so int keys
  1106. # come back as strings. Restore them for the split math.
  1107. layer_usage = None
  1108. if layer_usage_raw:
  1109. try:
  1110. layer_usage = {
  1111. int(layer): {int(fid): mm for fid, mm in filaments.items()}
  1112. for layer, filaments in layer_usage_raw.items()
  1113. }
  1114. except (TypeError, ValueError, AttributeError):
  1115. # AttributeError catches ``inner.items()`` when the
  1116. # inner value isn't dict-shaped (corrupt JSON row).
  1117. # Missing gcode falls through to the linear-ratio
  1118. # branch inside ``compute_tray_split_grams`` — still
  1119. # gives a correct split, just less precise.
  1120. layer_usage = None
  1121. split_updated, split_handled = await _report_spool_usage_split_by_tray_changes(
  1122. client,
  1123. filament_usage,
  1124. tray_changes,
  1125. ams_trays,
  1126. layer_usage,
  1127. filament_properties,
  1128. _total_layers,
  1129. _layer_denom_hint,
  1130. f"Archive {archive_id}",
  1131. printer_serial,
  1132. printer_id=printer_id,
  1133. slot_colors_out=slot_colors,
  1134. slot_materials_out=slot_materials,
  1135. )
  1136. spools_updated += split_updated
  1137. handled_global_tray_ids |= split_handled
  1138. else:
  1139. logger.info("[SPOOLMAN] Reporting per-filament usage for archive %s", archive_id)
  1140. usage_items = [(u.get("slot_id", 0), u.get("used_g", 0)) for u in filament_usage]
  1141. spools_updated = await _report_spool_usage_for_slots(
  1142. client,
  1143. usage_items,
  1144. ams_trays,
  1145. slot_to_tray,
  1146. f"Archive {archive_id}",
  1147. printer_serial,
  1148. printer_id=printer_id,
  1149. slot_colors_out=slot_colors,
  1150. slot_materials_out=slot_materials,
  1151. )
  1152. # Track which physical slots the 3MF path already covered so
  1153. # Path 2 doesn't double-charge them.
  1154. for u in filament_usage:
  1155. if u.get("used_g", 0) <= 0:
  1156. # ``_report_spool_usage_for_slots`` skipped this slot
  1157. # before resolving a tray for it, so nothing was
  1158. # charged and Path 2 is free to cover the slot from
  1159. # remain% -- claiming it here would suppress a real
  1160. # drop on the strength of a zero-gram estimate.
  1161. continue
  1162. slot_id = u.get("slot_id", 0)
  1163. handled_global_tray_ids.add(_resolve_global_tray_id(slot_id, slot_to_tray, ams_trays))
  1164. # --- Path 2: AMS remain%-delta for slots 3MF didn't cover -------
  1165. # Triggered for no-3MF "Untitled" prints (#1820) AND for partial
  1166. # 3MF coverage (slots whose filament_id wasn't in slice_info).
  1167. if tray_remain_start:
  1168. from backend.app.services.printer_manager import printer_manager
  1169. current = printer_manager.get_status(printer_id)
  1170. current_lookup = _snapshot_tray_remain(current.raw_data) if current and current.raw_data else {}
  1171. fallback_updates = await _report_remain_delta_for_slots(
  1172. client,
  1173. printer_id=printer_id,
  1174. tray_remain_start=tray_remain_start,
  1175. current_lookup=current_lookup,
  1176. handled_global_tray_ids=handled_global_tray_ids,
  1177. archive_id=archive_id,
  1178. print_used_keys=_print_used_tray_keys(slot_to_tray, tray_now_at_start, current),
  1179. slot_colors_out=slot_colors,
  1180. slot_materials_out=slot_materials,
  1181. )
  1182. spools_updated += fallback_updates
  1183. if spools_updated == 0:
  1184. logger.info("[SPOOLMAN] Archive %s: no spools updated", archive_id)
  1185. else:
  1186. logger.info("[SPOOLMAN] Archive %s: updated %s spool(s)", archive_id, spools_updated)
  1187. # Stamp the archive's filament colour from the matched Spoolman spools
  1188. # so it reflects the curated inventory colour, not the slicer's 3MF
  1189. # value (#1494) — mirrors the built-in inventory path in usage_tracker.
  1190. #
  1191. # Skipped when the mapping was a positional guess. Charging the wrong
  1192. # spool costs grams the owner can put back; rewriting the archive's
  1193. # colour and material on top of it overwrites what the slicer actually
  1194. # recorded, and the print then reads as a different filament than the
  1195. # one that made it, with nothing left to compare against (#2953).
  1196. if mapping_is_guess:
  1197. if slot_colors or slot_materials:
  1198. logger.info(
  1199. "[SPOOLMAN] Archive %s: leaving filament colour/type as sliced — "
  1200. "the spools were matched by position, not by a known mapping",
  1201. archive_id,
  1202. )
  1203. else:
  1204. await _apply_spool_colors_to_archive(db, archive_id, filament_usage, slot_colors)
  1205. # Same for the material: a slot mapped to a differently-typed spool
  1206. # than it was sliced for otherwise records the sliced type (#2563).
  1207. await _apply_spool_types_to_archive(db, archive_id, filament_usage, slot_materials)
  1208. def _print_used_tray_keys(
  1209. slot_to_tray: list | None,
  1210. tray_now_at_start: int | None,
  1211. state,
  1212. ) -> set[tuple[int, int]]:
  1213. """Which AMS slots this print actually drew from, as far as we can tell.
  1214. Mirrors the guard the internal tracker has carried since #1269. Without
  1215. it, swapping a spool in a slot the print never touched drops that slot's
  1216. ``remain%``, and the remain-delta path reads the drop as consumption and
  1217. charges it to whoever the slot is assigned to. That is a phantom write to
  1218. an uninvolved spool, and it is likeliest on exactly the prints this
  1219. fallback serves -- ones with no 3MF, where nothing else limits which slots
  1220. are considered.
  1221. Three sources, matching the internal tracker's:
  1222. - the print's ``ams_mapping``, stored here as ``slot_to_tray``;
  1223. - every tray the printer switched to mid-print;
  1224. - the tray it was drawing from at the start.
  1225. An empty result means no evidence, not "no slots" -- callers must then
  1226. consider every slot, as before, or a printer that reports none of the
  1227. three would silently stop being tracked at all.
  1228. Takes the two stored values rather than the tracking row: the caller
  1229. deletes that row before it gets this far, and everything read off it is
  1230. read into locals beforehand.
  1231. """
  1232. keys: set[tuple[int, int]] = set()
  1233. for global_tray_id in list(slot_to_tray or []):
  1234. if isinstance(global_tray_id, int) and global_tray_id >= 0:
  1235. keys.add(_global_tray_id_to_ams_slot(global_tray_id))
  1236. for change in getattr(state, "tray_change_log", None) or []:
  1237. if isinstance(change, (tuple, list)) and change:
  1238. global_tray_id = change[0]
  1239. if isinstance(global_tray_id, int) and global_tray_id >= 0:
  1240. keys.add(_global_tray_id_to_ams_slot(global_tray_id))
  1241. if isinstance(tray_now_at_start, int) and 0 <= tray_now_at_start <= _MAX_REAL_TRAY_ID:
  1242. keys.add(_global_tray_id_to_ams_slot(tray_now_at_start))
  1243. return keys
  1244. async def _report_remain_delta_for_slots(
  1245. client,
  1246. *,
  1247. printer_id: int,
  1248. tray_remain_start: dict[str, dict],
  1249. current_lookup: dict[str, dict],
  1250. handled_global_tray_ids: set[int],
  1251. archive_id: int,
  1252. print_used_keys: set[tuple[int, int]] | None = None,
  1253. slot_colors_out: dict[int, str] | None = None,
  1254. slot_materials_out: dict[int, str] | None = None,
  1255. ) -> int:
  1256. """AMS remain%-delta path: write ``(start - current) * filament.weight``
  1257. grams to Spoolman for slots the 3MF path didn't cover.
  1258. Mirrors ``usage_tracker.on_print_complete`` Path 2: per-slot, gated on a
  1259. valid current ``remain%``, skipped on spool swap (``tray_uuid`` changed),
  1260. using the resolved spool's filament reference weight rather than MQTT's
  1261. unreliable ``tray_weight`` (which is the failure mode #1119 documented).
  1262. """
  1263. spools_updated = 0
  1264. not_in_print: list[str] = []
  1265. for slot_key, start in tray_remain_start.items():
  1266. try:
  1267. ams_id_str, tray_id_str = slot_key.split("-", 1)
  1268. ams_id, tray_id = int(ams_id_str), int(tray_id_str)
  1269. except (ValueError, AttributeError):
  1270. continue
  1271. # Skip slots already handled by the 3MF path. Encoding mirrors
  1272. # build_ams_tray_lookup: VT trays land at 254/255, AMS-HT keeps
  1273. # its native id (>=128), regular AMS slots are ams_id*4+tray_id.
  1274. if ams_id == 255:
  1275. global_tray_id = 254 + tray_id
  1276. elif ams_id >= 128:
  1277. global_tray_id = ams_id
  1278. else:
  1279. global_tray_id = ams_id * 4 + tray_id
  1280. if global_tray_id in handled_global_tray_ids:
  1281. continue
  1282. # Slots the print never touched (#1269's guard, see _print_used_tray_keys).
  1283. # Only enforced when there is evidence of which slots it did use.
  1284. # Collected rather than logged per slot: on a four-AMS farm a
  1285. # single-colour print leaves fifteen of these, and they are the
  1286. # expected case, unlike the "consumed but charged nothing" lines below.
  1287. if print_used_keys and (ams_id, tray_id) not in print_used_keys:
  1288. not_in_print.append(f"AMS{ams_id}-T{tray_id}")
  1289. continue
  1290. current = current_lookup.get(slot_key)
  1291. if not current:
  1292. # Reported at info, like the internal tracker's equivalent: on a
  1293. # near-empty spool the AMS reports a negative remain%, which the
  1294. # snapshot gate rejects, and the slot that was actually printing
  1295. # disappears from this path entirely (#1820).
  1296. logger.info(
  1297. "[SPOOLMAN] AMS%d-T%d: no valid remain%% at completion, nothing charged for this slot", ams_id, tray_id
  1298. )
  1299. continue
  1300. # Spool swap mid-print — tray_uuid changed. We don't know how much
  1301. # of the print went to which spool; skip rather than mis-attribute.
  1302. start_uuid = (start.get("tray_uuid") or "").lower()
  1303. cur_uuid = (current.get("tray_uuid") or "").lower()
  1304. if start_uuid and cur_uuid and start_uuid != cur_uuid:
  1305. logger.info(
  1306. "[SPOOLMAN] AMS%d-T%d: spool swapped mid-print (uuid changed), skipping remain-delta", ams_id, tray_id
  1307. )
  1308. continue
  1309. delta_pct = start["remain"] - current["remain"]
  1310. if delta_pct <= 0:
  1311. # A fresh spool reads 100% for the first tens of grams and the AMS
  1312. # estimate drifts upward on its own, so this covers a real print
  1313. # that simply left no trace at AMS granularity -- not only a refill.
  1314. # Said out loud so it can be told apart from having nothing to
  1315. # charge, which is what "no spools updated" alone looked like.
  1316. logger.info(
  1317. "[SPOOLMAN] AMS%d-T%d: remain%% did not fall over the print (%d%% -> %d%%), nothing charged",
  1318. ams_id,
  1319. tray_id,
  1320. start["remain"],
  1321. current["remain"],
  1322. )
  1323. continue # No consumption captured at AMS granularity, or refilled
  1324. spool_id = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  1325. if spool_id is None:
  1326. logger.info(
  1327. "[SPOOLMAN] AMS%d-T%d: consumed %d%% but has no Spoolman slot assignment, nothing charged",
  1328. ams_id,
  1329. tray_id,
  1330. delta_pct,
  1331. )
  1332. continue
  1333. # Look up the spool's filament reference weight. Use a fresh GET so
  1334. # we don't depend on a stale cached_spools list. Failure here is
  1335. # silent-skip rather than fatal — other slots can still be written.
  1336. try:
  1337. spool = await client.get_spool(spool_id)
  1338. except Exception as exc: # noqa: BLE001
  1339. logger.debug("[SPOOLMAN] AMS%d-T%d: get_spool(%s) failed: %s", ams_id, tray_id, spool_id, exc)
  1340. continue
  1341. filament = spool.get("filament") or {}
  1342. ref_weight = filament.get("weight")
  1343. if not ref_weight or ref_weight <= 0:
  1344. logger.debug(
  1345. "[SPOOLMAN] AMS%d-T%d: spool %s has no filament.weight, skipping remain-delta",
  1346. ams_id,
  1347. tray_id,
  1348. spool_id,
  1349. )
  1350. continue
  1351. grams_used = round((delta_pct / 100.0) * ref_weight, 2)
  1352. if grams_used <= 0:
  1353. continue
  1354. try:
  1355. await client.use_spool(spool_id, grams_used)
  1356. except Exception as exc: # noqa: BLE001
  1357. logger.warning(
  1358. "[SPOOLMAN] AMS%d-T%d: use_spool(%s, %.2fg) failed: %s", ams_id, tray_id, spool_id, grams_used, exc
  1359. )
  1360. continue
  1361. spools_updated += 1
  1362. # No 3MF slot_id for this path — use the AMS slot key so the maps can
  1363. # still be inspected by callers if needed. The archive rewrites
  1364. # (#1494 colour, #2563 type) key on 3MF slot_ids, so remain-delta-only
  1365. # prints intentionally don't participate (matches usage_tracker's
  1366. # slot_id=None).
  1367. if slot_colors_out is not None:
  1368. color = filament.get("color_hex")
  1369. if color:
  1370. slot_colors_out[-(global_tray_id + 1)] = color
  1371. if slot_materials_out is not None:
  1372. material = filament.get("material")
  1373. if material:
  1374. slot_materials_out[-(global_tray_id + 1)] = material
  1375. logger.info(
  1376. "[SPOOLMAN] Archive %s AMS%d-T%d: %.2fg via remain-delta (%d%% of %.0fg) -> spool %s",
  1377. archive_id,
  1378. ams_id,
  1379. tray_id,
  1380. grams_used,
  1381. delta_pct,
  1382. ref_weight,
  1383. spool_id,
  1384. )
  1385. if not_in_print:
  1386. logger.info(
  1387. "[SPOOLMAN] Archive %s: slots not part of this print, left alone: %s",
  1388. archive_id,
  1389. ", ".join(not_in_print),
  1390. )
  1391. return spools_updated
  1392. async def _apply_spool_colors_to_archive(
  1393. db,
  1394. archive_id: int,
  1395. filament_usage: list[dict],
  1396. slot_colors: dict[int, str],
  1397. ) -> None:
  1398. """Overwrite an archive's ``filament_color`` with the colours of the
  1399. Spoolman spools that fed the print (#1494).
  1400. All-or-nothing, exactly like the built-in inventory path: the colour is
  1401. only rewritten when every used slot resolved to a spool that carries a
  1402. colour, so a partial match never drops slots from the archive.
  1403. """
  1404. if not slot_colors:
  1405. return
  1406. from backend.app.models.archive import PrintArchive
  1407. from backend.app.services.usage_tracker import (
  1408. _archive_colors_from_spools,
  1409. _spool_color_to_hex,
  1410. )
  1411. results = [{"slot_id": sid, "color": _spool_color_to_hex(hex_)} for sid, hex_ in slot_colors.items()]
  1412. colors = _archive_colors_from_spools(filament_usage, results)
  1413. if not colors:
  1414. return
  1415. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1416. if archive is None:
  1417. return
  1418. joined = ",".join(colors)
  1419. if joined != archive.filament_color:
  1420. logger.info(
  1421. "[SPOOLMAN] Archive %s filament_color %r -> %r (from Spoolman spools)",
  1422. archive_id,
  1423. archive.filament_color,
  1424. joined,
  1425. )
  1426. archive.filament_color = joined
  1427. await db.commit()
  1428. async def _apply_spool_types_to_archive(
  1429. db,
  1430. archive_id: int,
  1431. filament_usage: list[dict],
  1432. slot_materials: dict[int, str],
  1433. ) -> None:
  1434. """Overwrite an archive's ``filament_type`` with the materials of the
  1435. Spoolman spools that fed the print (#2563).
  1436. All-or-nothing, exactly like the colour path and the built-in inventory
  1437. path: the type is only rewritten when every used slot resolved to a spool
  1438. that carries a material, so a partial match never drops slots from the
  1439. archive or the material statistics.
  1440. """
  1441. if not slot_materials:
  1442. return
  1443. from backend.app.models.archive import PrintArchive
  1444. from backend.app.services.usage_tracker import _archive_types_from_spools
  1445. results = [{"slot_id": sid, "material": material} for sid, material in slot_materials.items()]
  1446. types = _archive_types_from_spools(filament_usage, results)
  1447. if not types:
  1448. return
  1449. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1450. if archive is None:
  1451. return
  1452. joined = ",".join(types)
  1453. if joined != archive.filament_type:
  1454. logger.info(
  1455. "[SPOOLMAN] Archive %s filament_type %r -> %r (from Spoolman spools)",
  1456. archive_id,
  1457. archive.filament_type,
  1458. joined,
  1459. )
  1460. archive.filament_type = joined
  1461. await db.commit()