spoolman_tracking.py 84 KB

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