spoolman_tracking.py 88 KB

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