spoolman_tracking.py 84 KB

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