spoolman_tracking.py 66 KB

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