spoolman_tracking.py 97 KB

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