spoolman_tracking.py 85 KB

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