spoolman_tracking.py 88 KB

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