spoolman_tracking.py 89 KB

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