usage_tracker.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  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 asyncio
  8. import json
  9. import logging
  10. import re
  11. from dataclasses import dataclass, field
  12. from datetime import datetime, timezone
  13. from sqlalchemy import func, select, update
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from backend.app.models.spool import Spool
  16. from backend.app.models.spool_assignment import SpoolAssignment
  17. from backend.app.models.spool_usage_history import SpoolUsageHistory
  18. from backend.app.services import spool_swaps
  19. logger = logging.getLogger(__name__)
  20. def _decode_mqtt_mapping(mapping_raw: list | None) -> list[int] | None:
  21. """Decode MQTT mapping field (snow-encoded) to bambuddy global tray IDs.
  22. The printer's MQTT mapping field is an array indexed by slicer filament slot
  23. (0-based). Each value uses snow encoding: ams_hw_id * 256 + local_slot.
  24. 65535 means unmapped.
  25. Returns a list of bambuddy global tray IDs (or -1 for unmapped), or None if
  26. no valid mappings found.
  27. """
  28. if not isinstance(mapping_raw, list) or not mapping_raw:
  29. return None
  30. result = []
  31. for value in mapping_raw:
  32. if not isinstance(value, int) or value >= 65535:
  33. result.append(-1)
  34. continue
  35. ams_hw_id = value >> 8
  36. slot = value & 0xFF
  37. if 0 <= ams_hw_id <= 3:
  38. # Regular AMS: sequential global ID
  39. result.append(ams_hw_id * 4 + (slot & 0x03))
  40. elif 128 <= ams_hw_id <= 135:
  41. # AMS-HT: global ID is the hardware ID (one slot per unit)
  42. result.append(ams_hw_id)
  43. elif ams_hw_id in (254, 255):
  44. # External spool
  45. result.append(254 if slot != 255 else 255)
  46. else:
  47. result.append(-1)
  48. # Only return if at least one valid mapping exists
  49. if all(v < 0 for v in result):
  50. return None
  51. return result
  52. def _spool_color_to_hex(rgba: str | None) -> str | None:
  53. """Normalise a ``Spool.rgba`` value (``RRGGBBAA`` hex, no ``#``) to the
  54. ``#RRGGBB`` form archives store in ``filament_color``.
  55. Alpha is dropped — the archive colour list and the Color Distribution
  56. graph treat filament colour as opaque. Returns ``None`` for a missing or
  57. too-short value so the caller can fall back to the 3MF colour.
  58. """
  59. if not rgba:
  60. return None
  61. h = rgba.strip().lstrip("#")
  62. if len(h) < 6:
  63. return None
  64. return "#" + h[:6].upper()
  65. def _archive_colors_from_spools(filament_usage: list[dict], results: list[dict]) -> list[str] | None:
  66. """Slot-ordered, de-duplicated hex colours for an archive's ``filament_color``,
  67. taken from the inventory spools that actually fed the print (#1494).
  68. The slicer's 3MF carries its own ``filament_colour`` per slot — a value
  69. picked independently of the colour the user curates on the matched
  70. inventory spool. So an archive printed from a ``#000000`` inventory spool
  71. would otherwise show the slicer's near-black ``#161616``. Once usage
  72. tracking has resolved the used slots to spools, the spool colours are the
  73. authoritative source and replace the 3MF values.
  74. Returns ``None`` — leave the 3MF colour untouched — unless *every* slot
  75. with non-zero usage was matched to a spool that carries a colour. A
  76. partial rewrite would silently drop the unmatched slots' colours from the
  77. archive (and the Color Distribution graph), so it is all-or-nothing.
  78. """
  79. 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}
  80. if not used_slots:
  81. return None
  82. slot_color: dict[int, str] = {}
  83. for r in results:
  84. slot_id = r.get("slot_id")
  85. color = r.get("color")
  86. if slot_id is not None and color:
  87. slot_color.setdefault(slot_id, color)
  88. if not used_slots.issubset(slot_color):
  89. return None
  90. ordered: list[str] = []
  91. for slot_id in sorted(used_slots):
  92. color = slot_color[slot_id]
  93. if color not in ordered:
  94. ordered.append(color)
  95. return ordered
  96. def _archive_types_from_spools(filament_usage: list[dict], results: list[dict]) -> list[str] | None:
  97. """Slot-ordered, de-duplicated materials for an archive's ``filament_type``,
  98. taken from the inventory spools that actually fed the print (#2563).
  99. The slicer's 3MF records the filament type it was *sliced for*. When the
  100. user manually maps a slot to a differently-typed loaded spool in the Print
  101. dialog — a PLA slice routed to the only loaded PETG slot — that sliced type
  102. misclassifies the run in the archive card, the Print Log and the material
  103. statistics, even though the deduction correctly hit the PETG spool. Once
  104. usage tracking has resolved every used slot to an inventory spool, the
  105. spool's declared material is the authoritative record of what was consumed,
  106. the same reasoning that already adopts the spool colour (#1494).
  107. Returns ``None`` — leave the 3MF type untouched — unless *every* slot with
  108. non-zero usage was matched to a spool that carries a material. All-or-
  109. nothing, exactly like ``_archive_colors_from_spools``: a partial rewrite
  110. would silently drop the unmatched slots' types from the archive (and the
  111. material stats).
  112. """
  113. 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}
  114. if not used_slots:
  115. return None
  116. slot_material: dict[int, str] = {}
  117. for r in results:
  118. slot_id = r.get("slot_id")
  119. material = (r.get("material") or "").strip()
  120. if slot_id is not None and material:
  121. slot_material.setdefault(slot_id, material)
  122. if not used_slots.issubset(slot_material):
  123. return None
  124. ordered: list[str] = []
  125. for slot_id in sorted(used_slots):
  126. material = slot_material[slot_id]
  127. if material not in ordered:
  128. ordered.append(material)
  129. return ordered
  130. def _match_slots_by_color(
  131. filament_usage: list[dict],
  132. ams_raw: dict | list | None,
  133. ) -> list[int] | None:
  134. """Match 3MF filament slots to AMS trays by color.
  135. Fallback mapping for printers that don't provide the MQTT mapping field
  136. or request topic subscription (e.g. A1, A1 Mini, P1S, P2S).
  137. Compares the 3MF slicer filament color (per slot) against each AMS tray's
  138. color to find a unique match. Only returns a mapping if every used slot
  139. matches exactly one tray (no ambiguity).
  140. Args:
  141. filament_usage: List of 3MF slot dicts with 'slot_id', 'color', 'type'
  142. ams_raw: raw_data["ams"] dict or list from printer state
  143. Returns:
  144. List of global tray IDs indexed by slicer slot (0-based), or None.
  145. """
  146. if not filament_usage or not ams_raw:
  147. return None
  148. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  149. if not ams_data:
  150. return None
  151. # Build map of normalized color → list of global tray IDs
  152. color_to_trays: dict[str, list[int]] = {}
  153. for ams_unit in ams_data:
  154. ams_id = int(ams_unit.get("id", 0))
  155. for tray in ams_unit.get("tray", []):
  156. tray_id = int(tray.get("id", 0))
  157. tray_color = tray.get("tray_color", "")
  158. tray_type = tray.get("tray_type", "")
  159. if not tray_color or not tray_type:
  160. continue
  161. # Normalize AMS color: strip alpha (last 2 chars), lowercase
  162. norm = tray_color[:6].lower() if len(tray_color) >= 6 else tray_color.lower()
  163. if ams_id >= 128:
  164. global_id = ams_id # AMS-HT
  165. else:
  166. global_id = ams_id * 4 + tray_id
  167. color_to_trays.setdefault(norm, []).append(global_id)
  168. if not color_to_trays:
  169. return None
  170. # Find max slot_id to size the result array
  171. max_slot = max(u.get("slot_id", 0) for u in filament_usage)
  172. if max_slot <= 0:
  173. return None
  174. result = [-1] * max_slot
  175. used_trays: set[int] = set()
  176. for usage in filament_usage:
  177. slot_id = usage.get("slot_id", 0)
  178. if slot_id <= 0:
  179. continue
  180. slot_color = usage.get("color", "").lstrip("#").lower()
  181. if len(slot_color) < 6:
  182. return None # Can't match without a valid color
  183. slot_color = slot_color[:6] # Strip alpha if present
  184. candidates = color_to_trays.get(slot_color, [])
  185. # Filter out trays already claimed by another slot
  186. available = [t for t in candidates if t not in used_trays]
  187. if len(available) != 1:
  188. # Ambiguous (multiple trays with same color) or no match
  189. return None
  190. result[slot_id - 1] = available[0]
  191. used_trays.add(available[0])
  192. # Only return if at least one valid mapping exists
  193. if all(v < 0 for v in result):
  194. return None
  195. logger.info("[UsageTracker] Color-matched slot_to_tray: %s", result)
  196. return result
  197. @dataclass
  198. class PrintSession:
  199. printer_id: int
  200. print_name: str
  201. started_at: datetime
  202. tray_remain_start: dict[tuple[int, int], int] = field(default_factory=dict)
  203. # tray_now at print start (correct value, unlike at completion where it's 255)
  204. tray_now_at_start: int = -1
  205. # Snapshot of spool assignments at print start: {(ams_id, tray_id): spool_id}
  206. # Prevents usage loss when on_ams_change unlinks a spool mid-print
  207. spool_assignments: dict[tuple[int, int], int] = field(default_factory=dict)
  208. # AMS mapping from print command (captured at start, needed when auto-archive is off)
  209. ams_mapping: list[int] | None = None
  210. # Queue item's plate_id when this print is a multi-plate 3MF dispatched for a
  211. # single plate (#1697). None for non-queue prints — the file's first/only plate
  212. # is the default and the 3MF parser already returns the full file in that case.
  213. plate_id: int | None = None
  214. # Module-level storage, keyed by printer_id. Mirrored to the
  215. # ``active_print_sessions`` table so a restart mid-print doesn't lose the
  216. # context — see ``persist_session`` / ``restore_session``.
  217. _active_sessions: dict[int, PrintSession] = {}
  218. # Printers whose finished print is being closed out. on_print_complete takes the
  219. # session first and charges the usage several awaits later; the printer already
  220. # reports FINISH, so without this mark the AMS remain% weight sync would run in
  221. # between and the print would be charged twice (WU-3).
  222. _completing: set[int] = set()
  223. def mark_completing(printer_id: int) -> None:
  224. """The completion path's first step: hold the weight sync off until the
  225. usage is booked (discard_session) or the completion ends."""
  226. _completing.add(printer_id)
  227. def done_completing(printer_id: int) -> None:
  228. _completing.discard(printer_id)
  229. def is_completing(printer_id: int) -> bool:
  230. """The printer's finished print is being closed out (on_print_complete runs)."""
  231. return printer_id in _completing
  232. def printer_is_charging(printer_id: int) -> bool:
  233. """A print's usage is still to be charged: it runs, or it ended and its
  234. completion has not booked it yet. The AMS remain% sync leaves the
  235. printer's spools alone meanwhile (#880)."""
  236. return printer_id in _active_sessions or printer_id in _completing
  237. # Serialises the read-modify-write on the persisted tray-change log, per printer.
  238. _tray_change_locks: dict[int, asyncio.Lock] = {}
  239. def _tray_key_to_str(key: tuple[int, int]) -> str:
  240. return f"{key[0]}-{key[1]}"
  241. def _tray_key_from_str(key: str) -> tuple[int, int] | None:
  242. ams_str, _, tray_str = key.partition("-")
  243. try:
  244. return int(ams_str), int(tray_str)
  245. except ValueError:
  246. return None
  247. def _tray_map_to_json(mapping: dict[tuple[int, int], int]) -> dict[str, int]:
  248. return {_tray_key_to_str(k): v for k, v in mapping.items()}
  249. def _tray_map_from_json(mapping: dict | None) -> dict[tuple[int, int], int]:
  250. result: dict[tuple[int, int], int] = {}
  251. for raw_key, value in (mapping or {}).items():
  252. key = _tray_key_from_str(str(raw_key))
  253. if key is not None and isinstance(value, int):
  254. result[key] = value
  255. return result
  256. async def _charge_spool(db: AsyncSession, spool: Spool, grams: float) -> bool:
  257. """Add *grams* to the spool's usage in the database itself (WU-4).
  258. The spool was loaded several awaits earlier; a weight set by hand or
  259. weighed on the scale since then would be lost to a write of the value
  260. computed from that copy. The loaded copy is set to the stored result: from
  261. this statement until the commit, the transaction holds the row (the write
  262. lock on SQLite), so writing it back on flush changes nothing.
  263. False when the spool was deleted meanwhile: the caller skips it, since a
  264. usage row for it would break its foreign key on PostgreSQL and roll back
  265. the whole completion.
  266. """
  267. now = datetime.now(timezone.utc)
  268. stored = await db.scalar(
  269. update(Spool)
  270. .where(Spool.id == spool.id)
  271. .values(weight_used=func.coalesce(Spool.weight_used, 0) + grams, last_used=now)
  272. .returning(Spool.weight_used)
  273. .execution_options(synchronize_session=False)
  274. )
  275. if stored is None:
  276. return False
  277. spool.weight_used = stored
  278. spool.last_used = now
  279. return True
  280. async def persist_session(
  281. db: AsyncSession,
  282. session: PrintSession,
  283. tray_change_log: list | None = None,
  284. spool_change_log: list | None = None,
  285. ) -> None:
  286. """Mirror ``session`` into ``active_print_sessions`` for restart recovery.
  287. Overwrites any existing row for the printer: a printer runs one print at a
  288. time, and a row left behind by a completion we never saw must not outlive
  289. the next print start.
  290. """
  291. from backend.app.models.active_print_session import ActivePrintSession
  292. row = await db.get(ActivePrintSession, session.printer_id)
  293. if row is None:
  294. row = ActivePrintSession(printer_id=session.printer_id)
  295. db.add(row)
  296. row.print_name = session.print_name or ""
  297. row.started_at = session.started_at.replace(tzinfo=None)
  298. row.tray_now_at_start = session.tray_now_at_start
  299. row.plate_id = session.plate_id
  300. row.ams_mapping = list(session.ams_mapping) if session.ams_mapping else None
  301. row.spool_assignments = _tray_map_to_json(session.spool_assignments) or None
  302. row.tray_remain_start = _tray_map_to_json(session.tray_remain_start) or None
  303. row.tray_change_log = [list(entry) for entry in (tray_change_log or [])] or None
  304. row.spool_change_log = list(spool_change_log or []) or None
  305. await db.commit()
  306. async def record_tray_change(db: AsyncSession, printer_id: int, tray_global: int, layer_num: int) -> None:
  307. """Append one tray change to the persisted log.
  308. No-op when no print-start row exists — a tray change outside a tracked
  309. print has nothing to attribute.
  310. """
  311. from backend.app.models.active_print_session import ActivePrintSession
  312. # Read-modify-write on a JSON column: two changes close together (a runout
  313. # parks the extruder and the backup tray loads moments later) would
  314. # otherwise race and drop a segment boundary.
  315. async with _tray_change_locks.setdefault(printer_id, asyncio.Lock()):
  316. row = await db.get(ActivePrintSession, printer_id)
  317. if row is None:
  318. return
  319. log = [list(entry) for entry in (row.tray_change_log or [])]
  320. entry = [tray_global, layer_num]
  321. if log and log[-1] == entry:
  322. # print-start seeds the log from PrinterState, which may already
  323. # hold a change this callback is also reporting.
  324. return
  325. log.append(entry)
  326. row.tray_change_log = log
  327. await db.commit()
  328. async def get_persisted_print_name(db: AsyncSession, printer_id: int) -> str | None:
  329. """Print name on the persisted row, for identity-checking a restored session."""
  330. from backend.app.models.active_print_session import ActivePrintSession
  331. row = await db.get(ActivePrintSession, printer_id)
  332. return row.print_name if row is not None else None
  333. async def get_persisted_spool_change_log(db: AsyncSession, printer_id: int) -> list[dict]:
  334. """The mid-print spool assignments on the persisted row (services.spool_swaps)."""
  335. from backend.app.models.active_print_session import ActivePrintSession
  336. row = await db.get(ActivePrintSession, printer_id)
  337. return [item for item in (row.spool_change_log or []) if isinstance(item, dict)] if row is not None else []
  338. async def get_persisted_ams_mapping(db: AsyncSession, printer_id: int) -> list[int] | None:
  339. """AMS mapping on the persisted row: the one captured from the print command."""
  340. from backend.app.models.active_print_session import ActivePrintSession
  341. row = await db.get(ActivePrintSession, printer_id)
  342. return list(row.ams_mapping) if row is not None and row.ams_mapping else None
  343. async def restore_session(db: AsyncSession, printer_id: int, register_active: bool = True) -> list[list[int]] | None:
  344. """Rebuild the in-memory session for ``printer_id`` from the persisted row.
  345. Returns the persisted tray-change log so the caller can put it back on
  346. ``PrinterState``, or None when there is nothing to restore.
  347. ``register_active=False`` returns the log without publishing the session to
  348. ``_active_sessions`` — for Spoolman users, who need the tray-change log
  349. restored but whose remain%-sync must not be suppressed by it (see
  350. ``on_print_start``).
  351. """
  352. from backend.app.models.active_print_session import ActivePrintSession
  353. row = await db.get(ActivePrintSession, printer_id)
  354. if row is None:
  355. return None
  356. started_at = row.started_at
  357. if started_at.tzinfo is None:
  358. started_at = started_at.replace(tzinfo=timezone.utc)
  359. session = PrintSession(
  360. printer_id=printer_id,
  361. print_name=row.print_name or "",
  362. started_at=started_at,
  363. tray_remain_start=_tray_map_from_json(row.tray_remain_start),
  364. tray_now_at_start=row.tray_now_at_start,
  365. spool_assignments=_tray_map_from_json(row.spool_assignments),
  366. ams_mapping=list(row.ams_mapping) if row.ams_mapping else None,
  367. plate_id=row.plate_id,
  368. )
  369. if register_active:
  370. _active_sessions[printer_id] = session
  371. log = [list(entry) for entry in (row.tray_change_log or [])]
  372. logger.info(
  373. "[UsageTracker] Restored print session for printer %d: plate_id=%s, ams_mapping=%s, "
  374. "%d assignments, tray_change_log=%s",
  375. printer_id,
  376. row.plate_id,
  377. row.ams_mapping,
  378. len(row.spool_assignments or {}),
  379. log,
  380. )
  381. return log
  382. async def clear_persisted_session(db: AsyncSession, printer_id: int) -> None:
  383. """Drop the persisted print-start row once the print is closed out."""
  384. from backend.app.models.active_print_session import ActivePrintSession
  385. row = await db.get(ActivePrintSession, printer_id)
  386. if row is not None:
  387. await db.delete(row)
  388. await db.commit()
  389. def forget_printer(printer_id: int) -> None:
  390. """A deleted printer's print-start context in memory (the row goes with the printer)."""
  391. _active_sessions.pop(printer_id, None)
  392. _completing.discard(printer_id)
  393. _tray_change_locks.pop(printer_id, None)
  394. async def discard_session(db: AsyncSession, printer_id: int) -> None:
  395. """Forget a printer's print-start context, in memory and on disk.
  396. The completion path calls this for every print, including the ones whose
  397. usage Spoolman owns: the context is captured for both backends, but only
  398. the internal tracker's ``on_print_complete`` consumes (and pops) it.
  399. """
  400. _active_sessions.pop(printer_id, None)
  401. _completing.discard(printer_id)
  402. _tray_change_locks.pop(printer_id, None)
  403. await clear_persisted_session(db, printer_id)
  404. def _to_epoch_seconds(value: datetime | None) -> float | None:
  405. """Convert datetime to epoch seconds, assuming UTC for naive values."""
  406. if value is None:
  407. return None
  408. dt = value
  409. if dt.tzinfo is None:
  410. dt = dt.replace(tzinfo=timezone.utc)
  411. return dt.timestamp()
  412. async def _resolve_spool_id_for_tray(
  413. printer_id: int,
  414. ams_id: int,
  415. tray_id: int,
  416. db: AsyncSession,
  417. spool_assignments_snapshot: dict[tuple[int, int], int] | None = None,
  418. print_started_at: datetime | None = None,
  419. ) -> int | None:
  420. """Resolve spool ID for a tray with safe support for mid-print reassignment.
  421. Resolution order:
  422. 1. If snapshot exists and live assignment changed *during this print*, use live spool.
  423. 2. Otherwise use snapshot spool when available.
  424. 3. Fall back to live assignment.
  425. """
  426. key = (ams_id, tray_id)
  427. snapshot_spool_id = spool_assignments_snapshot.get(key) if spool_assignments_snapshot else None
  428. # Backward-compatible fast path: if we have a snapshot but no print-start
  429. # timestamp, preserve legacy behavior and avoid extra DB lookups.
  430. if snapshot_spool_id is not None and print_started_at is None:
  431. return snapshot_spool_id
  432. result = await db.execute(
  433. select(SpoolAssignment).where(
  434. SpoolAssignment.printer_id == printer_id,
  435. SpoolAssignment.ams_id == ams_id,
  436. SpoolAssignment.tray_id == tray_id,
  437. )
  438. )
  439. live_assignment = result.scalar_one_or_none()
  440. if snapshot_spool_id is not None:
  441. if live_assignment and live_assignment.spool_id != snapshot_spool_id:
  442. live_created_ts = _to_epoch_seconds(getattr(live_assignment, "created_at", None))
  443. started_ts = _to_epoch_seconds(print_started_at)
  444. if live_created_ts is not None and started_ts is not None and live_created_ts >= started_ts:
  445. logger.info(
  446. "[UsageTracker] Assignment changed during print for printer %d AMS%d-T%d: snapshot spool %d -> live spool %d",
  447. printer_id,
  448. ams_id,
  449. tray_id,
  450. snapshot_spool_id,
  451. live_assignment.spool_id,
  452. )
  453. return live_assignment.spool_id
  454. return snapshot_spool_id
  455. if live_assignment:
  456. return live_assignment.spool_id
  457. return None
  458. async def on_print_start(
  459. printer_id: int,
  460. data: dict,
  461. printer_manager,
  462. db: AsyncSession | None = None,
  463. spoolman_owns_usage: bool = False,
  464. ) -> None:
  465. """Capture AMS tray remain% and spool assignments at print start.
  466. The capture runs for both inventory backends — the persisted row carries
  467. the tray-change log, which is the only record of which spool fed which
  468. layers when AMS Filament Backup swaps trays, and Spoolman's own durable
  469. row (#1820) does not hold it.
  470. ``spoolman_owns_usage`` keeps the in-memory session out of
  471. ``_active_sessions`` when Spoolman is writing the usage. That dict doubles
  472. as ``on_ams_change``'s "a print is running, so skip the remain%-based
  473. weight sync because the internal tracker will deduct precisely" flag
  474. (#880); registering a session the internal tracker will never complete
  475. would suppress a sync those users still need.
  476. """
  477. # A new print: whatever the last completion left marked is over.
  478. _completing.discard(printer_id)
  479. state = printer_manager.get_status(printer_id)
  480. if not state or not state.raw_data:
  481. logger.debug("[UsageTracker] No state for printer %d, skipping", printer_id)
  482. return
  483. ams_raw = state.raw_data.get("ams", [])
  484. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  485. tray_remain_start: dict[tuple[int, int], int] = {}
  486. skipped_invalid: list[str] = []
  487. for ams_unit in ams_data:
  488. ams_id = int(ams_unit.get("id", 0))
  489. for tray in ams_unit.get("tray", []):
  490. tray_id = int(tray.get("id", 0))
  491. remain = tray.get("remain", -1)
  492. if isinstance(remain, int) and 0 <= remain <= 100:
  493. tray_remain_start[(ams_id, tray_id)] = remain
  494. else:
  495. skipped_invalid.append(f"AMS{ams_id}-T{tray_id}(remain={remain})")
  496. # Also capture VT (external) tray remain% — these are separate from AMS units
  497. vt_tray_raw = state.raw_data.get("vt_tray") or []
  498. if isinstance(vt_tray_raw, dict):
  499. vt_tray_raw = [vt_tray_raw]
  500. for vt in vt_tray_raw:
  501. if not isinstance(vt, dict):
  502. continue
  503. vt_id = int(vt.get("id", 254))
  504. # VT tray id 254 → (ams_id=255, tray_id=0), id 255 → (ams_id=255, tray_id=1)
  505. vt_tray_id = vt_id - 254
  506. remain = vt.get("remain", -1)
  507. if isinstance(remain, int) and 0 <= remain <= 100:
  508. tray_remain_start[(255, vt_tray_id)] = remain
  509. else:
  510. skipped_invalid.append(f"VT{vt_id}(remain={remain})")
  511. if skipped_invalid:
  512. logger.info(
  513. "[UsageTracker] Skipped trays with invalid remain%% for printer %d: %s",
  514. printer_id,
  515. ", ".join(skipped_invalid),
  516. )
  517. if not ams_data and not vt_tray_raw:
  518. logger.debug("[UsageTracker] No AMS or VT tray data for printer %d, skipping", printer_id)
  519. return
  520. print_name = data.get("subtask_name", "") or data.get("filename", "unknown")
  521. # Capture tray_now at print start (reliable, unlike at completion where it's 255)
  522. tray_now_at_start = state.tray_now if state else -1
  523. # --- Diagnostic logging: dump mapping-related MQTT fields at print start ---
  524. # This helps us understand what each printer model reports for slot-to-tray mapping.
  525. mapping_field = state.raw_data.get("mapping")
  526. logger.info(
  527. "[UsageTracker] PRINT START printer %d: mapping=%s, tray_now=%d, last_loaded_tray=%s",
  528. printer_id,
  529. mapping_field,
  530. tray_now_at_start,
  531. getattr(state, "last_loaded_tray", "N/A"),
  532. )
  533. # Log all raw_data keys containing "map" or "ams" for discovery
  534. map_keys = {k: state.raw_data[k] for k in state.raw_data if "map" in k.lower()}
  535. if map_keys:
  536. logger.info("[UsageTracker] PRINT START printer %d: mapping-related keys: %s", printer_id, map_keys)
  537. # Log per-tray summary: tray_now, tray_tar, tray_type, tray_color for each slot
  538. for ams_unit in ams_data:
  539. ams_id = int(ams_unit.get("id", 0))
  540. tray_summary = []
  541. for tray in ams_unit.get("tray", []):
  542. tray_summary.append(
  543. f"T{tray.get('id', '?')}(type={tray.get('tray_type', '')}, "
  544. f"color={tray.get('tray_color', '')}, "
  545. f"now={ams_raw.get('tray_now', '?') if isinstance(ams_raw, dict) else '?'}, "
  546. f"tar={ams_raw.get('tray_tar', '?') if isinstance(ams_raw, dict) else '?'})"
  547. )
  548. logger.info("[UsageTracker] PRINT START printer %d AMS %d: %s", printer_id, ams_id, ", ".join(tray_summary))
  549. # Snapshot spool assignments so usage isn't lost if on_ams_change unlinks mid-print
  550. spool_assignments: dict[tuple[int, int], int] = {}
  551. if db:
  552. assign_result = await db.execute(select(SpoolAssignment).where(SpoolAssignment.printer_id == printer_id))
  553. for assignment in assign_result.scalars().all():
  554. spool_assignments[(assignment.ams_id, assignment.tray_id)] = assignment.spool_id
  555. if spool_assignments:
  556. logger.info(
  557. "[UsageTracker] Snapshotted %d spool assignments for printer %d: %s",
  558. len(spool_assignments),
  559. printer_id,
  560. {f"{k[0]}-{k[1]}": v for k, v in spool_assignments.items()},
  561. )
  562. # The spool each assigned tray starts the print with, in the backend that
  563. # writes the usage: a spool swapped on a tray mid-print is split against it
  564. # (#3325).
  565. if spoolman_owns_usage and db:
  566. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  567. spoolman_slots = {
  568. (row.ams_id, row.tray_id): row.spoolman_spool_id
  569. for row in (
  570. await db.execute(select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id))
  571. ).scalars()
  572. }
  573. state.spool_change_log = spool_swaps.start_entries(spool_swaps.SPOOLMAN, spoolman_slots)
  574. else:
  575. state.spool_change_log = spool_swaps.start_entries(spool_swaps.INVENTORY, spool_assignments)
  576. # Capture the queue item's plate_id so 3MF parsing at completion is scoped to
  577. # the plate that actually ran, not the whole multi-plate file (#1697).
  578. plate_id: int | None = None
  579. if db:
  580. from backend.app.models.print_queue import PrintQueueItem
  581. queue_result = await db.execute(
  582. select(PrintQueueItem)
  583. .where(PrintQueueItem.printer_id == printer_id)
  584. .where(PrintQueueItem.status == "printing")
  585. )
  586. queue_item = queue_result.scalars().first()
  587. if queue_item is not None:
  588. plate_id = queue_item.plate_id
  589. # Always create session (even without valid remain data) so print_name
  590. # is available at completion for 3MF-based tracking
  591. session = PrintSession(
  592. printer_id=printer_id,
  593. print_name=print_name,
  594. started_at=datetime.now(timezone.utc),
  595. tray_remain_start=tray_remain_start,
  596. tray_now_at_start=tray_now_at_start,
  597. spool_assignments=spool_assignments,
  598. ams_mapping=data.get("ams_mapping"),
  599. plate_id=plate_id,
  600. )
  601. if spoolman_owns_usage:
  602. _active_sessions.pop(printer_id, None)
  603. else:
  604. _active_sessions[printer_id] = session
  605. # Mirror to the DB so a restart mid-print doesn't lose the context. The
  606. # tray-change log has already been cleared and seeded with the starting
  607. # tray by bambu_mqtt before this callback fires.
  608. if db:
  609. try:
  610. await persist_session(
  611. db,
  612. session,
  613. getattr(state, "tray_change_log", None),
  614. getattr(state, "spool_change_log", None),
  615. )
  616. except Exception:
  617. logger.exception("[UsageTracker] Failed to persist print session for printer %d", printer_id)
  618. if tray_remain_start:
  619. logger.info(
  620. "[UsageTracker] Captured start remain%% for printer %d (%d trays): %s",
  621. printer_id,
  622. len(tray_remain_start),
  623. {f"{k[0]}-{k[1]}": v for k, v in tray_remain_start.items()},
  624. )
  625. else:
  626. logger.debug("[UsageTracker] No valid remain%% for printer %d, 3MF fallback available", printer_id)
  627. async def on_print_complete(
  628. printer_id: int,
  629. data: dict,
  630. printer_manager,
  631. db: AsyncSession,
  632. archive_id: int | None = None,
  633. ams_mapping: list[int] | None = None,
  634. ) -> list[dict]:
  635. """Compute consumption deltas and update spool weight_used/last_used.
  636. Uses two tracking strategies in priority order:
  637. 1. 3MF per-filament estimates (primary) — precise slicer data for all spools
  638. 2. AMS remain% delta (fallback) — only for trays not already handled by 3MF
  639. Returns a list of dicts describing what was logged (for WebSocket broadcast).
  640. """
  641. from sqlalchemy import select
  642. from backend.app.models.spool_usage_history import SpoolUsageHistory
  643. session = _active_sessions.pop(printer_id, None)
  644. if session is None:
  645. # Restart mid-print: the in-memory session is gone but the print-start
  646. # row survived. Without this the completion path loses the plate, the
  647. # dispatched mapping and the assignment snapshot, and attributes the
  648. # whole print to whichever tray happened to finish it.
  649. try:
  650. await restore_session(db, printer_id)
  651. except Exception:
  652. logger.exception("[UsageTracker] Failed to restore print session for printer %d", printer_id)
  653. session = _active_sessions.pop(printer_id, None)
  654. status = data.get("status", "completed")
  655. results = []
  656. handled_trays: set[tuple[int, int]] = set()
  657. # Fetch default filament cost from settings for fallback
  658. from backend.app.services.print_cost_estimate import default_cost_per_kg
  659. default_filament_cost = await default_cost_per_kg(db)
  660. # Fall back to ams_mapping captured at print start (needed when auto-archive is off
  661. # and the caller can't retrieve the mapping from _print_ams_mappings without archive_id)
  662. if not ams_mapping and session and session.ams_mapping:
  663. ams_mapping = session.ams_mapping
  664. logger.info(
  665. "[UsageTracker] on_print_complete: printer=%d, archive=%s, session=%s, ams_mapping=%s",
  666. printer_id,
  667. archive_id,
  668. "yes" if session else "no",
  669. ams_mapping,
  670. )
  671. # --- Diagnostic logging: dump mapping-related MQTT fields at print completion ---
  672. state = printer_manager.get_status(printer_id)
  673. if state and state.raw_data:
  674. logger.info(
  675. "[UsageTracker] PRINT COMPLETE printer %d: mapping=%s, tray_now=%s, last_loaded_tray=%s",
  676. printer_id,
  677. state.raw_data.get("mapping"),
  678. state.tray_now,
  679. getattr(state, "last_loaded_tray", "N/A"),
  680. )
  681. # --- Path 1 (PRIMARY): 3MF per-filament estimates ---
  682. print_name = (
  683. (session.print_name if session else None) or data.get("subtask_name", "") or data.get("filename", "unknown")
  684. )
  685. # When auto-archive is disabled (archive_id=None), try to find a 3MF by filename
  686. # from the library or previous archives so we can still track filament usage.
  687. threemf_path = None
  688. if not archive_id:
  689. from backend.app.core.config import settings as app_settings
  690. search_filename = data.get("filename") or data.get("subtask_name") or (session.print_name if session else "")
  691. if search_filename:
  692. threemf_path = await _find_3mf_by_filename(
  693. printer_id,
  694. search_filename,
  695. db,
  696. app_settings.base_dir,
  697. print_name=data.get("subtask_name") or (session.print_name if session else None),
  698. )
  699. if archive_id or threemf_path:
  700. threemf_results = await _track_from_3mf(
  701. printer_id,
  702. archive_id,
  703. status,
  704. print_name,
  705. handled_trays,
  706. printer_manager,
  707. db,
  708. ams_mapping=ams_mapping,
  709. tray_now_at_start=session.tray_now_at_start if session else -1,
  710. last_progress=data.get("last_progress", 0.0),
  711. last_layer_num=data.get("last_layer_num", 0),
  712. default_filament_cost=default_filament_cost,
  713. spool_assignments=session.spool_assignments if session else None,
  714. print_started_at=session.started_at if session else None,
  715. threemf_path=threemf_path,
  716. plate_id=session.plate_id if session else None,
  717. )
  718. results.extend(threemf_results)
  719. # --- Path 2 (FALLBACK): AMS remain% delta (only for trays not handled by 3MF) ---
  720. if session and session.tray_remain_start:
  721. state = printer_manager.get_status(printer_id)
  722. if state and state.raw_data:
  723. ams_raw = state.raw_data.get("ams", [])
  724. ams_data = (
  725. ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  726. )
  727. # Build set of trays actually involved in this print (#1269).
  728. # Without this guard, swapping a spool in an UNUSED slot mid-print
  729. # makes that slot's remain% drop to 0, which the fallback below
  730. # would otherwise charge to the originally-assigned spool.
  731. def _global_to_ams_key(global_tray_id: int) -> tuple[int, int]:
  732. if global_tray_id >= 254:
  733. return (255, global_tray_id - 254)
  734. if global_tray_id >= 128:
  735. return (global_tray_id, 0)
  736. return (global_tray_id // 4, global_tray_id % 4)
  737. print_used_keys: set[tuple[int, int]] = set()
  738. if ams_mapping:
  739. for gid in ams_mapping:
  740. if isinstance(gid, int) and gid >= 0:
  741. print_used_keys.add(_global_to_ams_key(gid))
  742. for change in getattr(state, "tray_change_log", None) or []:
  743. if isinstance(change, (tuple, list)) and len(change) >= 1:
  744. gid = change[0]
  745. if isinstance(gid, int) and gid >= 0:
  746. print_used_keys.add(_global_to_ams_key(gid))
  747. # 255 is not a slot: it is what ``tray_now`` reads at rest, before
  748. # the printer has reported one and while nothing is loaded, and an
  749. # unparseable reading falls back to it too. Mapped as a tray id it
  750. # becomes (255, 1), and if it were the only evidence every real
  751. # slot would be excluded and the fallback would charge nothing at
  752. # all (#1820). The external spool reports 254 when in use.
  753. if session.tray_now_at_start is not None and 0 <= session.tray_now_at_start <= 254:
  754. print_used_keys.add(_global_to_ams_key(session.tray_now_at_start))
  755. # Collect all trays to check: AMS trays + VT (external) trays
  756. # Each entry: (ams_id_for_assignment, tray_id_for_assignment, current_remain, label)
  757. trays_to_check: list[tuple[int, int, int, str]] = []
  758. for ams_unit in ams_data:
  759. ams_id = int(ams_unit.get("id", 0))
  760. for tray in ams_unit.get("tray", []):
  761. tray_id = int(tray.get("id", 0))
  762. remain = tray.get("remain", -1)
  763. trays_to_check.append((ams_id, tray_id, remain, f"AMS{ams_id}-T{tray_id}"))
  764. # VT (external) trays — same remain% delta logic
  765. vt_tray_raw = state.raw_data.get("vt_tray") or []
  766. if isinstance(vt_tray_raw, dict):
  767. vt_tray_raw = [vt_tray_raw]
  768. for vt in vt_tray_raw:
  769. if not isinstance(vt, dict):
  770. continue
  771. vt_id = int(vt.get("id", 254))
  772. vt_tray_id = vt_id - 254 # 254→0, 255→1
  773. remain = vt.get("remain", -1)
  774. trays_to_check.append((255, vt_tray_id, remain, f"VT{vt_id}"))
  775. for assign_ams_id, assign_tray_id, current_remain, tray_label in trays_to_check:
  776. key = (assign_ams_id, assign_tray_id)
  777. if key in handled_trays:
  778. continue # Already tracked via 3MF
  779. if key not in session.tray_remain_start:
  780. # No usable remain% when the print began, so there is no delta
  781. # to charge. Said out loud for the same reason as the branches
  782. # below: a slot the print used, holding a spool the operator
  783. # assigned, otherwise vanished from the accounting without a
  784. # word. Common on non-RFID spools, which report remain = -1
  785. # until a remaining amount is set by hand.
  786. if not print_used_keys or key in print_used_keys:
  787. logger.info(
  788. "[UsageTracker] %s: no valid remain%% at print start, nothing to charge for printer %d",
  789. tray_label,
  790. printer_id,
  791. )
  792. continue
  793. # Skip trays the print never touched. Only enforce when we have
  794. # evidence of which trays the print used; if print_used_keys is
  795. # empty (no mapping, no change log, no tray_now_at_start) keep
  796. # the legacy behavior of scanning every tray.
  797. if print_used_keys and key not in print_used_keys:
  798. logger.info(
  799. "[UsageTracker] %s: not in print mapping/tray_change_log — skipping fallback for printer %d",
  800. tray_label,
  801. printer_id,
  802. )
  803. continue
  804. if not isinstance(current_remain, int) or current_remain < 0 or current_remain > 100:
  805. logger.info(
  806. "[UsageTracker] %s: invalid remain%% at completion (%s), skipping fallback for printer %d",
  807. tray_label,
  808. current_remain,
  809. printer_id,
  810. )
  811. continue
  812. start_remain = session.tray_remain_start[key]
  813. delta_pct = start_remain - current_remain
  814. if delta_pct <= 0:
  815. # Not necessarily "nothing was printed". A fresh spool sits
  816. # at 100% for the first tens of grams, and the AMS estimate
  817. # drifts upward on its own, so a real print can end with the
  818. # same or a higher reading than it started with. Said out
  819. # loud because the alternative -- charging nothing, silently
  820. # -- is indistinguishable from having nothing to charge, and
  821. # the operator has no other way to find the prints that went
  822. # uncounted (#1820).
  823. logger.info(
  824. "[UsageTracker] %s: remain%% did not fall over the print (%d%% -> %d%%), "
  825. "nothing charged for printer %d",
  826. tray_label,
  827. start_remain,
  828. current_remain,
  829. printer_id,
  830. )
  831. continue
  832. swap_segs = spool_swaps.segments(
  833. getattr(state, "spool_change_log", None), spool_swaps.INVENTORY, assign_ams_id, assign_tray_id
  834. )
  835. if any(layer > 0 for _, layer in swap_segs[1:]):
  836. # Start and end remain% belong to two different spools: the
  837. # difference is neither one's usage (#3325). An assignment
  838. # corrected before the first layer is not a swap; the live
  839. # spool takes the delta below, as it always did.
  840. logger.warning(
  841. "[UsageTracker] %s: spool swapped during the print, remain%% delta not charged for printer %d",
  842. tray_label,
  843. printer_id,
  844. )
  845. continue
  846. spool_id = await _resolve_spool_id_for_tray(
  847. printer_id=printer_id,
  848. ams_id=assign_ams_id,
  849. tray_id=assign_tray_id,
  850. db=db,
  851. spool_assignments_snapshot=session.spool_assignments,
  852. print_started_at=session.started_at,
  853. )
  854. if spool_id is None:
  855. logger.info(
  856. "[UsageTracker] %s: no spool assigned, skipping fallback for printer %d",
  857. tray_label,
  858. printer_id,
  859. )
  860. continue
  861. # Load spool
  862. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  863. spool = spool_result.scalar_one_or_none()
  864. if not spool:
  865. continue
  866. # Compute weight consumed
  867. weight_grams = (delta_pct / 100.0) * spool.label_weight
  868. # Update spool
  869. if not await _charge_spool(db, spool, weight_grams):
  870. continue
  871. # Calculate cost for this usage
  872. cost = None
  873. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  874. if cost_per_kg > 0:
  875. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  876. # Insert usage history record
  877. history = SpoolUsageHistory(
  878. spool_id=spool.id,
  879. printer_id=printer_id,
  880. print_name=session.print_name,
  881. weight_used=round(weight_grams, 1),
  882. percent_used=delta_pct,
  883. status=status,
  884. cost=cost,
  885. archive_id=archive_id,
  886. )
  887. db.add(history)
  888. handled_trays.add(key)
  889. results.append(
  890. {
  891. "spool_id": spool.id,
  892. "weight_used": round(weight_grams, 1),
  893. "percent_used": delta_pct,
  894. "ams_id": assign_ams_id,
  895. "tray_id": assign_tray_id,
  896. "material": spool.material,
  897. "cost": cost,
  898. # AMS remain%-delta fallback has no 3MF slot — slot_id
  899. # stays None so it is excluded from the colour rewrite.
  900. "slot_id": None,
  901. "color": _spool_color_to_hex(spool.rgba),
  902. }
  903. )
  904. logger.info(
  905. "[UsageTracker] Spool %d consumed %.1fg (%d%%) on printer %d %s (AMS fallback, %s)",
  906. spool.id,
  907. weight_grams,
  908. delta_pct,
  909. printer_id,
  910. tray_label,
  911. status,
  912. )
  913. if results:
  914. await db.commit()
  915. # --- Update PrintArchive.cost from THIS print session only ---
  916. #
  917. # Cover any filament weight that wasn't tracked by an inventory spool with
  918. # the global default rate (#1344). Without this, a multi-color print where
  919. # only some AMS trays are mapped to inventory spools would record only the
  920. # mapped slots' share — e.g. $0.01 for a 110g print when 3 of 4 trays had
  921. # no spool record. The initial cost set by archive.py (total grams *
  922. # primary cost_per_kg) is fine on its own, but this block overwrites it,
  923. # so the overwrite must reconstruct the whole-print cost.
  924. if archive_id and results:
  925. from sqlalchemy import select
  926. from backend.app.models.archive import PrintArchive
  927. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  928. archive = archive_result.scalar_one_or_none()
  929. if archive:
  930. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  931. tracked_grams = sum(r.get("weight_used", 0) or 0 for r in results)
  932. archive_grams = archive.filament_used_grams or 0
  933. untracked_grams = max(0.0, archive_grams - tracked_grams)
  934. if untracked_grams > 0 and default_filament_cost > 0:
  935. total_cost += (untracked_grams / 1000.0) * default_filament_cost
  936. if total_cost > 0:
  937. # Only overwrite archive.cost on the first run. Reprint actuals
  938. # live in PrintLogEntry; the archive card keeps the first run's
  939. # cost so a failed reprint doesn't visually clobber a successful
  940. # 100 g/$X print with a 10 g/$X/10 partial (#1378).
  941. from backend.app.services.print_log import other_runs_of
  942. # Nor from a run that did not finish: the archive's cost is one
  943. # full print of the file -- the queue estimate, plate scaling and
  944. # billing read it so -- and a failed run's partial cost already
  945. # lands on its own Print Log entry. Spoolman mode never wrote it
  946. # either (COST-3).
  947. if status == "completed" and not await other_runs_of(db, archive):
  948. archive.cost = round(total_cost, 2)
  949. await db.commit()
  950. return results
  951. # A running print's ``filename`` is the path the printer is executing, and on a
  952. # sliced job that is always ``…/Metadata/plate_<N>.gcode``. Its stem names the
  953. # *plate*, not the model, and every Bambu print in existence has one — so it
  954. # identifies nothing and must never be used to match a 3MF. It reached the
  955. # matcher for real on H2-series and P2S prints, where the file goes to internal
  956. # eMMC, no 3MF can be fetched, and the archive keeps the gcode path as its
  957. # filename: `plate_1` then matched an unrelated `lid_plate_1.gcode.3mf` and that
  958. # print's filament figures were read off a different model entirely.
  959. _GENERIC_PLATE_STEM = re.compile(r"^plate_?\d+$", re.IGNORECASE)
  960. def _like_escape(value: str) -> str:
  961. """Escape LIKE metacharacters so a stem matches literally.
  962. ``_`` is a single-character wildcard, and model names are full of them.
  963. """
  964. return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
  965. def _threemf_search_stem(*candidates: str | None) -> str | None:
  966. """First candidate that names a model, or None if none of them do.
  967. Candidates are tried in order and the generic plate name is skipped rather
  968. than accepted, so a print that only has one falls through to "no match"
  969. instead of matching everything.
  970. """
  971. for raw in candidates:
  972. if not raw:
  973. continue
  974. stem = raw.split("/")[-1].strip()
  975. for suffix in (".gcode.3mf", ".gcode", ".3mf"):
  976. if stem.lower().endswith(suffix):
  977. stem = stem[: -len(suffix)]
  978. break
  979. # Stripped only to judge the stem, never to change it: a real archive
  980. # here is named "…Face Down .gcode.3mf", and a stem trimmed to
  981. # "…Face Down" no longer matches the file it came from.
  982. probe = stem.strip()
  983. if probe and not _GENERIC_PLATE_STEM.match(probe):
  984. return stem
  985. return None
  986. def _stem_matches(column, stem: str):
  987. """Filter matching *stem* at a filename boundary rather than anywhere.
  988. ``ilike("%<stem>.%")`` also matched a *suffix* of a longer name, which is how
  989. `plate_1` reached `lid_plate_1.gcode.3mf`. A name is either the whole
  990. basename or the basename after a directory separator.
  991. """
  992. escaped = _like_escape(stem)
  993. return column.ilike(f"{escaped}.%", escape="\\") | column.ilike(f"%/{escaped}.%", escape="\\")
  994. def _expected_plate_for_print(plate_id: int | None, gcode_file: str | None) -> int | None:
  995. """The plate a running print is on, from whatever was recorded about it.
  996. ``plate_id`` is the reliable source, and the archives that need a donor 3MF
  997. have none: the no-3MF fallback row is created before any 3MF is read, so
  998. the column is never filled. The gcode path the printer echoed is the other
  999. source, exact on the firmwares that echo ``Metadata/plate_N.gcode``. Some
  1000. P1S builds echo only the 3MF filename, and then the plate is simply not
  1001. knowable at print start (#2957).
  1002. """
  1003. from backend.app.services.printer_manager import parse_plate_id
  1004. if plate_id is not None:
  1005. return plate_id
  1006. return parse_plate_id(gcode_file)
  1007. def _donor_3mf_conflicts(candidate, expected_plate: int | None) -> str | None:
  1008. """Why *candidate* cannot be this print's 3MF, or None if nothing rules it out.
  1009. A same-name 3MF is not the same print. Bambu Studio writes the printer-side
  1010. filename from the project's ``Title`` metadata, so every plate of a project
  1011. arrives under one name however the user renamed the file on disk, and a
  1012. donor chosen on the name alone hands one plate's slicer estimates to another
  1013. plate's print. A reporter's single-filament job was charged against three
  1014. spools that way, and nothing about the deduction said it was a guess
  1015. (#2957).
  1016. The plate is the one thing that can settle this. It is the same comparison
  1017. #1204 already makes against a freshly downloaded 3MF, so a single-plate
  1018. export is known to carry its original index rather than a renumbered 1.
  1019. Filament *count* deliberately is not checked, however tempting: the slicer's
  1020. ``ams_mapping`` is indexed by the project's filament slot -- see
  1021. ``slot_to_tray[slot_id - 1]`` below -- not by the plate's, so a real
  1022. single-filament print reports ``[0, -1, -1, -1]`` and its length says
  1023. nothing about how many filaments the plate uses.
  1024. """
  1025. from backend.app.services.archive import plate_indexes_in_3mf
  1026. if expected_plate is None:
  1027. return None
  1028. plates = plate_indexes_in_3mf(candidate)
  1029. if not plates or any(plate is None for plate in plates):
  1030. # Nothing was read, or not all of it was, and neither is evidence about
  1031. # the plate. Refusing here would drop the fallback for every 3MF variant
  1032. # this parser does not understand; downstream reports that honestly as
  1033. # "no filament usage data".
  1034. return None
  1035. if len(plates) == 1 and plates[0] != expected_plate:
  1036. return f"it holds plate {plates[0]}, this print is plate {expected_plate}"
  1037. if expected_plate not in plates:
  1038. # An all-plates export is a good donor precisely when it carries the
  1039. # plate that is running. Without this the plate is looked for
  1040. # downstream, found missing, and the whole file's filaments are summed
  1041. # onto one plate's print.
  1042. return f"it has no plate {expected_plate}"
  1043. return None
  1044. async def _resolve_3mf_fallback(archive, db: AsyncSession, base_dir):
  1045. """Try to find a 3MF file from library or a previous archive when the current archive has none.
  1046. This handles fallback archives (FTP download failed) where the 3MF may already exist
  1047. locally from a library upload or a previous successful print of the same file.
  1048. A name match alone does not make a candidate this print's file, so every
  1049. candidate is put through :func:`_donor_3mf_conflicts` before it is handed
  1050. back (#2957).
  1051. """
  1052. from pathlib import Path
  1053. from backend.app.models.archive import PrintArchive
  1054. from backend.app.models.library import LibraryFile
  1055. # Derive search name from archive filename (e.g. "benchy.3mf" or "benchy.gcode.3mf"),
  1056. # falling back to the print name when the filename is only a plate path.
  1057. search_base = _threemf_search_stem(archive.filename, archive.print_name)
  1058. if not search_base:
  1059. return None
  1060. print_data = (getattr(archive, "extra_data", None) or {}).get("_print_data") or {}
  1061. expected_plate = _expected_plate_for_print(
  1062. getattr(archive, "plate_id", None),
  1063. archive.filename or print_data.get("filename"),
  1064. )
  1065. if expected_plate is None:
  1066. # Worth saying out loud. On the firmwares that echo only the 3MF
  1067. # filename there is nothing to check a donor against, so whatever is
  1068. # accepted below is accepted on its name alone -- which is how the
  1069. # reporter's spools were debited for another plate's filament. The
  1070. # deduction being silent was half the bug (#2957).
  1071. logger.warning(
  1072. "[UsageTracker] 3MF fallback: archive %s does not know its plate (%r), so a same-named "
  1073. "3MF can only be matched on its name",
  1074. archive.id,
  1075. archive.filename,
  1076. )
  1077. # 1. Try library files matching the name (match base name at file boundary)
  1078. try:
  1079. lib_result = await db.execute(
  1080. LibraryFile.active()
  1081. .where(_stem_matches(LibraryFile.file_path, search_base))
  1082. .where(LibraryFile.file_path.ilike("%.3mf"))
  1083. .order_by(LibraryFile.created_at.desc())
  1084. .limit(3)
  1085. )
  1086. for lib_file in lib_result.scalars().all():
  1087. lib_path = Path(lib_file.file_path)
  1088. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  1089. if candidate.exists() and candidate.suffix == ".3mf":
  1090. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1091. if conflict:
  1092. logger.warning(
  1093. "[UsageTracker] 3MF fallback: not using library file %s for archive %s — %s",
  1094. candidate,
  1095. archive.id,
  1096. conflict,
  1097. )
  1098. continue
  1099. logger.info(
  1100. "[UsageTracker] 3MF fallback: found library file %s for archive %s (expected plate=%s)",
  1101. candidate,
  1102. archive.id,
  1103. expected_plate,
  1104. )
  1105. return candidate
  1106. except Exception as e:
  1107. logger.debug("[UsageTracker] 3MF fallback: library lookup failed: %s", e)
  1108. # 2. Try previous archives with the same filename that have a valid file_path
  1109. try:
  1110. prev_result = await db.execute(
  1111. select(PrintArchive)
  1112. .where(PrintArchive.id != archive.id)
  1113. .where(PrintArchive.printer_id == archive.printer_id)
  1114. .where(PrintArchive.file_path != "")
  1115. .where(PrintArchive.file_path.isnot(None))
  1116. .where(_stem_matches(PrintArchive.filename, search_base))
  1117. .order_by(PrintArchive.created_at.desc())
  1118. .limit(3)
  1119. )
  1120. for prev_archive in prev_result.scalars().all():
  1121. candidate = base_dir / prev_archive.file_path
  1122. if candidate.exists() and candidate.suffix == ".3mf":
  1123. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1124. if conflict:
  1125. logger.warning(
  1126. "[UsageTracker] 3MF fallback: not using archive %s's file for archive %s — %s",
  1127. prev_archive.id,
  1128. archive.id,
  1129. conflict,
  1130. )
  1131. continue
  1132. logger.info(
  1133. "[UsageTracker] 3MF fallback: found previous archive %s file for archive %s (expected plate=%s)",
  1134. prev_archive.id,
  1135. archive.id,
  1136. expected_plate,
  1137. )
  1138. return candidate
  1139. except Exception as e:
  1140. logger.debug("[UsageTracker] 3MF fallback: previous archive lookup failed: %s", e)
  1141. return None
  1142. async def _find_3mf_by_filename(
  1143. printer_id: int,
  1144. filename: str,
  1145. db: AsyncSession,
  1146. base_dir,
  1147. print_name: str | None = None,
  1148. ):
  1149. """Find a 3MF file by filename from library or previous archives.
  1150. Used when auto-archive is disabled and there's no archive_id, but we still
  1151. need the 3MF slicer data for filament usage tracking.
  1152. ``print_name`` is the model name to fall back to when ``filename`` is the
  1153. printer's plate path, which names no model at all -- and when it is that
  1154. plate path, it is also what keeps a same-named file for a different plate
  1155. from being adopted (#2957); see :func:`_donor_3mf_conflicts`.
  1156. """
  1157. from pathlib import Path
  1158. from backend.app.models.archive import PrintArchive
  1159. from backend.app.models.library import LibraryFile
  1160. search_base = _threemf_search_stem(filename, print_name)
  1161. if not search_base:
  1162. return None
  1163. expected_plate = _expected_plate_for_print(None, filename)
  1164. # 1. Try library files matching the name
  1165. try:
  1166. lib_result = await db.execute(
  1167. LibraryFile.active()
  1168. .where(_stem_matches(LibraryFile.file_path, search_base))
  1169. .where(LibraryFile.file_path.ilike("%.3mf"))
  1170. .order_by(LibraryFile.created_at.desc())
  1171. .limit(3)
  1172. )
  1173. for lib_file in lib_result.scalars().all():
  1174. lib_path = Path(lib_file.file_path)
  1175. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  1176. if candidate.exists() and candidate.suffix == ".3mf":
  1177. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1178. if conflict:
  1179. logger.warning(
  1180. "[UsageTracker] 3MF (no-archive): not using library file %s for '%s' — %s",
  1181. candidate,
  1182. filename,
  1183. conflict,
  1184. )
  1185. continue
  1186. logger.info("[UsageTracker] 3MF (no-archive): found library file %s for '%s'", candidate, filename)
  1187. return candidate
  1188. except Exception as e:
  1189. logger.debug("[UsageTracker] 3MF (no-archive): library lookup failed: %s", e)
  1190. # 2. Try previous archives with a valid 3MF file_path
  1191. try:
  1192. prev_result = await db.execute(
  1193. select(PrintArchive)
  1194. .where(PrintArchive.printer_id == printer_id)
  1195. .where(PrintArchive.file_path != "")
  1196. .where(PrintArchive.file_path.isnot(None))
  1197. .where(_stem_matches(PrintArchive.filename, search_base))
  1198. .order_by(PrintArchive.created_at.desc())
  1199. .limit(3)
  1200. )
  1201. for prev_archive in prev_result.scalars().all():
  1202. candidate = base_dir / prev_archive.file_path
  1203. if candidate.exists() and candidate.suffix == ".3mf":
  1204. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1205. if conflict:
  1206. logger.warning(
  1207. "[UsageTracker] 3MF (no-archive): not using archive %s's file for '%s' — %s",
  1208. prev_archive.id,
  1209. filename,
  1210. conflict,
  1211. )
  1212. continue
  1213. logger.info(
  1214. "[UsageTracker] 3MF (no-archive): found previous archive %s file for '%s'",
  1215. prev_archive.id,
  1216. filename,
  1217. )
  1218. return candidate
  1219. except Exception as e:
  1220. logger.debug("[UsageTracker] 3MF (no-archive): previous archive lookup failed: %s", e)
  1221. return None
  1222. async def _track_from_3mf(
  1223. printer_id: int,
  1224. archive_id: int | None,
  1225. status: str,
  1226. print_name: str,
  1227. handled_trays: set[tuple[int, int]],
  1228. printer_manager,
  1229. db: AsyncSession,
  1230. ams_mapping: list[int] | None = None,
  1231. tray_now_at_start: int = -1,
  1232. last_progress: float = 0.0,
  1233. last_layer_num: int = 0,
  1234. default_filament_cost: float = 0.0,
  1235. spool_assignments: dict[tuple[int, int], int] | None = None,
  1236. print_started_at: datetime | None = None,
  1237. threemf_path=None,
  1238. plate_id: int | None = None,
  1239. ) -> list[dict]:
  1240. """Track usage from 3MF per-filament slicer data (primary path).
  1241. Uses slicer-estimated filament weight for all spools (BL and non-BL).
  1242. For partial prints (failed/aborted), tries per-layer gcode data first,
  1243. then falls back to linear scaling by progress.
  1244. When archive_id is None (auto-archive disabled), a pre-resolved threemf_path
  1245. can be provided to still track filament usage from slicer data.
  1246. When ``plate_id`` is set (queue prints of a single plate from a multi-plate
  1247. 3MF), only that plate's filaments contribute. Without it the 3MF parser sums
  1248. every plate, which is correct for direct/library Print flows that always
  1249. target the first or only plate (#1697).
  1250. Slot-to-tray mapping priority:
  1251. 1. Stored ams_mapping from print command (reprints/direct prints)
  1252. 2. MQTT mapping field from printer state (universal, all print sources)
  1253. 3. Queue item ams_mapping (for queue-initiated prints)
  1254. 4. tray_now from printer state (for single-filament non-queue prints)
  1255. 5. Position-based default using sorted available tray IDs (handles external spools)
  1256. 6. Default mapping: slot_id - 1 = global_tray_id (last resort)
  1257. """
  1258. from pathlib import Path
  1259. from backend.app.core.config import settings as app_settings
  1260. from backend.app.models.archive import PrintArchive
  1261. from backend.app.models.print_queue import PrintQueueItem
  1262. from backend.app.utils.threemf_tools import extract_filament_usage_from_3mf
  1263. file_path: Path | None = threemf_path
  1264. archive: PrintArchive | None = None
  1265. if file_path is None and archive_id:
  1266. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1267. archive = result.scalar_one_or_none()
  1268. if not archive:
  1269. logger.info("[UsageTracker] 3MF: archive %s not found, skipping", archive_id)
  1270. return []
  1271. # Try archive's own file_path first
  1272. if archive.file_path:
  1273. candidate = app_settings.base_dir / archive.file_path
  1274. if candidate.exists():
  1275. file_path = candidate
  1276. # Fallback: find 3MF from library or a previous archive with the same filename
  1277. if file_path is None:
  1278. file_path = await _resolve_3mf_fallback(archive, db, app_settings.base_dir)
  1279. if file_path is None:
  1280. logger.info("[UsageTracker] 3MF: no file available for archive %s, skipping", archive_id)
  1281. return []
  1282. # The queue item carries both the plate and the dispatched mapping; look it
  1283. # up at most once. A batch dispatches one archive as several queue items,
  1284. # on several printers at once: only this printer's newest is this run.
  1285. # Completion has already closed it, as cancelled for an aborted print.
  1286. _queue_item_lookup: list = []
  1287. async def _dispatch_queue_item():
  1288. if not _queue_item_lookup:
  1289. if not archive_id:
  1290. _queue_item_lookup.append(None)
  1291. else:
  1292. queue_result = await db.execute(
  1293. select(PrintQueueItem)
  1294. .where(PrintQueueItem.archive_id == archive_id)
  1295. .where(PrintQueueItem.printer_id == printer_id)
  1296. .where(PrintQueueItem.status.in_(["printing", "completed", "failed", "cancelled"]))
  1297. .order_by(PrintQueueItem.id.desc())
  1298. )
  1299. _queue_item_lookup.append(queue_result.scalars().first())
  1300. return _queue_item_lookup[0]
  1301. # The caller's plate_id comes from the in-memory session, which a restart
  1302. # mid-print destroys. Both the archive and the queue item recorded the
  1303. # plate at dispatch — without falling back to them the parser sums every
  1304. # plate of a multi-plate file and charges the lot to one spool. The
  1305. # newest queue item goes first: the archive keeps the plate of its first
  1306. # print, so a reprint of another plate is only on the queue item.
  1307. if plate_id is None:
  1308. plate_queue_item = await _dispatch_queue_item()
  1309. if plate_queue_item is not None and plate_queue_item.plate_id is not None:
  1310. plate_id = plate_queue_item.plate_id
  1311. logger.info(
  1312. "[UsageTracker] 3MF: plate_id=%s recovered from queue item %s",
  1313. plate_id,
  1314. plate_queue_item.id,
  1315. )
  1316. elif archive is not None and archive.plate_id is not None:
  1317. plate_id = archive.plate_id
  1318. logger.info("[UsageTracker] 3MF: plate_id=%s recovered from archive %s", plate_id, archive_id)
  1319. filament_usage = extract_filament_usage_from_3mf(file_path, plate_id)
  1320. if not filament_usage and plate_id is not None:
  1321. # The plate isn't in this file. That happens when the archive's own 3MF
  1322. # is gone and `_resolve_3mf_fallback` substituted a same-named file from
  1323. # the library that was sliced with different plates. Summing the whole
  1324. # file is wrong for a single-plate run, but it is closer than recording
  1325. # nothing at all — and unlike the silent whole-file sum this replaces,
  1326. # it says so.
  1327. filament_usage = extract_filament_usage_from_3mf(file_path, None)
  1328. if filament_usage:
  1329. logger.warning(
  1330. "[UsageTracker] 3MF: plate %s not present in %s — falling back to the whole-file total",
  1331. plate_id,
  1332. file_path,
  1333. )
  1334. plate_id = None
  1335. if not filament_usage:
  1336. logger.info("[UsageTracker] 3MF: no filament usage data in %s", file_path)
  1337. return []
  1338. logger.info("[UsageTracker] 3MF: archive %s, plate_id=%s, filament_usage=%s", archive_id, plate_id, filament_usage)
  1339. # --- Resolve slot-to-tray mapping ---
  1340. mapping_source = None
  1341. # 1. Use stored ams_mapping from the print command (reprints/direct prints)
  1342. slot_to_tray = ams_mapping
  1343. if slot_to_tray:
  1344. mapping_source = "print_cmd"
  1345. # 2. Try queue item ams_mapping (queue-initiated prints store the exact mapping)
  1346. #
  1347. # Ranked above the live MQTT field on purpose: `mapping` reports the tray
  1348. # the printer is feeding from *now*, and AMS filament backup rewrites it to
  1349. # the substitute tray when a spool runs dry. Read at completion it names
  1350. # the tray that finished the print, not the one the slicer assigned — the
  1351. # queue item's copy is the mapping the print was actually dispatched with.
  1352. if not slot_to_tray and archive_id:
  1353. queue_item = await _dispatch_queue_item()
  1354. if queue_item and queue_item.ams_mapping:
  1355. try:
  1356. slot_to_tray = json.loads(queue_item.ams_mapping)
  1357. mapping_source = "queue"
  1358. except (json.JSONDecodeError, TypeError):
  1359. pass
  1360. # 3. Try MQTT mapping field from printer state (universal, all print sources)
  1361. if not slot_to_tray:
  1362. state = printer_manager.get_status(printer_id)
  1363. raw_data = getattr(state, "raw_data", None) if state else None
  1364. if raw_data:
  1365. mqtt_mapping = raw_data.get("mapping")
  1366. decoded = _decode_mqtt_mapping(mqtt_mapping)
  1367. if decoded:
  1368. slot_to_tray = decoded
  1369. mapping_source = "mqtt"
  1370. # 4. Color-match 3MF filament slots to AMS trays (for printers without mapping field)
  1371. if not slot_to_tray:
  1372. state = printer_manager.get_status(printer_id)
  1373. raw_data = getattr(state, "raw_data", None) if state else None
  1374. if raw_data:
  1375. matched = _match_slots_by_color(filament_usage, raw_data.get("ams"))
  1376. if matched:
  1377. slot_to_tray = matched
  1378. mapping_source = "color_match"
  1379. logger.info(
  1380. "[UsageTracker] 3MF: slot_to_tray=%s (source: %s)",
  1381. slot_to_tray,
  1382. mapping_source or "none",
  1383. )
  1384. # A mapping that names no tray for any slot the print used carries no
  1385. # evidence at all -- typically a flat ams_mapping whose external spool is
  1386. # -1 and came without an ams_mapping2 to resolve it (#3166). Drop it so the
  1387. # tray_now evidence below decides, rather than leaving every slot unfed.
  1388. if slot_to_tray:
  1389. used_slots = [u.get("slot_id", 0) for u in filament_usage if u.get("used_g", 0) > 0]
  1390. if used_slots and all(
  1391. not (0 < s <= len(slot_to_tray) and isinstance(slot_to_tray[s - 1], int) and slot_to_tray[s - 1] >= 0)
  1392. for s in used_slots
  1393. ):
  1394. logger.info(
  1395. "[UsageTracker] 3MF: mapping %s names no tray for used slots %s — ignoring it",
  1396. slot_to_tray,
  1397. used_slots,
  1398. )
  1399. slot_to_tray = None
  1400. mapping_source = None
  1401. # 5. For single-filament non-queue prints, use tray_now from printer state
  1402. # Priority: tray_change_log (multi-tray split) > tray_now_at_start > current tray_now
  1403. # > last_loaded_tray > vt_tray check
  1404. #
  1405. # tray_change_log evidence wins over slot_to_tray when present: if the
  1406. # printer fed from multiple trays mid-print (AMS auto-fallback when one
  1407. # spool runs out, #957), the slicer's mapping captured at print start
  1408. # is stale and needs to be replaced with per-layer split attribution.
  1409. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  1410. tray_now_override: int | None = None
  1411. tray_changes: list[tuple[int, int]] = [] # [(global_tray_id, layer_num), ...]
  1412. state = printer_manager.get_status(printer_id) if len(nonzero_slots) == 1 else None
  1413. if state is not None:
  1414. tray_changes = getattr(state, "tray_change_log", []) or []
  1415. elif len(nonzero_slots) > 1:
  1416. # Multi-material print: every filament change moves tray_now, so the
  1417. # log can't be read as "this slot moved to that tray" and splitting
  1418. # would attribute worse than the mapping does. Say so rather than
  1419. # silently dropping the evidence — a runout mid-print on a
  1420. # multi-material job still lands entirely on the mapped tray.
  1421. _multi_state = printer_manager.get_status(printer_id)
  1422. if len(getattr(_multi_state, "tray_change_log", []) or []) > 1:
  1423. logger.warning(
  1424. "[UsageTracker] 3MF: %d tray changes observed but %d filament slots used — "
  1425. "splitting needs a single slot, attributing by mapping alone (printer %d, archive %s)",
  1426. len(_multi_state.tray_change_log),
  1427. len(nonzero_slots),
  1428. printer_id,
  1429. archive_id,
  1430. )
  1431. if len(tray_changes) > 1:
  1432. # Multi-tray usage detected — splitting takes over regardless of slot_to_tray.
  1433. logger.info("[UsageTracker] 3MF: tray change log: %s (will split weight)", tray_changes)
  1434. elif not slot_to_tray and len(nonzero_slots) == 1:
  1435. if 0 <= tray_now_at_start <= 254:
  1436. tray_now_override = tray_now_at_start
  1437. logger.info("[UsageTracker] 3MF: using tray_now_at_start=%d (single-filament fallback)", tray_now_at_start)
  1438. elif state and 0 <= state.tray_now <= 254:
  1439. tray_now_override = state.tray_now
  1440. logger.info("[UsageTracker] 3MF: using current tray_now=%d", state.tray_now)
  1441. elif state and 0 <= state.last_loaded_tray <= 253:
  1442. tray_now_override = state.last_loaded_tray
  1443. logger.info("[UsageTracker] 3MF: using last_loaded_tray=%d (post-retract fallback)", state.last_loaded_tray)
  1444. elif state and state.tray_now == 255:
  1445. # 255 = "no filament" on legacy printers, but valid 2nd external spool on H2-series
  1446. vt_tray = state.raw_data.get("vt_tray") or []
  1447. if any(int(vt.get("id", 0)) == 255 for vt in vt_tray if isinstance(vt, dict)):
  1448. tray_now_override = state.tray_now
  1449. logger.info("[UsageTracker] 3MF: using tray_now=255 (H2-series external spool)")
  1450. if tray_now_override is None:
  1451. logger.info(
  1452. "[UsageTracker] 3MF: no valid tray_now (at_start=%d, current=%s, last_loaded=%s)",
  1453. tray_now_at_start,
  1454. state.tray_now if state else "N/A",
  1455. state.last_loaded_tray if state else "N/A",
  1456. )
  1457. # Scale factor for partial prints (failed/aborted)
  1458. if status == "completed":
  1459. scale = 1.0
  1460. else:
  1461. state = printer_manager.get_status(printer_id)
  1462. progress = state.progress if state else 0
  1463. # Firmware resets progress to 0 on cancel — use last valid progress captured during print
  1464. if progress <= 0 and last_progress > 0:
  1465. progress = last_progress
  1466. logger.info("[UsageTracker] 3MF: using last_progress=%.1f (firmware reset current to 0)", last_progress)
  1467. scale = max(0.0, min(progress / 100.0, 1.0))
  1468. # Per-layer gcode accuracy for partial prints
  1469. layer_grams: dict[int, float] | None = None
  1470. if status != "completed":
  1471. state = printer_manager.get_status(printer_id)
  1472. current_layer = state.layer_num if state else 0
  1473. # Firmware resets layer_num to 0 on cancel — use last valid layer captured during print
  1474. if current_layer <= 0 and last_layer_num > 0:
  1475. current_layer = last_layer_num
  1476. logger.info("[UsageTracker] 3MF: using last_layer_num=%d (firmware reset current to 0)", last_layer_num)
  1477. if current_layer > 0:
  1478. try:
  1479. from backend.app.utils.threemf_tools import (
  1480. extract_filament_properties_from_3mf,
  1481. extract_layer_filament_usage_from_3mf,
  1482. get_cumulative_usage_at_layer,
  1483. mm_to_grams,
  1484. )
  1485. layer_usage = extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1486. if layer_usage:
  1487. cumulative_mm = get_cumulative_usage_at_layer(layer_usage, current_layer)
  1488. filament_props = extract_filament_properties_from_3mf(file_path)
  1489. layer_grams = {}
  1490. for filament_id, mm_used in cumulative_mm.items():
  1491. slot_id = filament_id + 1 # 0-based to 1-based
  1492. props = filament_props.get(slot_id, {})
  1493. density = props.get("density", 1.24)
  1494. diameter = props.get("diameter", 1.75)
  1495. layer_grams[slot_id] = mm_to_grams(mm_used, diameter, density)
  1496. except Exception:
  1497. pass # Fall back to linear scaling
  1498. results = []
  1499. # Trays this print drew from that no longer have an assignment to charge.
  1500. # Collected rather than acted on inline so one notification covers the whole
  1501. # print instead of one per slot (#2812).
  1502. unassigned_global_trays: list[int] = []
  1503. # Deduplicated by slicer slot, not by tray (#3230). Several slots mapped to
  1504. # one tray, or a single-slot print that returns to an earlier tray, each
  1505. # consume filament of their own. A slot only repeats when the plate is
  1506. # unknown and every plate of the file is listed, and that must not charge
  1507. # the same slot once per plate. Only a tray the caller had already covered
  1508. # before this pass is skipped.
  1509. charged_slots: set[int] = set()
  1510. covered_before = frozenset(handled_trays)
  1511. # Spools swapped by hand on one tray mid-print (#3325). The G-code's
  1512. # per-layer usage is read only when a tray was actually swapped.
  1513. _swap_state = printer_manager.get_status(printer_id)
  1514. _swap_total = getattr(_swap_state, "total_layers", 0)
  1515. _swap_layer = getattr(_swap_state, "layer_num", 0)
  1516. if status == "completed":
  1517. _swap_end = max(_swap_total if isinstance(_swap_total, int) else 0, last_layer_num)
  1518. else:
  1519. _swap_end = _swap_layer if isinstance(_swap_layer, int) and _swap_layer > 0 else last_layer_num
  1520. def _read_layer_usage():
  1521. from backend.app.utils.threemf_tools import extract_layer_filament_usage_from_3mf
  1522. return extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1523. _swap_shares = spool_swaps.Splitter(
  1524. getattr(_swap_state, "spool_change_log", None) if _swap_state else None,
  1525. spool_swaps.INVENTORY,
  1526. _read_layer_usage,
  1527. _swap_end,
  1528. completed=status == "completed",
  1529. ).shares
  1530. for usage in filament_usage:
  1531. slot_id = usage.get("slot_id", 0)
  1532. used_g = usage.get("used_g", 0)
  1533. if used_g <= 0:
  1534. continue
  1535. if slot_id in charged_slots:
  1536. continue
  1537. charged_slots.add(slot_id)
  1538. # --- Mid-print tray switch: split weight across trays ---
  1539. # Split math is shared with the Spoolman writer via
  1540. # ``utils.tray_split.compute_tray_split_grams`` (#1793) — both
  1541. # inventory backends must attribute segments identically or a
  1542. # user running dual-mode sees divergent totals.
  1543. if len(tray_changes) > 1:
  1544. # Compute total weight for this slot (same logic as normal path)
  1545. if layer_grams and slot_id in layer_grams:
  1546. total_weight = layer_grams[slot_id]
  1547. else:
  1548. total_weight = used_g * scale
  1549. if total_weight <= 0:
  1550. continue
  1551. # Extract per-layer gcode for segment splitting
  1552. split_layer_usage = None
  1553. split_props: dict = {}
  1554. try:
  1555. from backend.app.utils.threemf_tools import (
  1556. extract_filament_properties_from_3mf,
  1557. extract_layer_filament_usage_from_3mf,
  1558. )
  1559. split_layer_usage = extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1560. filament_props = extract_filament_properties_from_3mf(file_path)
  1561. split_props = filament_props.get(slot_id, {})
  1562. except Exception:
  1563. pass # Fall back to linear splitting
  1564. from backend.app.utils.tray_split import compute_tray_split_grams
  1565. segments = compute_tray_split_grams(
  1566. tray_changes=tray_changes,
  1567. total_weight=total_weight,
  1568. slot_id=slot_id,
  1569. layer_usage=split_layer_usage,
  1570. density=split_props.get("density", 1.24),
  1571. diameter=split_props.get("diameter", 1.75),
  1572. total_layers=(state.total_layers if state else 0) or 0,
  1573. last_layer_num=last_layer_num,
  1574. )
  1575. for seg_idx, tray_global, segment_grams in segments:
  1576. if segment_grams <= 0:
  1577. continue
  1578. # Convert global tray ID to (ams_id, tray_id)
  1579. if tray_global >= 254:
  1580. seg_ams_id = 255
  1581. seg_tray_id = tray_global - 254
  1582. elif tray_global >= 128:
  1583. seg_ams_id = tray_global
  1584. seg_tray_id = 0
  1585. else:
  1586. seg_ams_id = tray_global // 4
  1587. seg_tray_id = tray_global % 4
  1588. seg_key = (seg_ams_id, seg_tray_id)
  1589. if seg_key in covered_before:
  1590. continue
  1591. seg_start_layer = tray_changes[seg_idx][1]
  1592. is_last = seg_idx + 1 >= len(tray_changes)
  1593. logger.info(
  1594. "[UsageTracker] 3MF split: segment %d tray=%d (AMS%d-T%d) layers %d-%s -> %.1fg",
  1595. seg_idx,
  1596. tray_global,
  1597. seg_ams_id,
  1598. seg_tray_id,
  1599. seg_start_layer,
  1600. tray_changes[seg_idx + 1][1] if not is_last else "end",
  1601. segment_grams,
  1602. )
  1603. # A spool swapped by hand on this tray within the segment (#3325).
  1604. seg_shares = _swap_shares(
  1605. seg_ams_id,
  1606. seg_tray_id,
  1607. slot_id,
  1608. segment_grams,
  1609. seg_start_layer,
  1610. None if is_last else tray_changes[seg_idx + 1][1],
  1611. )
  1612. seg_spool_id = await _resolve_spool_id_for_tray(
  1613. printer_id=printer_id,
  1614. ams_id=seg_ams_id,
  1615. tray_id=seg_tray_id,
  1616. db=db,
  1617. spool_assignments_snapshot=spool_assignments,
  1618. print_started_at=print_started_at,
  1619. )
  1620. if seg_shares is None and seg_spool_id is None:
  1621. logger.info(
  1622. "[UsageTracker] 3MF split: no spool at printer %d AMS%d-T%d, skipping segment",
  1623. printer_id,
  1624. seg_ams_id,
  1625. seg_tray_id,
  1626. )
  1627. continue
  1628. for share_spool_id, share_grams in seg_shares or [(seg_spool_id, segment_grams)]:
  1629. spool_result = await db.execute(select(Spool).where(Spool.id == share_spool_id))
  1630. spool = spool_result.scalar_one_or_none()
  1631. if not spool:
  1632. continue
  1633. if not await _charge_spool(db, spool, share_grams):
  1634. continue
  1635. percent = round(share_grams / (spool.label_weight or 1000) * 100)
  1636. cost = None
  1637. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1638. if cost_per_kg > 0:
  1639. cost = round((share_grams / 1000.0) * cost_per_kg, 2)
  1640. history = SpoolUsageHistory(
  1641. spool_id=spool.id,
  1642. printer_id=printer_id,
  1643. print_name=print_name,
  1644. weight_used=round(share_grams, 1),
  1645. percent_used=percent,
  1646. status=status,
  1647. cost=cost,
  1648. archive_id=archive_id,
  1649. )
  1650. db.add(history)
  1651. handled_trays.add(seg_key)
  1652. results.append(
  1653. {
  1654. "spool_id": spool.id,
  1655. "weight_used": round(share_grams, 1),
  1656. "percent_used": percent,
  1657. "ams_id": seg_ams_id,
  1658. "tray_id": seg_tray_id,
  1659. "material": spool.material,
  1660. "cost": cost,
  1661. "slot_id": slot_id,
  1662. "color": _spool_color_to_hex(spool.rgba),
  1663. }
  1664. )
  1665. logger.info(
  1666. "[UsageTracker] Spool %d consumed %.1fg (3MF split seg%d) on printer %d AMS%d-T%d (%s)",
  1667. spool.id,
  1668. share_grams,
  1669. seg_idx,
  1670. printer_id,
  1671. seg_ams_id,
  1672. seg_tray_id,
  1673. status,
  1674. )
  1675. continue # Skip normal single-tray processing for this slot
  1676. # Map 3MF slot_id to physical (ams_id, tray_id) using resolved mapping
  1677. tray_is_guessed = False
  1678. if tray_now_override is not None:
  1679. # Single-filament non-queue print: use actual tray from printer state
  1680. global_tray_id = tray_now_override
  1681. else:
  1682. # Explicit mapping (print command, MQTT, queue, color match)
  1683. global_tray_id = None
  1684. if slot_to_tray and slot_id <= len(slot_to_tray):
  1685. mapped = slot_to_tray[slot_id - 1]
  1686. if isinstance(mapped, int) and mapped >= 0:
  1687. global_tray_id = mapped
  1688. elif mapped == -1:
  1689. # The mapping says this slot isn't fed from any tray. The
  1690. # position-based guess below would hand it the Nth loaded
  1691. # tray anyway -- an AMS spool that never moved (#3166), or
  1692. # the tray another slot really used, which that slot then
  1693. # finds already handled and drops (#2880).
  1694. logger.info(
  1695. "[UsageTracker] 3MF: slot_id=%d is unmapped (-1) — nothing charged (used_g=%.1f)",
  1696. slot_id,
  1697. used_g,
  1698. )
  1699. continue
  1700. # Position-based default: sort available tray IDs so external spools (254/255)
  1701. # naturally follow standard AMS trays, matching slicer slot numbering.
  1702. #
  1703. # Filter out AMS slots that have no spool loaded (empty `tray_type`) —
  1704. # BambuStudio/OrcaSlicer compact the slot list when assigning filaments
  1705. # and don't expose empty AMS slots to the user, so the slicer's 3MF
  1706. # slot N maps to the Nth *loaded* tray, not the Nth physical position.
  1707. # Without this filter a "3 AMS slots loaded + 1 empty + external"
  1708. # layout routes the slicer's 4th filament to the empty AMS slot
  1709. # instead of the external (#1607), and the external's spool usage
  1710. # never gets recorded. vt_tray entries are already filtered the
  1711. # same way inside `build_ams_tray_lookup` (line 174 checks
  1712. # `tray_type`), so this just mirrors that for the AMS side.
  1713. tray_is_guessed = global_tray_id is None
  1714. if global_tray_id is None:
  1715. _state = printer_manager.get_status(printer_id)
  1716. _raw = getattr(_state, "raw_data", None) if _state else None
  1717. if _raw:
  1718. from backend.app.services.spoolman_tracking import build_ams_tray_lookup
  1719. _lookup = build_ams_tray_lookup(_raw)
  1720. available_trays = sorted(gid for gid, info in _lookup.items() if info.get("tray_type"))
  1721. if slot_id <= len(available_trays):
  1722. global_tray_id = available_trays[slot_id - 1]
  1723. # Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools)
  1724. if global_tray_id is None:
  1725. global_tray_id = slot_id - 1
  1726. if global_tray_id >= 254:
  1727. # External spool: ams_id=255 (sentinel), tray_id=slot index (0 or 1)
  1728. ams_id = 255
  1729. tray_id = global_tray_id - 254
  1730. elif global_tray_id >= 128:
  1731. ams_id = global_tray_id
  1732. tray_id = 0
  1733. else:
  1734. ams_id = global_tray_id // 4
  1735. tray_id = global_tray_id % 4
  1736. logger.info(
  1737. "[UsageTracker] 3MF: slot_id=%d -> global_tray=%d -> AMS%d-T%d (used_g=%.1f, tray_now_override=%s)",
  1738. slot_id,
  1739. global_tray_id,
  1740. ams_id,
  1741. tray_id,
  1742. used_g,
  1743. tray_now_override,
  1744. )
  1745. key = (ams_id, tray_id)
  1746. if key in covered_before:
  1747. continue
  1748. if tray_is_guessed and key in handled_trays:
  1749. # A guess by position can land a second slot on a tray another slot
  1750. # was charged for. That says nothing about which spool fed it, so
  1751. # it is not charged to that tray's spool as well.
  1752. continue
  1753. spool_id = await _resolve_spool_id_for_tray(
  1754. printer_id=printer_id,
  1755. ams_id=ams_id,
  1756. tray_id=tray_id,
  1757. db=db,
  1758. spool_assignments_snapshot=spool_assignments,
  1759. print_started_at=print_started_at,
  1760. )
  1761. # Use per-layer grams if available, otherwise linear scale
  1762. if layer_grams and slot_id in layer_grams:
  1763. slot_grams = layer_grams[slot_id]
  1764. else:
  1765. slot_grams = used_g * scale
  1766. # A spool swapped by hand on this tray mid-print shares it (#3325).
  1767. shares = _swap_shares(ams_id, tray_id, slot_id, slot_grams) if slot_grams > 0 else None
  1768. if shares is None and spool_id is None:
  1769. # WARNING, not INFO: everything upstream of this line succeeded --
  1770. # the 3MF was found, the grams were read, the tray resolved -- and
  1771. # the print will still report success while this filament is never
  1772. # deducted. At INFO it was invisible under the default log level and
  1773. # absent from the reasoning in support bundles (#2812).
  1774. logger.warning(
  1775. "[UsageTracker] 3MF: no spool assignment at printer %d AMS%d-T%d — %.1fg not deducted",
  1776. printer_id,
  1777. ams_id,
  1778. tray_id,
  1779. used_g,
  1780. )
  1781. unassigned_global_trays.append(global_tray_id)
  1782. continue
  1783. if slot_grams <= 0:
  1784. continue
  1785. for share_spool_id, weight_grams in shares or [(spool_id, slot_grams)]:
  1786. # Load spool
  1787. spool_result = await db.execute(select(Spool).where(Spool.id == share_spool_id))
  1788. spool = spool_result.scalar_one_or_none()
  1789. if not spool:
  1790. continue
  1791. # Update spool
  1792. if not await _charge_spool(db, spool, weight_grams):
  1793. continue
  1794. percent = round(weight_grams / (spool.label_weight or 1000) * 100)
  1795. # Calculate cost for this usage
  1796. cost = None
  1797. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1798. if cost_per_kg > 0:
  1799. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  1800. # Insert usage history record
  1801. history = SpoolUsageHistory(
  1802. spool_id=spool.id,
  1803. printer_id=printer_id,
  1804. print_name=print_name,
  1805. weight_used=round(weight_grams, 1),
  1806. percent_used=percent,
  1807. status=status,
  1808. cost=cost,
  1809. archive_id=archive_id,
  1810. )
  1811. db.add(history)
  1812. handled_trays.add(key)
  1813. results.append(
  1814. {
  1815. "spool_id": spool.id,
  1816. "weight_used": round(weight_grams, 1),
  1817. "percent_used": percent,
  1818. "ams_id": ams_id,
  1819. "tray_id": tray_id,
  1820. "material": spool.material,
  1821. "cost": cost,
  1822. "slot_id": slot_id,
  1823. "color": _spool_color_to_hex(spool.rgba),
  1824. }
  1825. )
  1826. # Determine mapping source for debug logging
  1827. if tray_now_override is not None:
  1828. map_src = ", tray_now"
  1829. elif mapping_source:
  1830. map_src = f", {mapping_source}_map"
  1831. else:
  1832. map_src = ""
  1833. logger.info(
  1834. "[UsageTracker] Spool %d consumed %.1fg (3MF%s%s) on printer %d AMS%d-T%d (%s)",
  1835. spool.id,
  1836. weight_grams,
  1837. " per-layer"
  1838. if (layer_grams and slot_id in layer_grams)
  1839. else (f" scaled {scale:.0%}" if scale < 1 else ""),
  1840. map_src,
  1841. printer_id,
  1842. ams_id,
  1843. tray_id,
  1844. status,
  1845. )
  1846. # --- Adopt the matched inventory spools' colours for the archive (#1494) ---
  1847. # The archive's filament_color was set from the slicer's 3MF at creation
  1848. # time; now that every used slot has been resolved to an inventory spool,
  1849. # the curated spool colour is authoritative. Committed by the caller's
  1850. # `if results: await db.commit()`.
  1851. if archive is not None:
  1852. spool_colors = _archive_colors_from_spools(filament_usage, results)
  1853. if spool_colors:
  1854. joined = ",".join(spool_colors)
  1855. if joined != archive.filament_color:
  1856. logger.info(
  1857. "[UsageTracker] 3MF: archive %s filament_color %r -> %r (from inventory spools)",
  1858. archive_id,
  1859. archive.filament_color,
  1860. joined,
  1861. )
  1862. archive.filament_color = joined
  1863. # Adopt the matched spools' materials too (#2563) — a slot mapped to a
  1864. # differently-typed spool than it was sliced for otherwise records the
  1865. # sliced type in the archive, Print Log and material stats.
  1866. spool_types = _archive_types_from_spools(filament_usage, results)
  1867. if spool_types:
  1868. joined_types = ",".join(spool_types)
  1869. if joined_types != archive.filament_type:
  1870. logger.info(
  1871. "[UsageTracker] 3MF: archive %s filament_type %r -> %r (from inventory spools)",
  1872. archive_id,
  1873. archive.filament_type,
  1874. joined_types,
  1875. )
  1876. archive.filament_type = joined_types
  1877. if unassigned_global_trays:
  1878. from backend.app.services.spool_assignment_notifications import (
  1879. notify_missing_spool_assignments_on_print_complete,
  1880. )
  1881. await notify_missing_spool_assignments_on_print_complete(printer_id, unassigned_global_trays, db, logger)
  1882. return results