usage_tracker.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. """Automatic filament consumption tracking.
  2. Captures AMS tray remain% at print start, then computes consumption
  3. deltas at print complete to update spool weight_used and last_used.
  4. Primary tracking uses 3MF slicer estimates (precise per-filament data).
  5. AMS remain% delta is the fallback for trays not covered by 3MF data.
  6. """
  7. import json
  8. import logging
  9. from dataclasses import dataclass, field
  10. from datetime import datetime, timezone
  11. from sqlalchemy import select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.models.spool import Spool
  14. from backend.app.models.spool_assignment import SpoolAssignment
  15. from backend.app.models.spool_usage_history import SpoolUsageHistory
  16. logger = logging.getLogger(__name__)
  17. def _decode_mqtt_mapping(mapping_raw: list | None) -> list[int] | None:
  18. """Decode MQTT mapping field (snow-encoded) to bambuddy global tray IDs.
  19. The printer's MQTT mapping field is an array indexed by slicer filament slot
  20. (0-based). Each value uses snow encoding: ams_hw_id * 256 + local_slot.
  21. 65535 means unmapped.
  22. Returns a list of bambuddy global tray IDs (or -1 for unmapped), or None if
  23. no valid mappings found.
  24. """
  25. if not isinstance(mapping_raw, list) or not mapping_raw:
  26. return None
  27. result = []
  28. for value in mapping_raw:
  29. if not isinstance(value, int) or value >= 65535:
  30. result.append(-1)
  31. continue
  32. ams_hw_id = value >> 8
  33. slot = value & 0xFF
  34. if 0 <= ams_hw_id <= 3:
  35. # Regular AMS: sequential global ID
  36. result.append(ams_hw_id * 4 + (slot & 0x03))
  37. elif 128 <= ams_hw_id <= 135:
  38. # AMS-HT: global ID is the hardware ID (one slot per unit)
  39. result.append(ams_hw_id)
  40. elif ams_hw_id in (254, 255):
  41. # External spool
  42. result.append(254 if slot != 255 else 255)
  43. else:
  44. result.append(-1)
  45. # Only return if at least one valid mapping exists
  46. if all(v < 0 for v in result):
  47. return None
  48. return result
  49. def _spool_color_to_hex(rgba: str | None) -> str | None:
  50. """Normalise a ``Spool.rgba`` value (``RRGGBBAA`` hex, no ``#``) to the
  51. ``#RRGGBB`` form archives store in ``filament_color``.
  52. Alpha is dropped — the archive colour list and the Color Distribution
  53. graph treat filament colour as opaque. Returns ``None`` for a missing or
  54. too-short value so the caller can fall back to the 3MF colour.
  55. """
  56. if not rgba:
  57. return None
  58. h = rgba.strip().lstrip("#")
  59. if len(h) < 6:
  60. return None
  61. return "#" + h[:6].upper()
  62. def _archive_colors_from_spools(filament_usage: list[dict], results: list[dict]) -> list[str] | None:
  63. """Slot-ordered, de-duplicated hex colours for an archive's ``filament_color``,
  64. taken from the inventory spools that actually fed the print (#1494).
  65. The slicer's 3MF carries its own ``filament_colour`` per slot — a value
  66. picked independently of the colour the user curates on the matched
  67. inventory spool. So an archive printed from a ``#000000`` inventory spool
  68. would otherwise show the slicer's near-black ``#161616``. Once usage
  69. tracking has resolved the used slots to spools, the spool colours are the
  70. authoritative source and replace the 3MF values.
  71. Returns ``None`` — leave the 3MF colour untouched — unless *every* slot
  72. with non-zero usage was matched to a spool that carries a colour. A
  73. partial rewrite would silently drop the unmatched slots' colours from the
  74. archive (and the Color Distribution graph), so it is all-or-nothing.
  75. """
  76. used_slots = {u["slot_id"] for u in filament_usage if u.get("used_g", 0) > 0 and u.get("slot_id") is not None}
  77. if not used_slots:
  78. return None
  79. slot_color: dict[int, str] = {}
  80. for r in results:
  81. slot_id = r.get("slot_id")
  82. color = r.get("color")
  83. if slot_id is not None and color:
  84. slot_color.setdefault(slot_id, color)
  85. if not used_slots.issubset(slot_color):
  86. return None
  87. ordered: list[str] = []
  88. for slot_id in sorted(used_slots):
  89. color = slot_color[slot_id]
  90. if color not in ordered:
  91. ordered.append(color)
  92. return ordered
  93. def _match_slots_by_color(
  94. filament_usage: list[dict],
  95. ams_raw: dict | list | None,
  96. ) -> list[int] | None:
  97. """Match 3MF filament slots to AMS trays by color.
  98. Fallback mapping for printers that don't provide the MQTT mapping field
  99. or request topic subscription (e.g. A1, A1 Mini, P1S, P2S).
  100. Compares the 3MF slicer filament color (per slot) against each AMS tray's
  101. color to find a unique match. Only returns a mapping if every used slot
  102. matches exactly one tray (no ambiguity).
  103. Args:
  104. filament_usage: List of 3MF slot dicts with 'slot_id', 'color', 'type'
  105. ams_raw: raw_data["ams"] dict or list from printer state
  106. Returns:
  107. List of global tray IDs indexed by slicer slot (0-based), or None.
  108. """
  109. if not filament_usage or not ams_raw:
  110. return None
  111. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  112. if not ams_data:
  113. return None
  114. # Build map of normalized color → list of global tray IDs
  115. color_to_trays: dict[str, list[int]] = {}
  116. for ams_unit in ams_data:
  117. ams_id = int(ams_unit.get("id", 0))
  118. for tray in ams_unit.get("tray", []):
  119. tray_id = int(tray.get("id", 0))
  120. tray_color = tray.get("tray_color", "")
  121. tray_type = tray.get("tray_type", "")
  122. if not tray_color or not tray_type:
  123. continue
  124. # Normalize AMS color: strip alpha (last 2 chars), lowercase
  125. norm = tray_color[:6].lower() if len(tray_color) >= 6 else tray_color.lower()
  126. if ams_id >= 128:
  127. global_id = ams_id # AMS-HT
  128. else:
  129. global_id = ams_id * 4 + tray_id
  130. color_to_trays.setdefault(norm, []).append(global_id)
  131. if not color_to_trays:
  132. return None
  133. # Find max slot_id to size the result array
  134. max_slot = max(u.get("slot_id", 0) for u in filament_usage)
  135. if max_slot <= 0:
  136. return None
  137. result = [-1] * max_slot
  138. used_trays: set[int] = set()
  139. for usage in filament_usage:
  140. slot_id = usage.get("slot_id", 0)
  141. if slot_id <= 0:
  142. continue
  143. slot_color = usage.get("color", "").lstrip("#").lower()
  144. if len(slot_color) < 6:
  145. return None # Can't match without a valid color
  146. slot_color = slot_color[:6] # Strip alpha if present
  147. candidates = color_to_trays.get(slot_color, [])
  148. # Filter out trays already claimed by another slot
  149. available = [t for t in candidates if t not in used_trays]
  150. if len(available) != 1:
  151. # Ambiguous (multiple trays with same color) or no match
  152. return None
  153. result[slot_id - 1] = available[0]
  154. used_trays.add(available[0])
  155. # Only return if at least one valid mapping exists
  156. if all(v < 0 for v in result):
  157. return None
  158. logger.info("[UsageTracker] Color-matched slot_to_tray: %s", result)
  159. return result
  160. @dataclass
  161. class PrintSession:
  162. printer_id: int
  163. print_name: str
  164. started_at: datetime
  165. tray_remain_start: dict[tuple[int, int], int] = field(default_factory=dict)
  166. # tray_now at print start (correct value, unlike at completion where it's 255)
  167. tray_now_at_start: int = -1
  168. # Snapshot of spool assignments at print start: {(ams_id, tray_id): spool_id}
  169. # Prevents usage loss when on_ams_change unlinks a spool mid-print
  170. spool_assignments: dict[tuple[int, int], int] = field(default_factory=dict)
  171. # AMS mapping from print command (captured at start, needed when auto-archive is off)
  172. ams_mapping: list[int] | None = None
  173. # Queue item's plate_id when this print is a multi-plate 3MF dispatched for a
  174. # single plate (#1697). None for non-queue prints — the file's first/only plate
  175. # is the default and the 3MF parser already returns the full file in that case.
  176. plate_id: int | None = None
  177. # Module-level storage, keyed by printer_id
  178. _active_sessions: dict[int, PrintSession] = {}
  179. def _to_epoch_seconds(value: datetime | None) -> float | None:
  180. """Convert datetime to epoch seconds, assuming UTC for naive values."""
  181. if value is None:
  182. return None
  183. dt = value
  184. if dt.tzinfo is None:
  185. dt = dt.replace(tzinfo=timezone.utc)
  186. return dt.timestamp()
  187. async def _resolve_spool_id_for_tray(
  188. printer_id: int,
  189. ams_id: int,
  190. tray_id: int,
  191. db: AsyncSession,
  192. spool_assignments_snapshot: dict[tuple[int, int], int] | None = None,
  193. print_started_at: datetime | None = None,
  194. ) -> int | None:
  195. """Resolve spool ID for a tray with safe support for mid-print reassignment.
  196. Resolution order:
  197. 1. If snapshot exists and live assignment changed *during this print*, use live spool.
  198. 2. Otherwise use snapshot spool when available.
  199. 3. Fall back to live assignment.
  200. """
  201. key = (ams_id, tray_id)
  202. snapshot_spool_id = spool_assignments_snapshot.get(key) if spool_assignments_snapshot else None
  203. # Backward-compatible fast path: if we have a snapshot but no print-start
  204. # timestamp, preserve legacy behavior and avoid extra DB lookups.
  205. if snapshot_spool_id is not None and print_started_at is None:
  206. return snapshot_spool_id
  207. result = await db.execute(
  208. select(SpoolAssignment).where(
  209. SpoolAssignment.printer_id == printer_id,
  210. SpoolAssignment.ams_id == ams_id,
  211. SpoolAssignment.tray_id == tray_id,
  212. )
  213. )
  214. live_assignment = result.scalar_one_or_none()
  215. if snapshot_spool_id is not None:
  216. if live_assignment and live_assignment.spool_id != snapshot_spool_id:
  217. live_created_ts = _to_epoch_seconds(getattr(live_assignment, "created_at", None))
  218. started_ts = _to_epoch_seconds(print_started_at)
  219. if live_created_ts is not None and started_ts is not None and live_created_ts >= started_ts:
  220. logger.info(
  221. "[UsageTracker] Assignment changed during print for printer %d AMS%d-T%d: snapshot spool %d -> live spool %d",
  222. printer_id,
  223. ams_id,
  224. tray_id,
  225. snapshot_spool_id,
  226. live_assignment.spool_id,
  227. )
  228. return live_assignment.spool_id
  229. return snapshot_spool_id
  230. if live_assignment:
  231. return live_assignment.spool_id
  232. return None
  233. async def on_print_start(printer_id: int, data: dict, printer_manager, db: AsyncSession | None = None) -> None:
  234. """Capture AMS tray remain% and spool assignments at print start."""
  235. state = printer_manager.get_status(printer_id)
  236. if not state or not state.raw_data:
  237. logger.debug("[UsageTracker] No state for printer %d, skipping", printer_id)
  238. return
  239. ams_raw = state.raw_data.get("ams", [])
  240. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  241. tray_remain_start: dict[tuple[int, int], int] = {}
  242. skipped_invalid: list[str] = []
  243. for ams_unit in ams_data:
  244. ams_id = int(ams_unit.get("id", 0))
  245. for tray in ams_unit.get("tray", []):
  246. tray_id = int(tray.get("id", 0))
  247. remain = tray.get("remain", -1)
  248. if isinstance(remain, int) and 0 <= remain <= 100:
  249. tray_remain_start[(ams_id, tray_id)] = remain
  250. else:
  251. skipped_invalid.append(f"AMS{ams_id}-T{tray_id}(remain={remain})")
  252. # Also capture VT (external) tray remain% — these are separate from AMS units
  253. vt_tray_raw = state.raw_data.get("vt_tray") or []
  254. if isinstance(vt_tray_raw, dict):
  255. vt_tray_raw = [vt_tray_raw]
  256. for vt in vt_tray_raw:
  257. if not isinstance(vt, dict):
  258. continue
  259. vt_id = int(vt.get("id", 254))
  260. # VT tray id 254 → (ams_id=255, tray_id=0), id 255 → (ams_id=255, tray_id=1)
  261. vt_tray_id = vt_id - 254
  262. remain = vt.get("remain", -1)
  263. if isinstance(remain, int) and 0 <= remain <= 100:
  264. tray_remain_start[(255, vt_tray_id)] = remain
  265. else:
  266. skipped_invalid.append(f"VT{vt_id}(remain={remain})")
  267. if skipped_invalid:
  268. logger.info(
  269. "[UsageTracker] Skipped trays with invalid remain%% for printer %d: %s",
  270. printer_id,
  271. ", ".join(skipped_invalid),
  272. )
  273. if not ams_data and not vt_tray_raw:
  274. logger.debug("[UsageTracker] No AMS or VT tray data for printer %d, skipping", printer_id)
  275. return
  276. print_name = data.get("subtask_name", "") or data.get("filename", "unknown")
  277. # Capture tray_now at print start (reliable, unlike at completion where it's 255)
  278. tray_now_at_start = state.tray_now if state else -1
  279. # --- Diagnostic logging: dump mapping-related MQTT fields at print start ---
  280. # This helps us understand what each printer model reports for slot-to-tray mapping.
  281. mapping_field = state.raw_data.get("mapping")
  282. logger.info(
  283. "[UsageTracker] PRINT START printer %d: mapping=%s, tray_now=%d, last_loaded_tray=%s",
  284. printer_id,
  285. mapping_field,
  286. tray_now_at_start,
  287. getattr(state, "last_loaded_tray", "N/A"),
  288. )
  289. # Log all raw_data keys containing "map" or "ams" for discovery
  290. map_keys = {k: state.raw_data[k] for k in state.raw_data if "map" in k.lower()}
  291. if map_keys:
  292. logger.info("[UsageTracker] PRINT START printer %d: mapping-related keys: %s", printer_id, map_keys)
  293. # Log per-tray summary: tray_now, tray_tar, tray_type, tray_color for each slot
  294. for ams_unit in ams_data:
  295. ams_id = int(ams_unit.get("id", 0))
  296. tray_summary = []
  297. for tray in ams_unit.get("tray", []):
  298. tray_summary.append(
  299. f"T{tray.get('id', '?')}(type={tray.get('tray_type', '')}, "
  300. f"color={tray.get('tray_color', '')}, "
  301. f"now={ams_raw.get('tray_now', '?') if isinstance(ams_raw, dict) else '?'}, "
  302. f"tar={ams_raw.get('tray_tar', '?') if isinstance(ams_raw, dict) else '?'})"
  303. )
  304. logger.info("[UsageTracker] PRINT START printer %d AMS %d: %s", printer_id, ams_id, ", ".join(tray_summary))
  305. # Snapshot spool assignments so usage isn't lost if on_ams_change unlinks mid-print
  306. spool_assignments: dict[tuple[int, int], int] = {}
  307. if db:
  308. assign_result = await db.execute(select(SpoolAssignment).where(SpoolAssignment.printer_id == printer_id))
  309. for assignment in assign_result.scalars().all():
  310. spool_assignments[(assignment.ams_id, assignment.tray_id)] = assignment.spool_id
  311. if spool_assignments:
  312. logger.info(
  313. "[UsageTracker] Snapshotted %d spool assignments for printer %d: %s",
  314. len(spool_assignments),
  315. printer_id,
  316. {f"{k[0]}-{k[1]}": v for k, v in spool_assignments.items()},
  317. )
  318. # Capture the queue item's plate_id so 3MF parsing at completion is scoped to
  319. # the plate that actually ran, not the whole multi-plate file (#1697).
  320. plate_id: int | None = None
  321. if db:
  322. from backend.app.models.print_queue import PrintQueueItem
  323. queue_result = await db.execute(
  324. select(PrintQueueItem)
  325. .where(PrintQueueItem.printer_id == printer_id)
  326. .where(PrintQueueItem.status == "printing")
  327. )
  328. queue_item = queue_result.scalars().first()
  329. if queue_item is not None:
  330. plate_id = queue_item.plate_id
  331. # Always create session (even without valid remain data) so print_name
  332. # is available at completion for 3MF-based tracking
  333. session = PrintSession(
  334. printer_id=printer_id,
  335. print_name=print_name,
  336. started_at=datetime.now(timezone.utc),
  337. tray_remain_start=tray_remain_start,
  338. tray_now_at_start=tray_now_at_start,
  339. spool_assignments=spool_assignments,
  340. ams_mapping=data.get("ams_mapping"),
  341. plate_id=plate_id,
  342. )
  343. _active_sessions[printer_id] = session
  344. if tray_remain_start:
  345. logger.info(
  346. "[UsageTracker] Captured start remain%% for printer %d (%d trays): %s",
  347. printer_id,
  348. len(tray_remain_start),
  349. {f"{k[0]}-{k[1]}": v for k, v in tray_remain_start.items()},
  350. )
  351. else:
  352. logger.debug("[UsageTracker] No valid remain%% for printer %d, 3MF fallback available", printer_id)
  353. async def on_print_complete(
  354. printer_id: int,
  355. data: dict,
  356. printer_manager,
  357. db: AsyncSession,
  358. archive_id: int | None = None,
  359. ams_mapping: list[int] | None = None,
  360. ) -> list[dict]:
  361. """Compute consumption deltas and update spool weight_used/last_used.
  362. Uses two tracking strategies in priority order:
  363. 1. 3MF per-filament estimates (primary) — precise slicer data for all spools
  364. 2. AMS remain% delta (fallback) — only for trays not already handled by 3MF
  365. Returns a list of dicts describing what was logged (for WebSocket broadcast).
  366. """
  367. from sqlalchemy import select
  368. from backend.app.api.routes.settings import get_setting
  369. from backend.app.models.spool_usage_history import SpoolUsageHistory
  370. session = _active_sessions.pop(printer_id, None)
  371. status = data.get("status", "completed")
  372. results = []
  373. handled_trays: set[tuple[int, int]] = set()
  374. # Fetch default filament cost from settings for fallback
  375. default_cost_str = await get_setting(db, "default_filament_cost")
  376. default_filament_cost = float(default_cost_str) if default_cost_str else 0.0
  377. # Fall back to ams_mapping captured at print start (needed when auto-archive is off
  378. # and the caller can't retrieve the mapping from _print_ams_mappings without archive_id)
  379. if not ams_mapping and session and session.ams_mapping:
  380. ams_mapping = session.ams_mapping
  381. logger.info(
  382. "[UsageTracker] on_print_complete: printer=%d, archive=%s, session=%s, ams_mapping=%s",
  383. printer_id,
  384. archive_id,
  385. "yes" if session else "no",
  386. ams_mapping,
  387. )
  388. # --- Diagnostic logging: dump mapping-related MQTT fields at print completion ---
  389. state = printer_manager.get_status(printer_id)
  390. if state and state.raw_data:
  391. logger.info(
  392. "[UsageTracker] PRINT COMPLETE printer %d: mapping=%s, tray_now=%s, last_loaded_tray=%s",
  393. printer_id,
  394. state.raw_data.get("mapping"),
  395. state.tray_now,
  396. getattr(state, "last_loaded_tray", "N/A"),
  397. )
  398. # --- Path 1 (PRIMARY): 3MF per-filament estimates ---
  399. print_name = (
  400. (session.print_name if session else None) or data.get("subtask_name", "") or data.get("filename", "unknown")
  401. )
  402. # When auto-archive is disabled (archive_id=None), try to find a 3MF by filename
  403. # from the library or previous archives so we can still track filament usage.
  404. threemf_path = None
  405. if not archive_id:
  406. from backend.app.core.config import settings as app_settings
  407. search_filename = data.get("filename") or data.get("subtask_name") or (session.print_name if session else "")
  408. if search_filename:
  409. threemf_path = await _find_3mf_by_filename(printer_id, search_filename, db, app_settings.base_dir)
  410. if archive_id or threemf_path:
  411. threemf_results = await _track_from_3mf(
  412. printer_id,
  413. archive_id,
  414. status,
  415. print_name,
  416. handled_trays,
  417. printer_manager,
  418. db,
  419. ams_mapping=ams_mapping,
  420. tray_now_at_start=session.tray_now_at_start if session else -1,
  421. last_progress=data.get("last_progress", 0.0),
  422. last_layer_num=data.get("last_layer_num", 0),
  423. default_filament_cost=default_filament_cost,
  424. spool_assignments=session.spool_assignments if session else None,
  425. print_started_at=session.started_at if session else None,
  426. threemf_path=threemf_path,
  427. plate_id=session.plate_id if session else None,
  428. )
  429. results.extend(threemf_results)
  430. # --- Path 2 (FALLBACK): AMS remain% delta (only for trays not handled by 3MF) ---
  431. if session and session.tray_remain_start:
  432. state = printer_manager.get_status(printer_id)
  433. if state and state.raw_data:
  434. ams_raw = state.raw_data.get("ams", [])
  435. ams_data = (
  436. ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  437. )
  438. # Build set of trays actually involved in this print (#1269).
  439. # Without this guard, swapping a spool in an UNUSED slot mid-print
  440. # makes that slot's remain% drop to 0, which the fallback below
  441. # would otherwise charge to the originally-assigned spool.
  442. def _global_to_ams_key(global_tray_id: int) -> tuple[int, int]:
  443. if global_tray_id >= 254:
  444. return (255, global_tray_id - 254)
  445. if global_tray_id >= 128:
  446. return (global_tray_id, 0)
  447. return (global_tray_id // 4, global_tray_id % 4)
  448. print_used_keys: set[tuple[int, int]] = set()
  449. if ams_mapping:
  450. for gid in ams_mapping:
  451. if isinstance(gid, int) and gid >= 0:
  452. print_used_keys.add(_global_to_ams_key(gid))
  453. for change in getattr(state, "tray_change_log", None) or []:
  454. if isinstance(change, (tuple, list)) and len(change) >= 1:
  455. gid = change[0]
  456. if isinstance(gid, int) and gid >= 0:
  457. print_used_keys.add(_global_to_ams_key(gid))
  458. if session.tray_now_at_start is not None and session.tray_now_at_start >= 0:
  459. print_used_keys.add(_global_to_ams_key(session.tray_now_at_start))
  460. # Collect all trays to check: AMS trays + VT (external) trays
  461. # Each entry: (ams_id_for_assignment, tray_id_for_assignment, current_remain, label)
  462. trays_to_check: list[tuple[int, int, int, str]] = []
  463. for ams_unit in ams_data:
  464. ams_id = int(ams_unit.get("id", 0))
  465. for tray in ams_unit.get("tray", []):
  466. tray_id = int(tray.get("id", 0))
  467. remain = tray.get("remain", -1)
  468. trays_to_check.append((ams_id, tray_id, remain, f"AMS{ams_id}-T{tray_id}"))
  469. # VT (external) trays — same remain% delta logic
  470. vt_tray_raw = state.raw_data.get("vt_tray") or []
  471. if isinstance(vt_tray_raw, dict):
  472. vt_tray_raw = [vt_tray_raw]
  473. for vt in vt_tray_raw:
  474. if not isinstance(vt, dict):
  475. continue
  476. vt_id = int(vt.get("id", 254))
  477. vt_tray_id = vt_id - 254 # 254→0, 255→1
  478. remain = vt.get("remain", -1)
  479. trays_to_check.append((255, vt_tray_id, remain, f"VT{vt_id}"))
  480. for assign_ams_id, assign_tray_id, current_remain, tray_label in trays_to_check:
  481. key = (assign_ams_id, assign_tray_id)
  482. if key in handled_trays:
  483. continue # Already tracked via 3MF
  484. if key not in session.tray_remain_start:
  485. continue
  486. # Skip trays the print never touched. Only enforce when we have
  487. # evidence of which trays the print used; if print_used_keys is
  488. # empty (no mapping, no change log, no tray_now_at_start) keep
  489. # the legacy behavior of scanning every tray.
  490. if print_used_keys and key not in print_used_keys:
  491. logger.info(
  492. "[UsageTracker] %s: not in print mapping/tray_change_log — skipping fallback for printer %d",
  493. tray_label,
  494. printer_id,
  495. )
  496. continue
  497. if not isinstance(current_remain, int) or current_remain < 0 or current_remain > 100:
  498. logger.info(
  499. "[UsageTracker] %s: invalid remain%% at completion (%s), skipping fallback for printer %d",
  500. tray_label,
  501. current_remain,
  502. printer_id,
  503. )
  504. continue
  505. start_remain = session.tray_remain_start[key]
  506. delta_pct = start_remain - current_remain
  507. if delta_pct <= 0:
  508. continue # No consumption or tray was refilled
  509. spool_id = await _resolve_spool_id_for_tray(
  510. printer_id=printer_id,
  511. ams_id=assign_ams_id,
  512. tray_id=assign_tray_id,
  513. db=db,
  514. spool_assignments_snapshot=session.spool_assignments,
  515. print_started_at=session.started_at,
  516. )
  517. if spool_id is None:
  518. logger.info(
  519. "[UsageTracker] %s: no spool assigned, skipping fallback for printer %d",
  520. tray_label,
  521. printer_id,
  522. )
  523. continue
  524. # Load spool
  525. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  526. spool = spool_result.scalar_one_or_none()
  527. if not spool:
  528. continue
  529. # Compute weight consumed
  530. weight_grams = (delta_pct / 100.0) * spool.label_weight
  531. # Update spool
  532. spool.weight_used = (spool.weight_used or 0) + weight_grams
  533. spool.last_used = datetime.now(timezone.utc)
  534. # Calculate cost for this usage
  535. cost = None
  536. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  537. if cost_per_kg > 0:
  538. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  539. # Insert usage history record
  540. history = SpoolUsageHistory(
  541. spool_id=spool.id,
  542. printer_id=printer_id,
  543. print_name=session.print_name,
  544. weight_used=round(weight_grams, 1),
  545. percent_used=delta_pct,
  546. status=status,
  547. cost=cost,
  548. archive_id=archive_id,
  549. )
  550. db.add(history)
  551. handled_trays.add(key)
  552. results.append(
  553. {
  554. "spool_id": spool.id,
  555. "weight_used": round(weight_grams, 1),
  556. "percent_used": delta_pct,
  557. "ams_id": assign_ams_id,
  558. "tray_id": assign_tray_id,
  559. "material": spool.material,
  560. "cost": cost,
  561. # AMS remain%-delta fallback has no 3MF slot — slot_id
  562. # stays None so it is excluded from the colour rewrite.
  563. "slot_id": None,
  564. "color": _spool_color_to_hex(spool.rgba),
  565. }
  566. )
  567. logger.info(
  568. "[UsageTracker] Spool %d consumed %.1fg (%d%%) on printer %d %s (AMS fallback, %s)",
  569. spool.id,
  570. weight_grams,
  571. delta_pct,
  572. printer_id,
  573. tray_label,
  574. status,
  575. )
  576. if results:
  577. await db.commit()
  578. # --- Update PrintArchive.cost from THIS print session only ---
  579. #
  580. # Cover any filament weight that wasn't tracked by an inventory spool with
  581. # the global default rate (#1344). Without this, a multi-color print where
  582. # only some AMS trays are mapped to inventory spools would record only the
  583. # mapped slots' share — e.g. $0.01 for a 110g print when 3 of 4 trays had
  584. # no spool record. The initial cost set by archive.py (total grams *
  585. # primary cost_per_kg) is fine on its own, but this block overwrites it,
  586. # so the overwrite must reconstruct the whole-print cost.
  587. if archive_id and results:
  588. from sqlalchemy import func, select
  589. from backend.app.models.archive import PrintArchive
  590. from backend.app.models.print_log import PrintLogEntry
  591. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  592. archive = archive_result.scalar_one_or_none()
  593. if archive:
  594. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  595. tracked_grams = sum(r.get("weight_used", 0) or 0 for r in results)
  596. archive_grams = archive.filament_used_grams or 0
  597. untracked_grams = max(0.0, archive_grams - tracked_grams)
  598. if untracked_grams > 0 and default_filament_cost > 0:
  599. total_cost += (untracked_grams / 1000.0) * default_filament_cost
  600. if total_cost > 0:
  601. # Only overwrite archive.cost on the first run. Reprint actuals
  602. # live in PrintLogEntry; the archive card keeps the first run's
  603. # cost so a failed reprint doesn't visually clobber a successful
  604. # 100 g/$X print with a 10 g/$X/10 partial (#1378).
  605. _existing_runs_result = await db.execute(
  606. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  607. )
  608. _existing_runs = _existing_runs_result.scalar()
  609. if not _existing_runs:
  610. archive.cost = round(total_cost, 2)
  611. await db.commit()
  612. return results
  613. async def _resolve_3mf_fallback(archive, db: AsyncSession, base_dir):
  614. """Try to find a 3MF file from library or a previous archive when the current archive has none.
  615. This handles fallback archives (FTP download failed) where the 3MF may already exist
  616. locally from a library upload or a previous successful print of the same file.
  617. """
  618. from pathlib import Path
  619. from backend.app.models.archive import PrintArchive
  620. from backend.app.models.library import LibraryFile
  621. # Derive search name from archive filename (e.g. "benchy.3mf" or "benchy.gcode.3mf")
  622. search_name = archive.filename or archive.print_name
  623. if not search_name:
  624. return None
  625. # Normalize: strip path parts, get base name
  626. search_name = search_name.split("/")[-1]
  627. search_base = search_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  628. if not search_base:
  629. return None
  630. # 1. Try library files matching the name (match base name at file boundary)
  631. try:
  632. lib_result = await db.execute(
  633. LibraryFile.active()
  634. .where(LibraryFile.file_path.ilike(f"%/{search_base}.%") | LibraryFile.file_path.ilike(f"{search_base}.%"))
  635. .where(LibraryFile.file_path.ilike("%.3mf"))
  636. .order_by(LibraryFile.created_at.desc())
  637. .limit(3)
  638. )
  639. for lib_file in lib_result.scalars().all():
  640. lib_path = Path(lib_file.file_path)
  641. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  642. if candidate.exists() and candidate.suffix == ".3mf":
  643. logger.info("[UsageTracker] 3MF fallback: found library file %s for archive %s", candidate, archive.id)
  644. return candidate
  645. except Exception as e:
  646. logger.debug("[UsageTracker] 3MF fallback: library lookup failed: %s", e)
  647. # 2. Try previous archives with the same filename that have a valid file_path
  648. try:
  649. prev_result = await db.execute(
  650. select(PrintArchive)
  651. .where(PrintArchive.id != archive.id)
  652. .where(PrintArchive.printer_id == archive.printer_id)
  653. .where(PrintArchive.file_path != "")
  654. .where(PrintArchive.file_path.isnot(None))
  655. .where(
  656. PrintArchive.filename.ilike(f"%{search_base}.%") | PrintArchive.filename.ilike(f"{search_base}.%"),
  657. )
  658. .order_by(PrintArchive.created_at.desc())
  659. .limit(3)
  660. )
  661. for prev_archive in prev_result.scalars().all():
  662. candidate = base_dir / prev_archive.file_path
  663. if candidate.exists() and candidate.suffix == ".3mf":
  664. logger.info(
  665. "[UsageTracker] 3MF fallback: found previous archive %s file for archive %s",
  666. prev_archive.id,
  667. archive.id,
  668. )
  669. return candidate
  670. except Exception as e:
  671. logger.debug("[UsageTracker] 3MF fallback: previous archive lookup failed: %s", e)
  672. return None
  673. async def _find_3mf_by_filename(
  674. printer_id: int,
  675. filename: str,
  676. db: AsyncSession,
  677. base_dir,
  678. ):
  679. """Find a 3MF file by filename from library or previous archives.
  680. Used when auto-archive is disabled and there's no archive_id, but we still
  681. need the 3MF slicer data for filament usage tracking.
  682. """
  683. from pathlib import Path
  684. from backend.app.models.archive import PrintArchive
  685. from backend.app.models.library import LibraryFile
  686. search_name = filename.split("/")[-1] if "/" in filename else filename
  687. search_base = search_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  688. if not search_base:
  689. return None
  690. # 1. Try library files matching the name
  691. try:
  692. lib_result = await db.execute(
  693. LibraryFile.active()
  694. .where(LibraryFile.file_path.ilike(f"%/{search_base}.%") | LibraryFile.file_path.ilike(f"{search_base}.%"))
  695. .where(LibraryFile.file_path.ilike("%.3mf"))
  696. .order_by(LibraryFile.created_at.desc())
  697. .limit(3)
  698. )
  699. for lib_file in lib_result.scalars().all():
  700. lib_path = Path(lib_file.file_path)
  701. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  702. if candidate.exists() and candidate.suffix == ".3mf":
  703. logger.info("[UsageTracker] 3MF (no-archive): found library file %s for '%s'", candidate, filename)
  704. return candidate
  705. except Exception as e:
  706. logger.debug("[UsageTracker] 3MF (no-archive): library lookup failed: %s", e)
  707. # 2. Try previous archives with a valid 3MF file_path
  708. try:
  709. prev_result = await db.execute(
  710. select(PrintArchive)
  711. .where(PrintArchive.printer_id == printer_id)
  712. .where(PrintArchive.file_path != "")
  713. .where(PrintArchive.file_path.isnot(None))
  714. .where(
  715. PrintArchive.filename.ilike(f"%{search_base}.%") | PrintArchive.filename.ilike(f"{search_base}.%"),
  716. )
  717. .order_by(PrintArchive.created_at.desc())
  718. .limit(3)
  719. )
  720. for prev_archive in prev_result.scalars().all():
  721. candidate = base_dir / prev_archive.file_path
  722. if candidate.exists() and candidate.suffix == ".3mf":
  723. logger.info(
  724. "[UsageTracker] 3MF (no-archive): found previous archive %s file for '%s'",
  725. prev_archive.id,
  726. filename,
  727. )
  728. return candidate
  729. except Exception as e:
  730. logger.debug("[UsageTracker] 3MF (no-archive): previous archive lookup failed: %s", e)
  731. return None
  732. async def _track_from_3mf(
  733. printer_id: int,
  734. archive_id: int | None,
  735. status: str,
  736. print_name: str,
  737. handled_trays: set[tuple[int, int]],
  738. printer_manager,
  739. db: AsyncSession,
  740. ams_mapping: list[int] | None = None,
  741. tray_now_at_start: int = -1,
  742. last_progress: float = 0.0,
  743. last_layer_num: int = 0,
  744. default_filament_cost: float = 0.0,
  745. spool_assignments: dict[tuple[int, int], int] | None = None,
  746. print_started_at: datetime | None = None,
  747. threemf_path=None,
  748. plate_id: int | None = None,
  749. ) -> list[dict]:
  750. """Track usage from 3MF per-filament slicer data (primary path).
  751. Uses slicer-estimated filament weight for all spools (BL and non-BL).
  752. For partial prints (failed/aborted), tries per-layer gcode data first,
  753. then falls back to linear scaling by progress.
  754. When archive_id is None (auto-archive disabled), a pre-resolved threemf_path
  755. can be provided to still track filament usage from slicer data.
  756. When ``plate_id`` is set (queue prints of a single plate from a multi-plate
  757. 3MF), only that plate's filaments contribute. Without it the 3MF parser sums
  758. every plate, which is correct for direct/library Print flows that always
  759. target the first or only plate (#1697).
  760. Slot-to-tray mapping priority:
  761. 1. Stored ams_mapping from print command (reprints/direct prints)
  762. 2. MQTT mapping field from printer state (universal, all print sources)
  763. 3. Queue item ams_mapping (for queue-initiated prints)
  764. 4. tray_now from printer state (for single-filament non-queue prints)
  765. 5. Position-based default using sorted available tray IDs (handles external spools)
  766. 6. Default mapping: slot_id - 1 = global_tray_id (last resort)
  767. """
  768. from pathlib import Path
  769. from backend.app.core.config import settings as app_settings
  770. from backend.app.models.archive import PrintArchive
  771. from backend.app.models.print_queue import PrintQueueItem
  772. from backend.app.utils.threemf_tools import extract_filament_usage_from_3mf
  773. file_path: Path | None = threemf_path
  774. archive: PrintArchive | None = None
  775. if file_path is None and archive_id:
  776. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  777. archive = result.scalar_one_or_none()
  778. if not archive:
  779. logger.info("[UsageTracker] 3MF: archive %s not found, skipping", archive_id)
  780. return []
  781. # Try archive's own file_path first
  782. if archive.file_path:
  783. candidate = app_settings.base_dir / archive.file_path
  784. if candidate.exists():
  785. file_path = candidate
  786. # Fallback: find 3MF from library or a previous archive with the same filename
  787. if file_path is None:
  788. file_path = await _resolve_3mf_fallback(archive, db, app_settings.base_dir)
  789. if file_path is None:
  790. logger.info("[UsageTracker] 3MF: no file available for archive %s, skipping", archive_id)
  791. return []
  792. filament_usage = extract_filament_usage_from_3mf(file_path, plate_id)
  793. if not filament_usage:
  794. logger.info("[UsageTracker] 3MF: no filament usage data in %s", file_path)
  795. return []
  796. logger.info("[UsageTracker] 3MF: archive %s, plate_id=%s, filament_usage=%s", archive_id, plate_id, filament_usage)
  797. # --- Resolve slot-to-tray mapping ---
  798. mapping_source = None
  799. # 1. Use stored ams_mapping from the print command (reprints/direct prints)
  800. slot_to_tray = ams_mapping
  801. if slot_to_tray:
  802. mapping_source = "print_cmd"
  803. # 2. Try MQTT mapping field from printer state (universal, all print sources)
  804. if not slot_to_tray:
  805. state = printer_manager.get_status(printer_id)
  806. raw_data = getattr(state, "raw_data", None) if state else None
  807. if raw_data:
  808. mqtt_mapping = raw_data.get("mapping")
  809. decoded = _decode_mqtt_mapping(mqtt_mapping)
  810. if decoded:
  811. slot_to_tray = decoded
  812. mapping_source = "mqtt"
  813. # 3. Try queue item ams_mapping (queue-initiated prints store the exact mapping)
  814. if not slot_to_tray and archive_id:
  815. queue_result = await db.execute(
  816. select(PrintQueueItem)
  817. .where(PrintQueueItem.archive_id == archive_id)
  818. .where(PrintQueueItem.status.in_(["printing", "completed", "failed"]))
  819. )
  820. queue_item = queue_result.scalar_one_or_none()
  821. if queue_item and queue_item.ams_mapping:
  822. try:
  823. slot_to_tray = json.loads(queue_item.ams_mapping)
  824. mapping_source = "queue"
  825. except (json.JSONDecodeError, TypeError):
  826. pass
  827. # 4. Color-match 3MF filament slots to AMS trays (for printers without mapping field)
  828. if not slot_to_tray:
  829. state = printer_manager.get_status(printer_id)
  830. raw_data = getattr(state, "raw_data", None) if state else None
  831. if raw_data:
  832. matched = _match_slots_by_color(filament_usage, raw_data.get("ams"))
  833. if matched:
  834. slot_to_tray = matched
  835. mapping_source = "color_match"
  836. logger.info(
  837. "[UsageTracker] 3MF: slot_to_tray=%s (source: %s)",
  838. slot_to_tray,
  839. mapping_source or "none",
  840. )
  841. # 5. For single-filament non-queue prints, use tray_now from printer state
  842. # Priority: tray_change_log (multi-tray split) > tray_now_at_start > current tray_now
  843. # > last_loaded_tray > vt_tray check
  844. #
  845. # tray_change_log evidence wins over slot_to_tray when present: if the
  846. # printer fed from multiple trays mid-print (AMS auto-fallback when one
  847. # spool runs out, #957), the slicer's mapping captured at print start
  848. # is stale and needs to be replaced with per-layer split attribution.
  849. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  850. tray_now_override: int | None = None
  851. tray_changes: list[tuple[int, int]] = [] # [(global_tray_id, layer_num), ...]
  852. state = printer_manager.get_status(printer_id) if len(nonzero_slots) == 1 else None
  853. if state is not None:
  854. tray_changes = getattr(state, "tray_change_log", []) or []
  855. if len(tray_changes) > 1:
  856. # Multi-tray usage detected — splitting takes over regardless of slot_to_tray.
  857. logger.info("[UsageTracker] 3MF: tray change log: %s (will split weight)", tray_changes)
  858. elif not slot_to_tray and len(nonzero_slots) == 1:
  859. if 0 <= tray_now_at_start <= 254:
  860. tray_now_override = tray_now_at_start
  861. logger.info("[UsageTracker] 3MF: using tray_now_at_start=%d (single-filament fallback)", tray_now_at_start)
  862. elif state and 0 <= state.tray_now <= 254:
  863. tray_now_override = state.tray_now
  864. logger.info("[UsageTracker] 3MF: using current tray_now=%d", state.tray_now)
  865. elif state and 0 <= state.last_loaded_tray <= 253:
  866. tray_now_override = state.last_loaded_tray
  867. logger.info("[UsageTracker] 3MF: using last_loaded_tray=%d (post-retract fallback)", state.last_loaded_tray)
  868. elif state and state.tray_now == 255:
  869. # 255 = "no filament" on legacy printers, but valid 2nd external spool on H2-series
  870. vt_tray = state.raw_data.get("vt_tray") or []
  871. if any(int(vt.get("id", 0)) == 255 for vt in vt_tray if isinstance(vt, dict)):
  872. tray_now_override = state.tray_now
  873. logger.info("[UsageTracker] 3MF: using tray_now=255 (H2-series external spool)")
  874. if tray_now_override is None:
  875. logger.info(
  876. "[UsageTracker] 3MF: no valid tray_now (at_start=%d, current=%s, last_loaded=%s)",
  877. tray_now_at_start,
  878. state.tray_now if state else "N/A",
  879. state.last_loaded_tray if state else "N/A",
  880. )
  881. # Scale factor for partial prints (failed/aborted)
  882. if status == "completed":
  883. scale = 1.0
  884. else:
  885. state = printer_manager.get_status(printer_id)
  886. progress = state.progress if state else 0
  887. # Firmware resets progress to 0 on cancel — use last valid progress captured during print
  888. if progress <= 0 and last_progress > 0:
  889. progress = last_progress
  890. logger.info("[UsageTracker] 3MF: using last_progress=%.1f (firmware reset current to 0)", last_progress)
  891. scale = max(0.0, min(progress / 100.0, 1.0))
  892. # Per-layer gcode accuracy for partial prints
  893. layer_grams: dict[int, float] | None = None
  894. if status != "completed":
  895. state = printer_manager.get_status(printer_id)
  896. current_layer = state.layer_num if state else 0
  897. # Firmware resets layer_num to 0 on cancel — use last valid layer captured during print
  898. if current_layer <= 0 and last_layer_num > 0:
  899. current_layer = last_layer_num
  900. logger.info("[UsageTracker] 3MF: using last_layer_num=%d (firmware reset current to 0)", last_layer_num)
  901. if current_layer > 0:
  902. try:
  903. from backend.app.utils.threemf_tools import (
  904. extract_filament_properties_from_3mf,
  905. extract_layer_filament_usage_from_3mf,
  906. get_cumulative_usage_at_layer,
  907. mm_to_grams,
  908. )
  909. layer_usage = extract_layer_filament_usage_from_3mf(file_path)
  910. if layer_usage:
  911. cumulative_mm = get_cumulative_usage_at_layer(layer_usage, current_layer)
  912. filament_props = extract_filament_properties_from_3mf(file_path)
  913. layer_grams = {}
  914. for filament_id, mm_used in cumulative_mm.items():
  915. slot_id = filament_id + 1 # 0-based to 1-based
  916. props = filament_props.get(slot_id, {})
  917. density = props.get("density", 1.24)
  918. diameter = props.get("diameter", 1.75)
  919. layer_grams[slot_id] = mm_to_grams(mm_used, diameter, density)
  920. except Exception:
  921. pass # Fall back to linear scaling
  922. results = []
  923. for usage in filament_usage:
  924. slot_id = usage.get("slot_id", 0)
  925. used_g = usage.get("used_g", 0)
  926. if used_g <= 0:
  927. continue
  928. # --- Mid-print tray switch: split weight across trays ---
  929. # Split math is shared with the Spoolman writer via
  930. # ``utils.tray_split.compute_tray_split_grams`` (#1793) — both
  931. # inventory backends must attribute segments identically or a
  932. # user running dual-mode sees divergent totals.
  933. if len(tray_changes) > 1:
  934. # Compute total weight for this slot (same logic as normal path)
  935. if layer_grams and slot_id in layer_grams:
  936. total_weight = layer_grams[slot_id]
  937. else:
  938. total_weight = used_g * scale
  939. if total_weight <= 0:
  940. continue
  941. # Extract per-layer gcode for segment splitting
  942. split_layer_usage = None
  943. split_props: dict = {}
  944. try:
  945. from backend.app.utils.threemf_tools import (
  946. extract_filament_properties_from_3mf,
  947. extract_layer_filament_usage_from_3mf,
  948. )
  949. split_layer_usage = extract_layer_filament_usage_from_3mf(file_path)
  950. filament_props = extract_filament_properties_from_3mf(file_path)
  951. split_props = filament_props.get(slot_id, {})
  952. except Exception:
  953. pass # Fall back to linear splitting
  954. from backend.app.utils.tray_split import compute_tray_split_grams
  955. segments = compute_tray_split_grams(
  956. tray_changes=tray_changes,
  957. total_weight=total_weight,
  958. slot_id=slot_id,
  959. layer_usage=split_layer_usage,
  960. density=split_props.get("density", 1.24),
  961. diameter=split_props.get("diameter", 1.75),
  962. total_layers=(state.total_layers if state else 0) or 0,
  963. last_layer_num=last_layer_num,
  964. )
  965. for seg_idx, tray_global, segment_grams in segments:
  966. if segment_grams <= 0:
  967. continue
  968. # Convert global tray ID to (ams_id, tray_id)
  969. if tray_global >= 254:
  970. seg_ams_id = 255
  971. seg_tray_id = tray_global - 254
  972. elif tray_global >= 128:
  973. seg_ams_id = tray_global
  974. seg_tray_id = 0
  975. else:
  976. seg_ams_id = tray_global // 4
  977. seg_tray_id = tray_global % 4
  978. seg_key = (seg_ams_id, seg_tray_id)
  979. if seg_key in handled_trays:
  980. continue
  981. seg_start_layer = tray_changes[seg_idx][1]
  982. is_last = seg_idx + 1 >= len(tray_changes)
  983. logger.info(
  984. "[UsageTracker] 3MF split: segment %d tray=%d (AMS%d-T%d) layers %d-%s -> %.1fg",
  985. seg_idx,
  986. tray_global,
  987. seg_ams_id,
  988. seg_tray_id,
  989. seg_start_layer,
  990. tray_changes[seg_idx + 1][1] if not is_last else "end",
  991. segment_grams,
  992. )
  993. seg_spool_id = await _resolve_spool_id_for_tray(
  994. printer_id=printer_id,
  995. ams_id=seg_ams_id,
  996. tray_id=seg_tray_id,
  997. db=db,
  998. spool_assignments_snapshot=spool_assignments,
  999. print_started_at=print_started_at,
  1000. )
  1001. if seg_spool_id is None:
  1002. logger.info(
  1003. "[UsageTracker] 3MF split: no spool at printer %d AMS%d-T%d, skipping segment",
  1004. printer_id,
  1005. seg_ams_id,
  1006. seg_tray_id,
  1007. )
  1008. continue
  1009. spool_result = await db.execute(select(Spool).where(Spool.id == seg_spool_id))
  1010. spool = spool_result.scalar_one_or_none()
  1011. if not spool:
  1012. continue
  1013. spool.weight_used = (spool.weight_used or 0) + segment_grams
  1014. spool.last_used = datetime.now(timezone.utc)
  1015. percent = round(segment_grams / (spool.label_weight or 1000) * 100)
  1016. cost = None
  1017. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1018. if cost_per_kg > 0:
  1019. cost = round((segment_grams / 1000.0) * cost_per_kg, 2)
  1020. history = SpoolUsageHistory(
  1021. spool_id=spool.id,
  1022. printer_id=printer_id,
  1023. print_name=print_name,
  1024. weight_used=round(segment_grams, 1),
  1025. percent_used=percent,
  1026. status=status,
  1027. cost=cost,
  1028. archive_id=archive_id,
  1029. )
  1030. db.add(history)
  1031. handled_trays.add(seg_key)
  1032. results.append(
  1033. {
  1034. "spool_id": spool.id,
  1035. "weight_used": round(segment_grams, 1),
  1036. "percent_used": percent,
  1037. "ams_id": seg_ams_id,
  1038. "tray_id": seg_tray_id,
  1039. "material": spool.material,
  1040. "cost": cost,
  1041. "slot_id": slot_id,
  1042. "color": _spool_color_to_hex(spool.rgba),
  1043. }
  1044. )
  1045. logger.info(
  1046. "[UsageTracker] Spool %d consumed %.1fg (3MF split seg%d) on printer %d AMS%d-T%d (%s)",
  1047. spool.id,
  1048. segment_grams,
  1049. seg_idx,
  1050. printer_id,
  1051. seg_ams_id,
  1052. seg_tray_id,
  1053. status,
  1054. )
  1055. continue # Skip normal single-tray processing for this slot
  1056. # Map 3MF slot_id to physical (ams_id, tray_id) using resolved mapping
  1057. if tray_now_override is not None:
  1058. # Single-filament non-queue print: use actual tray from printer state
  1059. global_tray_id = tray_now_override
  1060. else:
  1061. # Explicit mapping (print command, MQTT, queue, color match)
  1062. global_tray_id = None
  1063. if slot_to_tray and slot_id <= len(slot_to_tray):
  1064. mapped = slot_to_tray[slot_id - 1]
  1065. if isinstance(mapped, int) and mapped >= 0:
  1066. global_tray_id = mapped
  1067. # Position-based default: sort available tray IDs so external spools (254/255)
  1068. # naturally follow standard AMS trays, matching slicer slot numbering.
  1069. #
  1070. # Filter out AMS slots that have no spool loaded (empty `tray_type`) —
  1071. # BambuStudio/OrcaSlicer compact the slot list when assigning filaments
  1072. # and don't expose empty AMS slots to the user, so the slicer's 3MF
  1073. # slot N maps to the Nth *loaded* tray, not the Nth physical position.
  1074. # Without this filter a "3 AMS slots loaded + 1 empty + external"
  1075. # layout routes the slicer's 4th filament to the empty AMS slot
  1076. # instead of the external (#1607), and the external's spool usage
  1077. # never gets recorded. vt_tray entries are already filtered the
  1078. # same way inside `build_ams_tray_lookup` (line 174 checks
  1079. # `tray_type`), so this just mirrors that for the AMS side.
  1080. if global_tray_id is None:
  1081. _state = printer_manager.get_status(printer_id)
  1082. _raw = getattr(_state, "raw_data", None) if _state else None
  1083. if _raw:
  1084. from backend.app.services.spoolman_tracking import build_ams_tray_lookup
  1085. _lookup = build_ams_tray_lookup(_raw)
  1086. available_trays = sorted(gid for gid, info in _lookup.items() if info.get("tray_type"))
  1087. if slot_id <= len(available_trays):
  1088. global_tray_id = available_trays[slot_id - 1]
  1089. # Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools)
  1090. if global_tray_id is None:
  1091. global_tray_id = slot_id - 1
  1092. if global_tray_id >= 254:
  1093. # External spool: ams_id=255 (sentinel), tray_id=slot index (0 or 1)
  1094. ams_id = 255
  1095. tray_id = global_tray_id - 254
  1096. elif global_tray_id >= 128:
  1097. ams_id = global_tray_id
  1098. tray_id = 0
  1099. else:
  1100. ams_id = global_tray_id // 4
  1101. tray_id = global_tray_id % 4
  1102. logger.info(
  1103. "[UsageTracker] 3MF: slot_id=%d -> global_tray=%d -> AMS%d-T%d (used_g=%.1f, tray_now_override=%s)",
  1104. slot_id,
  1105. global_tray_id,
  1106. ams_id,
  1107. tray_id,
  1108. used_g,
  1109. tray_now_override,
  1110. )
  1111. key = (ams_id, tray_id)
  1112. if key in handled_trays:
  1113. continue
  1114. spool_id = await _resolve_spool_id_for_tray(
  1115. printer_id=printer_id,
  1116. ams_id=ams_id,
  1117. tray_id=tray_id,
  1118. db=db,
  1119. spool_assignments_snapshot=spool_assignments,
  1120. print_started_at=print_started_at,
  1121. )
  1122. if spool_id is None:
  1123. logger.info("[UsageTracker] 3MF: no spool assignment at printer %d AMS%d-T%d", printer_id, ams_id, tray_id)
  1124. continue
  1125. # Load spool
  1126. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1127. spool = spool_result.scalar_one_or_none()
  1128. if not spool:
  1129. continue
  1130. # Use per-layer grams if available, otherwise linear scale
  1131. if layer_grams and slot_id in layer_grams:
  1132. weight_grams = layer_grams[slot_id]
  1133. else:
  1134. weight_grams = used_g * scale
  1135. if weight_grams <= 0:
  1136. continue
  1137. # Update spool
  1138. spool.weight_used = (spool.weight_used or 0) + weight_grams
  1139. spool.last_used = datetime.now(timezone.utc)
  1140. percent = round(weight_grams / (spool.label_weight or 1000) * 100)
  1141. # Calculate cost for this usage
  1142. cost = None
  1143. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1144. if cost_per_kg > 0:
  1145. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  1146. # Insert usage history record
  1147. history = SpoolUsageHistory(
  1148. spool_id=spool.id,
  1149. printer_id=printer_id,
  1150. print_name=print_name,
  1151. weight_used=round(weight_grams, 1),
  1152. percent_used=percent,
  1153. status=status,
  1154. cost=cost,
  1155. archive_id=archive_id,
  1156. )
  1157. db.add(history)
  1158. handled_trays.add(key)
  1159. results.append(
  1160. {
  1161. "spool_id": spool.id,
  1162. "weight_used": round(weight_grams, 1),
  1163. "percent_used": percent,
  1164. "ams_id": ams_id,
  1165. "tray_id": tray_id,
  1166. "material": spool.material,
  1167. "cost": cost,
  1168. "slot_id": slot_id,
  1169. "color": _spool_color_to_hex(spool.rgba),
  1170. }
  1171. )
  1172. # Determine mapping source for debug logging
  1173. if tray_now_override is not None:
  1174. map_src = ", tray_now"
  1175. elif mapping_source:
  1176. map_src = f", {mapping_source}_map"
  1177. else:
  1178. map_src = ""
  1179. logger.info(
  1180. "[UsageTracker] Spool %d consumed %.1fg (3MF%s%s) on printer %d AMS%d-T%d (%s)",
  1181. spool.id,
  1182. weight_grams,
  1183. " per-layer" if (layer_grams and slot_id in layer_grams) else (f" scaled {scale:.0%}" if scale < 1 else ""),
  1184. map_src,
  1185. printer_id,
  1186. ams_id,
  1187. tray_id,
  1188. status,
  1189. )
  1190. # --- Adopt the matched inventory spools' colours for the archive (#1494) ---
  1191. # The archive's filament_color was set from the slicer's 3MF at creation
  1192. # time; now that every used slot has been resolved to an inventory spool,
  1193. # the curated spool colour is authoritative. Committed by the caller's
  1194. # `if results: await db.commit()`.
  1195. if archive is not None:
  1196. spool_colors = _archive_colors_from_spools(filament_usage, results)
  1197. if spool_colors:
  1198. joined = ",".join(spool_colors)
  1199. if joined != archive.filament_color:
  1200. logger.info(
  1201. "[UsageTracker] 3MF: archive %s filament_color %r -> %r (from inventory spools)",
  1202. archive_id,
  1203. archive.filament_color,
  1204. joined,
  1205. )
  1206. archive.filament_color = joined
  1207. return results