spoolman_tracking.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. from sqlalchemy import delete, select
  9. from backend.app.core.config import settings as app_settings
  10. from backend.app.core.database import async_session
  11. from backend.app.services.spoolman import (
  12. SpoolmanClientError,
  13. SpoolmanNotFoundError,
  14. SpoolmanUnavailableError,
  15. get_spoolman_client,
  16. init_spoolman_client,
  17. )
  18. logger = logging.getLogger(__name__)
  19. # Zero UUID used by Bambu printers for empty/unset tray_uuid
  20. _ZERO_UUID = "00000000000000000000000000000000"
  21. _ZERO_TAG_UID = "0000000000000000"
  22. def _is_non_zero_identifier(value: str) -> bool:
  23. """Return True when identifier is non-empty and not all zeros."""
  24. if not value:
  25. return False
  26. return set(value) != {"0"}
  27. def _to_fixed_hex(value: int, width: int) -> str:
  28. """Mirror frontend toFixedHex(): uppercase, zero-padded, fixed width."""
  29. safe = max(0, int(value))
  30. return format(safe, "X").zfill(width)[-width:]
  31. def _hash_serial_to_hex32(serial: str) -> str:
  32. """Mirror frontend hashSerialToHex32() exactly (32-bit FNV-1a)."""
  33. input_str = (serial or "").strip().upper()
  34. hash_value = 0x811C9DC5
  35. for char in input_str:
  36. hash_value ^= ord(char)
  37. hash_value = (hash_value * 0x01000193) & 0xFFFFFFFF
  38. return format(hash_value, "X").zfill(8)
  39. def _global_tray_id_to_ams_slot(global_tray_id: int) -> tuple[int, int]:
  40. """Convert global tray id to (ams_id, tray_id) tuple for fallback tag generation."""
  41. # External spool slots use IDs 254/255 and map to ams_id=255 tray_id=0/1.
  42. if global_tray_id >= 254:
  43. return 255, max(0, global_tray_id - 254)
  44. # AMS-HT units are addressed by ams_id directly and have a single tray.
  45. if global_tray_id >= 128:
  46. return global_tray_id, 0
  47. # Standard AMS units: four trays each.
  48. return global_tray_id // 4, global_tray_id % 4
  49. def _get_fallback_spool_tag(printer_serial: str, global_tray_id: int) -> str:
  50. """Mirror frontend getFallbackSpoolTag(serial, amsId, trayId) exactly."""
  51. if not printer_serial:
  52. return ""
  53. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  54. return get_fallback_spool_tag_for_slot(printer_serial, ams_id, tray_id)
  55. def get_fallback_spool_tag_for_slot(printer_serial: str, ams_id: int, tray_id: int) -> str:
  56. """Public helper matching frontend getFallbackSpoolTag(serial, amsId, trayId).
  57. Used by stale-tag cleanup (#1457) to detect Spoolman spools still holding
  58. this slot's deterministic fallback tag in extra.tag.
  59. """
  60. if not printer_serial:
  61. return ""
  62. return f"{_hash_serial_to_hex32(printer_serial)}{_to_fixed_hex(ams_id, 4)}{_to_fixed_hex(tray_id, 4)}"
  63. def _resolve_spool_tag(tray_info: dict, printer_serial: str = "", global_tray_id: int | None = None) -> str:
  64. """Get the best spool identifier from tray info (prefer tray_uuid over tag_uid).
  65. Returns empty string if no usable identifier is found.
  66. """
  67. tray_uuid = str(tray_info.get("tray_uuid", "") or "")
  68. tag_uid = str(tray_info.get("tag_uid", "") or "")
  69. if tray_uuid and tray_uuid != _ZERO_UUID and _is_non_zero_identifier(tray_uuid):
  70. return tray_uuid
  71. if tag_uid and tag_uid != _ZERO_TAG_UID and _is_non_zero_identifier(tag_uid):
  72. return tag_uid
  73. if global_tray_id is not None:
  74. return _get_fallback_spool_tag(printer_serial, global_tray_id)
  75. return ""
  76. async def _get_printer_serial(printer_id: int) -> str:
  77. """Get printer serial for deterministic fallback tag generation."""
  78. from backend.app.models.printer import Printer
  79. from backend.app.services.printer_manager import printer_manager
  80. printer_info = printer_manager.get_printer(printer_id)
  81. if printer_info and printer_info.serial_number:
  82. return printer_info.serial_number
  83. async with async_session() as db:
  84. result = await db.execute(select(Printer.serial_number).where(Printer.id == printer_id))
  85. serial_number = result.scalar_one_or_none()
  86. return serial_number or ""
  87. def _resolve_global_tray_id(slot_id: int, slot_to_tray: list | None, ams_trays: dict | None = None) -> int:
  88. """Map a 1-based slot_id to a global_tray_id using optional custom mapping.
  89. Custom mapping: slot_to_tray[slot_id - 1] is used when >= 0.
  90. A value of -1 in the custom mapping means the slicer routed this slot to
  91. the external spool. BambuStudio converts virtual tray IDs (254/255) to -1
  92. in the flat ams_mapping array before sending to the printer — see
  93. start_print() in bambu_mqtt.py which documents this convention. We mirror
  94. it here: when -1 is seen, look up the external spool's actual
  95. global_tray_id (254/255) in ams_trays rather than falling through to the
  96. position-based default (which would map slot_id=1 to the first AMS tray
  97. and credit an unrelated spool — see #1276, regression of #853).
  98. Position-based default: uses sorted ams_trays keys so external spools (ID 254/255)
  99. naturally follow standard AMS trays, matching the slicer's slot numbering.
  100. Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools).
  101. """
  102. if slot_to_tray and slot_id <= len(slot_to_tray):
  103. mapped_tray = slot_to_tray[slot_id - 1]
  104. if mapped_tray >= 0:
  105. return mapped_tray
  106. if mapped_tray == -1 and ams_trays:
  107. # -1 means external spool. 254 = VIRTUAL_TRAY_DEPUTY_ID (main on
  108. # single-nozzle, left/deputy on H2D dual-nozzle); 255 =
  109. # VIRTUAL_TRAY_MAIN_ID. Prefer 254 when both exist since that's
  110. # what single-nozzle printers report via tray_now.
  111. for ext_id in (254, 255):
  112. if ext_id in ams_trays:
  113. return ext_id
  114. # Position-based default: sort available tray IDs so external spools (254/255)
  115. # come after standard AMS trays, matching the slicer's slot assignment order.
  116. if ams_trays:
  117. sorted_tray_ids = sorted(ams_trays.keys())
  118. if slot_id <= len(sorted_tray_ids):
  119. return sorted_tray_ids[slot_id - 1]
  120. return slot_id - 1
  121. def build_ams_tray_lookup(raw_data: dict) -> dict[int, dict]:
  122. """Build lookup of global_tray_id -> tray info from printer state.
  123. Returns: {0: {"tray_uuid": "...", "tag_uid": "...", "tray_type": "..."}, ...}
  124. """
  125. lookup = {}
  126. ams_data = raw_data.get("ams", [])
  127. for ams_unit in ams_data:
  128. ams_id = int(ams_unit.get("id", 0))
  129. for tray in ams_unit.get("tray", []):
  130. tray_id = int(tray.get("id", 0))
  131. # AMS-HT units have IDs starting at 128 with a single tray
  132. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  133. lookup[global_tray_id] = {
  134. "tray_uuid": tray.get("tray_uuid", ""),
  135. "tag_uid": tray.get("tag_uid", ""),
  136. "tray_type": tray.get("tray_type", ""),
  137. }
  138. # External spool(s) (vt_tray is a list, global_tray_id from each entry's "id")
  139. for vt in raw_data.get("vt_tray") or []:
  140. if vt.get("tray_type"):
  141. tray_id = int(vt.get("id", 254))
  142. lookup[tray_id] = {
  143. "tray_uuid": vt.get("tray_uuid", ""),
  144. "tag_uid": vt.get("tag_uid", ""),
  145. "tray_type": vt.get("tray_type", ""),
  146. }
  147. return lookup
  148. def _snapshot_tray_remain(raw_data: dict) -> dict[str, dict]:
  149. """Capture per-slot ``remain%`` + ``tray_uuid`` at print start so the
  150. completion path can compute a remain-delta when 3MF data doesn't cover
  151. the slot (or there's no 3MF at all — #1820).
  152. Returns ``{"<ams_id>-<tray_id>": {"remain": int, "tray_uuid": str}}``.
  153. Only slots whose ``remain`` is a valid 0..100 int are included; invalid
  154. values mean the AMS hasn't read the spool yet and a delta would be
  155. meaningless. Mirrors the gate in
  156. ``usage_tracker.on_print_start:309``.
  157. """
  158. snapshot: dict[str, dict] = {}
  159. ams_raw = raw_data.get("ams", [])
  160. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  161. for ams_unit in ams_data:
  162. if not isinstance(ams_unit, dict):
  163. continue
  164. ams_id = int(ams_unit.get("id", 0))
  165. for tray in ams_unit.get("tray", []):
  166. if not isinstance(tray, dict):
  167. continue
  168. tray_id = int(tray.get("id", 0))
  169. remain = tray.get("remain", -1)
  170. if isinstance(remain, int) and 0 <= remain <= 100:
  171. snapshot[f"{ams_id}-{tray_id}"] = {
  172. "remain": remain,
  173. "tray_uuid": tray.get("tray_uuid", "") or "",
  174. }
  175. vt_tray_raw = raw_data.get("vt_tray") or []
  176. if isinstance(vt_tray_raw, dict):
  177. vt_tray_raw = [vt_tray_raw]
  178. for vt in vt_tray_raw:
  179. if not isinstance(vt, dict):
  180. continue
  181. vt_id = int(vt.get("id", 254))
  182. # 254 → (255, 0), 255 → (255, 1) — matches usage_tracker's encoding.
  183. vt_tray_id = vt_id - 254
  184. remain = vt.get("remain", -1)
  185. if isinstance(remain, int) and 0 <= remain <= 100:
  186. snapshot[f"255-{vt_tray_id}"] = {
  187. "remain": remain,
  188. "tray_uuid": vt.get("tray_uuid", "") or "",
  189. }
  190. return snapshot
  191. async def store_print_data(
  192. printer_id: int,
  193. archive_id: int,
  194. file_path: str,
  195. db,
  196. printer_manager,
  197. ams_mapping: list[int] | None = None,
  198. plate_id: int | None = None,
  199. ):
  200. """Store Spoolman tracking data at print start (persisted to database).
  201. Per-print tracking is the primary weight-update path for Spoolman, mirroring
  202. how the internal Filament Inventory works. The legacy AMS-remain%-based sync
  203. is no longer used as a weight writer (#1119), so this runs whenever Spoolman
  204. is enabled regardless of the deprecated `spoolman_disable_weight_sync` flag.
  205. ``plate_id``, when set, scopes the 3MF filament extract to a single plate so
  206. queue / direct-Print dispatch of plate N of a multi-plate file doesn't
  207. attribute every plate's filament to the printed spool (#1697). When unset,
  208. the queue item's plate_id (if any) is used; otherwise the whole-file sum is
  209. extracted, which is correct for direct prints that target the first/only
  210. plate of a single-plate file.
  211. """
  212. from backend.app.api.routes.settings import get_setting
  213. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  214. from backend.app.models.print_queue import PrintQueueItem
  215. from backend.app.utils.threemf_tools import (
  216. extract_filament_properties_from_3mf,
  217. extract_filament_usage_from_3mf,
  218. extract_layer_filament_usage_from_3mf,
  219. )
  220. # Check if Spoolman is enabled
  221. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  222. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  223. return
  224. # Get current AMS tray state up front — needed both for the 3MF path's
  225. # ams_trays field and for the remain%-delta snapshot (#1820 fallback for
  226. # no-3MF "Untitled" prints, mirroring usage_tracker.on_print_start).
  227. state = printer_manager.get_status(printer_id)
  228. ams_trays: dict[int, dict] = {}
  229. tray_remain_start: dict[str, dict] = {}
  230. if state and state.raw_data:
  231. ams_trays = build_ams_tray_lookup(state.raw_data)
  232. tray_remain_start = _snapshot_tray_remain(state.raw_data)
  233. # Try to read per-slot filament estimates from the 3MF. Two paths can
  234. # leave ``filament_usage`` empty: (1) fallback archive (no .gcode.3mf
  235. # was downloadable from the printer — "Untitled" prints, see #1820),
  236. # (2) 3MF present but slice_info missing per-filament estimates.
  237. # Both fall through to the remain%-delta path at completion.
  238. filament_usage: list | None = None
  239. layer_usage_json: dict | None = None
  240. filament_properties: dict | None = None
  241. full_path = (
  242. app_settings.base_dir / file_path
  243. ) # SEC-PATH-OK: file_path is archive.file_path / library_file.file_path — DB-stored, internally generated
  244. threemf_available = bool(file_path) and full_path.exists()
  245. queue_item = None
  246. if threemf_available:
  247. # Resolve the queue item once — used both for the plate-scoped 3MF parsing
  248. # fallback (#1697: multi-plate file dispatched for one plate must only count
  249. # that plate's filament) and for the ams_mapping fallback below.
  250. queue_result = await db.execute(
  251. select(PrintQueueItem)
  252. .where(PrintQueueItem.archive_id == archive_id)
  253. .where(PrintQueueItem.status == "printing")
  254. )
  255. queue_item = queue_result.scalar_one_or_none()
  256. # Caller-supplied plate_id wins (direct-Print path); fall back to the queue
  257. # item's plate_id (queue dispatch path).
  258. effective_plate_id = (
  259. plate_id if plate_id is not None else (queue_item.plate_id if queue_item is not None else None)
  260. )
  261. filament_usage = extract_filament_usage_from_3mf(full_path, effective_plate_id) or None
  262. layer_usage = extract_layer_filament_usage_from_3mf(full_path)
  263. if layer_usage:
  264. # Convert int keys to string for JSON serialization
  265. layer_usage_json = {str(k): v for k, v in layer_usage.items()}
  266. logger.debug("[SPOOLMAN] Parsed %s layers from G-code", len(layer_usage))
  267. filament_properties = extract_filament_properties_from_3mf(full_path)
  268. else:
  269. # No 3MF on disk — common for "Untitled" prints whose .gcode.3mf
  270. # was never on the printer's FTP. Logged at debug since the
  271. # fallback path below picks up the slack when remain% is available.
  272. logger.debug("[SPOOLMAN] 3MF file not available: %s", full_path)
  273. # If neither path has anything useful, there's nothing to track.
  274. if not filament_usage and not tray_remain_start:
  275. if threemf_available:
  276. logger.debug("[SPOOLMAN] No filament usage data in 3MF for archive %s", archive_id)
  277. return
  278. # Prefer the explicit mapping captured from the print command, then fall back
  279. # to any queue mapping stored for scheduled/reprint jobs.
  280. slot_to_tray = ams_mapping if ams_mapping is not None else None
  281. if not slot_to_tray and queue_item and queue_item.ams_mapping:
  282. try:
  283. slot_to_tray = json.loads(queue_item.ams_mapping)
  284. except json.JSONDecodeError:
  285. pass # Ignore malformed AMS mapping; fall back to default slot assignment
  286. # Delete any existing row for this printer/archive (shouldn't exist, but just in case)
  287. await db.execute(
  288. delete(ActivePrintSpoolman)
  289. .where(ActivePrintSpoolman.printer_id == printer_id)
  290. .where(ActivePrintSpoolman.archive_id == archive_id)
  291. )
  292. # Insert new tracking data. ``filament_usage`` may be None for the
  293. # no-3MF case; report_usage falls back to ``tray_remain_start``.
  294. tracking = ActivePrintSpoolman(
  295. printer_id=printer_id,
  296. archive_id=archive_id,
  297. filament_usage=filament_usage,
  298. ams_trays=ams_trays,
  299. slot_to_tray=slot_to_tray,
  300. layer_usage=layer_usage_json,
  301. filament_properties=filament_properties,
  302. tray_remain_start=tray_remain_start or None,
  303. )
  304. db.add(tracking)
  305. await db.commit()
  306. logger.info(
  307. "[SPOOLMAN] Stored tracking data for print: printer=%s, archive=%s (3mf=%s, remain_snapshot=%d slot(s))",
  308. printer_id,
  309. archive_id,
  310. "yes" if filament_usage else "no",
  311. len(tray_remain_start),
  312. )
  313. logger.debug("[SPOOLMAN] Filament usage: %s", filament_usage)
  314. logger.debug("[SPOOLMAN] AMS trays: %s", list(ams_trays.keys()))
  315. if slot_to_tray:
  316. logger.debug("[SPOOLMAN] Custom slot mapping: %s", slot_to_tray)
  317. if layer_usage_json:
  318. logger.debug("[SPOOLMAN] Layer usage data available for partial tracking")
  319. async def cleanup_tracking(
  320. printer_id: int,
  321. archive_id: int,
  322. db,
  323. last_layer_num: int | None = None,
  324. last_progress: int | None = None,
  325. ):
  326. """Report partial usage and clean up Spoolman tracking data for failed/aborted prints."""
  327. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  328. # Get tracking data first (needed for partial usage reporting)
  329. result = await db.execute(
  330. select(ActivePrintSpoolman)
  331. .where(ActivePrintSpoolman.printer_id == printer_id)
  332. .where(ActivePrintSpoolman.archive_id == archive_id)
  333. )
  334. tracking = result.scalar_one_or_none()
  335. if not tracking:
  336. logger.debug("[SPOOLMAN] No tracking data to clean up for printer=%s, archive=%s", printer_id, archive_id)
  337. return
  338. # Try to report partial usage before cleanup
  339. try:
  340. await _report_partial_usage(
  341. printer_id,
  342. tracking,
  343. last_layer_num=last_layer_num,
  344. last_progress=last_progress,
  345. )
  346. except Exception as e:
  347. logger.warning("[SPOOLMAN] Partial usage report failed: %s", e)
  348. # Delete tracking data
  349. await db.execute(
  350. delete(ActivePrintSpoolman)
  351. .where(ActivePrintSpoolman.printer_id == printer_id)
  352. .where(ActivePrintSpoolman.archive_id == archive_id)
  353. )
  354. await db.commit()
  355. logger.debug("[SPOOLMAN] Cleaned up tracking data for printer=%s, archive=%s", printer_id, archive_id)
  356. async def _get_spoolman_client_with_fallback():
  357. """Get Spoolman client, initializing from settings if needed.
  358. Returns (client, is_healthy) tuple. Client may be None.
  359. """
  360. client = await get_spoolman_client()
  361. if not client:
  362. async with async_session() as db:
  363. from backend.app.api.routes.settings import get_setting
  364. spoolman_url = await get_setting(db, "spoolman_url")
  365. if spoolman_url:
  366. try:
  367. client = await init_spoolman_client(spoolman_url)
  368. except ValueError as exc:
  369. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  370. return None
  371. if not client:
  372. return None
  373. if not await client.health_check():
  374. logger.warning("Spoolman health check failed; skipping usage reporting")
  375. return None
  376. return client
  377. async def _resolve_spool_id_via_slot_assignment(printer_id: int, ams_id: int, tray_id: int) -> int | None:
  378. """Look up the Spoolman spool ID locally bound to (printer, ams, tray).
  379. Fallback path for #1459: when a tag-less spool was assigned via the
  380. Bambuddy UI, the user's deterministic fallback tag is intentionally NOT
  381. written to Spoolman's extra.tag (kept clean per #1457), so
  382. find_spool_by_tag misses. The local spoolman_slot_assignments table is
  383. the authoritative binding for those spools.
  384. """
  385. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  386. async with async_session() as db:
  387. result = await db.execute(
  388. select(SpoolmanSlotAssignment.spoolman_spool_id).where(
  389. SpoolmanSlotAssignment.printer_id == printer_id,
  390. SpoolmanSlotAssignment.ams_id == ams_id,
  391. SpoolmanSlotAssignment.tray_id == tray_id,
  392. )
  393. )
  394. return result.scalar_one_or_none()
  395. async def _report_spool_usage_for_slots(
  396. client,
  397. filament_usage_items: list[tuple[int, float]],
  398. ams_trays: dict[int, dict],
  399. slot_to_tray: list | None,
  400. method_label: str,
  401. printer_serial: str = "",
  402. printer_id: int | None = None,
  403. slot_colors_out: dict[int, str] | None = None,
  404. ) -> int:
  405. """Report usage to Spoolman for a list of (slot_id, grams) pairs.
  406. Resolution order per slot: (1) Spoolman extra.tag match against the
  407. tray's RFID or deterministic fallback tag, (2) #1459 fallback —
  408. local spoolman_slot_assignments table keyed by (printer_id, ams_id,
  409. tray_id). Without (2), tag-less spools assigned via the Bambuddy UI
  410. never get their weight decremented because their extra.tag is empty
  411. on the Spoolman side.
  412. When ``slot_colors_out`` is provided it is populated with
  413. ``{slot_id: color_hex}`` for every resolved spool — used by
  414. :func:`report_usage` to stamp the archive's filament colour from the
  415. Spoolman spool rather than the slicer's 3MF value (#1494).
  416. Returns number of spools successfully updated.
  417. """
  418. spools_updated = 0
  419. for slot_id, grams_used in filament_usage_items:
  420. if grams_used <= 0:
  421. continue
  422. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  423. tray_info = ams_trays.get(global_tray_id)
  424. if not tray_info:
  425. logger.debug("[SPOOLMAN] Slot %s: no tray at global_tray_id %s", slot_id, global_tray_id)
  426. continue
  427. is_external = global_tray_id >= 254
  428. tray_type = tray_info.get("tray_type", "")
  429. logger.debug(
  430. "[SPOOLMAN] Slot %s resolved to global_tray_id %s (tray_type=%s, external=%s)",
  431. slot_id,
  432. global_tray_id,
  433. tray_type or "unknown",
  434. is_external,
  435. )
  436. spool_id_to_use: int | None = None
  437. resolution_path = ""
  438. # color_hex of the resolved spool's filament, for the #1494 archive
  439. # colour rewrite. The tag path already has the full spool object;
  440. # the slot-assignment path only yields an id and is fetched below.
  441. spool_color_hex: str | None = None
  442. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  443. if spool_tag:
  444. spool = await client.find_spool_by_tag(spool_tag)
  445. if spool:
  446. spool_id_to_use = spool["id"]
  447. resolution_path = "tag"
  448. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  449. if spool_id_to_use is None and printer_id is not None:
  450. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  451. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  452. if spool_id_to_use is not None:
  453. resolution_path = "slot-assignment"
  454. if spool_id_to_use is None:
  455. logger.debug(
  456. "[SPOOLMAN] Slot %s: no spool resolved (tag=%s, no slot-assignment)",
  457. slot_id,
  458. spool_tag[:16] if spool_tag else "none",
  459. )
  460. continue
  461. # Record the spool's filament colour for the archive rewrite (#1494).
  462. # The slot-assignment path resolved only an id, so fetch the spool.
  463. # Strictly best-effort: a colour-fetch failure must never abort the
  464. # weight reporting for the remaining slots, so the catch is broad.
  465. if slot_colors_out is not None:
  466. if spool_color_hex is None:
  467. try:
  468. full_spool = await client.get_spool(spool_id_to_use)
  469. spool_color_hex = (full_spool.get("filament") or {}).get("color_hex")
  470. except Exception as exc: # noqa: BLE001 — colour is non-critical
  471. logger.debug("[SPOOLMAN] Slot %s: could not fetch spool colour: %s", slot_id, exc)
  472. if spool_color_hex:
  473. slot_colors_out[slot_id] = spool_color_hex
  474. try:
  475. await client.use_spool(spool_id_to_use, grams_used)
  476. logger.info(
  477. "[SPOOLMAN] %s: slot %s: %sg -> spool %s (via %s)",
  478. method_label,
  479. slot_id,
  480. grams_used,
  481. spool_id_to_use,
  482. resolution_path,
  483. )
  484. spools_updated += 1
  485. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  486. logger.warning("[SPOOLMAN] Failed to record usage for spool %s: %s", spool_id_to_use, exc)
  487. return spools_updated
  488. async def _report_spool_usage_split_by_tray_changes(
  489. client,
  490. filament_usage: list[dict],
  491. tray_changes: list[tuple[int, int]],
  492. ams_trays: dict[int, dict],
  493. layer_usage: dict[int, dict[int, float]] | None,
  494. filament_properties: dict | None,
  495. total_layers: int,
  496. last_layer_num: int,
  497. method_label: str,
  498. printer_serial: str,
  499. printer_id: int,
  500. slot_colors_out: dict[int, str] | None = None,
  501. ) -> tuple[int, set[int]]:
  502. """Split each slot's grams across ``tray_changes`` and charge per-segment.
  503. Mirrors ``usage_tracker`` Path 1's tray-switch branch so Spoolman and
  504. the internal Spool inventory attribute mid-print AMS-backup switches
  505. identically (#1793 — reporter's origin spool was over-charged the
  506. whole print because this path didn't exist). ``compute_tray_split_grams``
  507. holds the shared segment-math; this function wraps the per-segment
  508. spool resolution + ``use_spool`` sink for the Spoolman side.
  509. Returns ``(spools_updated, handled_global_tray_ids)`` — the caller
  510. passes ``handled_global_tray_ids`` into the remain-delta fallback so
  511. a tray attributed here is not double-charged there.
  512. """
  513. from backend.app.utils.tray_split import compute_tray_split_grams
  514. spools_updated = 0
  515. handled_global_tray_ids: set[int] = set()
  516. for usage in filament_usage:
  517. slot_id = usage.get("slot_id", 0)
  518. total_weight = usage.get("used_g", 0)
  519. if total_weight <= 0 or slot_id <= 0:
  520. continue
  521. props = (filament_properties or {}).get(str(slot_id)) or (filament_properties or {}).get(slot_id) or {}
  522. segments = compute_tray_split_grams(
  523. tray_changes=tray_changes,
  524. total_weight=float(total_weight),
  525. slot_id=slot_id,
  526. layer_usage=layer_usage,
  527. density=float(props.get("density", 1.24)),
  528. diameter=float(props.get("diameter", 1.75)),
  529. total_layers=total_layers,
  530. last_layer_num=last_layer_num,
  531. )
  532. for seg_idx, tray_global, segment_grams in segments:
  533. if segment_grams <= 0:
  534. continue
  535. # Mark this tray as handled BEFORE the resolution attempt so
  536. # remain-delta doesn't double-charge it, even if we fail to
  537. # find a spool below. Matches usage_tracker behaviour: the
  538. # tray was physically fed from during this print, whether or
  539. # not Spoolman happens to have a matching row.
  540. handled_global_tray_ids.add(tray_global)
  541. tray_info = ams_trays.get(tray_global) or {}
  542. spool_id_to_use: int | None = None
  543. resolution_path = ""
  544. spool_color_hex: str | None = None
  545. spool_tag = _resolve_spool_tag(tray_info, printer_serial, tray_global) if tray_info else ""
  546. if spool_tag:
  547. spool = await client.find_spool_by_tag(spool_tag)
  548. if spool:
  549. spool_id_to_use = spool["id"]
  550. resolution_path = "tag"
  551. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  552. if spool_id_to_use is None:
  553. seg_ams_id, seg_tray_id = _global_tray_id_to_ams_slot(tray_global)
  554. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, seg_ams_id, seg_tray_id)
  555. if spool_id_to_use is not None:
  556. resolution_path = "slot-assignment"
  557. if spool_id_to_use is None:
  558. logger.info(
  559. "[SPOOLMAN] Split slot %s seg %s tray=%d: no spool resolved — %.2fg lost from split accounting",
  560. slot_id,
  561. seg_idx,
  562. tray_global,
  563. segment_grams,
  564. )
  565. continue
  566. # Colour rewrite (#1494) — first segment for a slot wins. The
  567. # UI displays a single colour per slot, so later segments on the
  568. # same slot don't overwrite (a backup swap can be a different
  569. # colour but the archive card stays consistent with the origin).
  570. if slot_colors_out is not None and slot_id not in slot_colors_out:
  571. if spool_color_hex is None:
  572. try:
  573. full_spool = await client.get_spool(spool_id_to_use)
  574. spool_color_hex = (full_spool.get("filament") or {}).get("color_hex")
  575. except Exception as exc: # noqa: BLE001 — colour is non-critical
  576. logger.debug("[SPOOLMAN] Split slot %s: could not fetch spool colour: %s", slot_id, exc)
  577. if spool_color_hex:
  578. slot_colors_out[slot_id] = spool_color_hex
  579. try:
  580. await client.use_spool(spool_id_to_use, round(segment_grams, 2))
  581. logger.info(
  582. "[SPOOLMAN] %s: slot %s seg %s tray=%d: %.2fg -> spool %s (via %s)",
  583. method_label,
  584. slot_id,
  585. seg_idx,
  586. tray_global,
  587. segment_grams,
  588. spool_id_to_use,
  589. resolution_path,
  590. )
  591. spools_updated += 1
  592. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  593. logger.warning(
  594. "[SPOOLMAN] Split slot %s seg %s: failed to record usage for spool %s: %s",
  595. slot_id,
  596. seg_idx,
  597. spool_id_to_use,
  598. exc,
  599. )
  600. return spools_updated, handled_global_tray_ids
  601. async def _report_partial_usage(
  602. printer_id: int,
  603. tracking,
  604. last_layer_num: int | None = None,
  605. last_progress: int | None = None,
  606. ):
  607. """Report partial filament usage based on actual G-code layer data.
  608. Uses per-layer cumulative extrusion from G-code parsing for accurate
  609. multi-material tracking. Falls back to linear interpolation if G-code
  610. data is unavailable.
  611. """
  612. from backend.app.services.printer_manager import printer_manager
  613. from backend.app.utils.threemf_tools import get_cumulative_usage_at_layer, mm_to_grams
  614. async with async_session() as db:
  615. from backend.app.api.routes.settings import get_setting
  616. # Check if partial usage reporting is enabled (default: true)
  617. report_partial = await get_setting(db, "spoolman_report_partial_usage")
  618. if report_partial and report_partial.lower() == "false":
  619. logger.debug("[SPOOLMAN] Partial usage reporting disabled by setting")
  620. return
  621. # Check if Spoolman is enabled
  622. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  623. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  624. return
  625. # Get current printer state for layer progress.
  626. # On failed/aborted prints the firmware may already reset to IDLE with layer=0,
  627. # so we fall back to completion-time hints captured from MQTT.
  628. state = printer_manager.get_status(printer_id)
  629. current_layer = state.layer_num if state else None
  630. total_layers = state.total_layers if state else None
  631. if (not current_layer or current_layer <= 0) and last_layer_num and last_layer_num > 0:
  632. current_layer = last_layer_num
  633. logger.debug("[SPOOLMAN] Using captured last_layer_num=%s for partial usage", current_layer)
  634. progress_ratio_from_event = None
  635. if last_progress is not None:
  636. try:
  637. progress_ratio_from_event = min(max(float(last_progress), 0.0), 100.0) / 100.0
  638. except (TypeError, ValueError):
  639. progress_ratio_from_event = None
  640. if (not current_layer or current_layer <= 0) and progress_ratio_from_event and total_layers and total_layers > 0:
  641. current_layer = max(1, int(round(total_layers * progress_ratio_from_event)))
  642. logger.debug(
  643. "[SPOOLMAN] Estimated layer from last_progress=%s%% and total_layers=%s -> %s",
  644. last_progress,
  645. total_layers,
  646. current_layer,
  647. )
  648. if not current_layer or current_layer <= 0:
  649. logger.debug(
  650. "[SPOOLMAN] No progress to report (layer 0/unknown, last_layer_num=%s, last_progress=%s)",
  651. last_layer_num,
  652. last_progress,
  653. )
  654. return
  655. logger.info("[SPOOLMAN] Reporting partial usage at layer %s/%s", current_layer, total_layers or "?")
  656. # Get tracking data
  657. layer_usage = tracking.layer_usage
  658. filament_properties = tracking.filament_properties or {}
  659. filament_usage = tracking.filament_usage or []
  660. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  661. slot_to_tray = tracking.slot_to_tray
  662. tray_remain_start = tracking.tray_remain_start or {}
  663. printer_serial = await _get_printer_serial(printer_id)
  664. client = await _get_spoolman_client_with_fallback()
  665. if not client:
  666. logger.warning("[SPOOLMAN] Not reachable for partial usage reporting")
  667. return
  668. # No-3MF aborted print (#1820 mirror of the completion path): nothing in
  669. # filament_usage or layer_usage to base partial estimates on, but the
  670. # remain%-delta snapshot we captured at start still describes consumption
  671. # up to the abort moment. Write it the same way report_usage's fallback
  672. # does, then return — there's no 3MF-derived partial to layer on top.
  673. # ``state`` was already fetched at the top of the function for current_layer.
  674. if not filament_usage and not layer_usage and tray_remain_start:
  675. current_lookup = _snapshot_tray_remain(state.raw_data) if state and state.raw_data else {}
  676. await _report_remain_delta_for_slots(
  677. client,
  678. printer_id=printer_id,
  679. tray_remain_start=tray_remain_start,
  680. current_lookup=current_lookup,
  681. handled_global_tray_ids=set(),
  682. archive_id=getattr(tracking, "archive_id", -1),
  683. )
  684. return
  685. # Try to use accurate G-code parsed data
  686. if layer_usage:
  687. layer_usage_int = {
  688. int(layer): {int(fid): mm for fid, mm in filaments.items()} for layer, filaments in layer_usage.items()
  689. }
  690. usage_mm = get_cumulative_usage_at_layer(layer_usage_int, current_layer)
  691. if usage_mm:
  692. logger.info("[SPOOLMAN] Using G-code parsed data for layer %s", current_layer)
  693. # Build (slot_id, grams) list using Spoolman densities with 3MF fallback
  694. usage_items = []
  695. for filament_id, mm_used in usage_mm.items():
  696. slot_id = filament_id + 1 # filament_id is 0-based, slot_id is 1-based
  697. # Get density from Spoolman (most accurate), fall back to 3MF, then PLA default
  698. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  699. tray_info = ams_trays.get(global_tray_id)
  700. density = None
  701. diameter = 1.75
  702. if tray_info:
  703. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  704. if spool_tag:
  705. spool = await client.find_spool_by_tag(spool_tag)
  706. if spool:
  707. filament_data = spool.get("filament", {})
  708. density = filament_data.get("density")
  709. diameter = filament_data.get("diameter", 1.75)
  710. if not density:
  711. props = filament_properties.get(str(slot_id), filament_properties.get(slot_id, {}))
  712. density = props.get("density", 1.24)
  713. logger.debug("[SPOOLMAN] Using fallback density %s for slot %s", density, slot_id)
  714. grams_used = round(mm_to_grams(mm_used, diameter, density), 2)
  715. usage_items.append((slot_id, grams_used))
  716. spools_updated = await _report_spool_usage_for_slots(
  717. client,
  718. usage_items,
  719. ams_trays,
  720. slot_to_tray,
  721. "Partial (G-code)",
  722. printer_serial,
  723. printer_id=printer_id,
  724. )
  725. if spools_updated > 0:
  726. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using G-code data", spools_updated)
  727. return
  728. # Fallback: linear interpolation (if no G-code data available)
  729. progress_ratio = None
  730. if total_layers and total_layers > 0:
  731. progress_ratio = min(current_layer / total_layers, 1.0)
  732. elif progress_ratio_from_event is not None:
  733. progress_ratio = progress_ratio_from_event
  734. if progress_ratio is None:
  735. logger.debug(
  736. "[SPOOLMAN] Cannot use linear fallback: total_layers=%s, last_progress=%s",
  737. total_layers,
  738. last_progress,
  739. )
  740. return
  741. logger.info("[SPOOLMAN] Falling back to linear interpolation (%s)", progress_ratio)
  742. usage_items = []
  743. for usage in filament_usage:
  744. slot_id = usage.get("slot_id", 0)
  745. total_used_g = usage.get("used_g", 0)
  746. if total_used_g > 0:
  747. partial_used_g = round(total_used_g * progress_ratio, 2)
  748. usage_items.append((slot_id, partial_used_g))
  749. spools_updated = await _report_spool_usage_for_slots(
  750. client,
  751. usage_items,
  752. ams_trays,
  753. slot_to_tray,
  754. "Partial (linear)",
  755. printer_serial,
  756. printer_id=printer_id,
  757. )
  758. if spools_updated > 0:
  759. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using linear interpolation", spools_updated)
  760. async def report_usage(printer_id: int, archive_id: int):
  761. """Report filament usage to Spoolman after print completion.
  762. Two writers, mirroring the internal-inventory split in usage_tracker:
  763. 1. **3MF path (primary)** — per-filament slice estimates captured at
  764. print start drive a precise per-slot ``use_spool`` call.
  765. 2. **AMS remain%-delta (fallback)** — for slots the 3MF path didn't
  766. handle (including the no-3MF "Untitled" case from #1820): compute
  767. ``start_remain - current_remain``, multiply by the resolved
  768. Spoolman filament's reference weight, and write the delta. Mirrors
  769. ``usage_tracker.on_print_complete`` Path 2 (line 517).
  770. """
  771. async with async_session() as db:
  772. from backend.app.api.routes.settings import get_setting
  773. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  774. # Get tracking data stored at print start
  775. result = await db.execute(
  776. select(ActivePrintSpoolman)
  777. .where(ActivePrintSpoolman.printer_id == printer_id)
  778. .where(ActivePrintSpoolman.archive_id == archive_id)
  779. )
  780. tracking = result.scalar_one_or_none()
  781. if not tracking:
  782. logger.info("[SPOOLMAN] No tracking data for print (printer=%s, archive=%s)", printer_id, archive_id)
  783. return
  784. filament_usage = tracking.filament_usage or []
  785. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  786. slot_to_tray = tracking.slot_to_tray
  787. tray_remain_start = tracking.tray_remain_start or {}
  788. # ``layer_usage`` and ``filament_properties`` were added later than
  789. # the base tracking fields; use ``getattr`` so tests that stub
  790. # ``tracking`` as a lightweight SimpleNamespace stay valid, and
  791. # historic ORM rows loaded without these columns can't AttributeError
  792. # on read.
  793. layer_usage_raw = getattr(tracking, "layer_usage", None) or {}
  794. filament_properties = getattr(tracking, "filament_properties", None) or {}
  795. printer_serial = await _get_printer_serial(printer_id)
  796. # Delete tracking row (we're done with it)
  797. await db.delete(tracking)
  798. await db.commit()
  799. if not filament_usage and not tray_remain_start:
  800. logger.debug("[SPOOLMAN] No usage data or remain-snapshot for archive %s", archive_id)
  801. return
  802. # Check if Spoolman is enabled
  803. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  804. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  805. return
  806. client = await _get_spoolman_client_with_fallback()
  807. if not client:
  808. logger.warning("[SPOOLMAN] Not reachable for usage reporting")
  809. return
  810. # Consult the live printer state for the tray-change log written by
  811. # ``bambu_mqtt.py`` on every mid-print ``tray_now`` change (#957).
  812. # When there's more than one entry, the print traversed >1 AMS tray
  813. # and the split path attributes each segment to the tray that was
  814. # loaded at the time — matches the internal Spool inventory writer
  815. # in ``usage_tracker.py``. Without this, an AMS-backup runout switch
  816. # charges the whole slot to the origin spool and pushes it past
  817. # ``initial_weight`` (#1793).
  818. #
  819. # Split only for SINGLE-slot prints — same gate as
  820. # ``usage_tracker.py:1002``. Multi-slot (multi-colour) prints
  821. # naturally cycle trays for every colour change, so splitting each
  822. # slot's grams across ALL tray_change_log entries would attribute
  823. # slot 1's grams to the segments where slot 2's tray was loaded and
  824. # vice versa. Multi-slot prints fall through to the existing
  825. # single-tray path (which uses the stable ``slot_to_tray`` mapping).
  826. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  827. tray_changes: list[tuple[int, int]] = []
  828. _state = None
  829. if len(nonzero_slots) == 1:
  830. from backend.app.services.printer_manager import printer_manager as _pm
  831. _state = _pm.get_status(printer_id)
  832. if _state is not None:
  833. tray_changes = list(getattr(_state, "tray_change_log", []) or [])
  834. _total_layers = int(getattr(_state, "total_layers", 0) or 0) if _state else 0
  835. _current_layer = int(getattr(_state, "layer_num", 0) or 0) if _state else 0
  836. # For the linear-fallback denominator when total_layers is 0 (P1S
  837. # firmware resets it at print end). At completion the current layer
  838. # is the print's last valid layer.
  839. _layer_denom_hint = _total_layers or _current_layer
  840. slot_colors: dict[int, str] = {}
  841. handled_global_tray_ids: set[int] = set()
  842. spools_updated = 0
  843. # --- Path 1: 3MF per-slot estimates -----------------------------
  844. if filament_usage:
  845. if len(tray_changes) > 1:
  846. # Tray-split path — attribute per-segment to the tray that
  847. # was loaded at that time.
  848. logger.info(
  849. "[SPOOLMAN] Reporting per-filament usage for archive %s with tray-split "
  850. "(tray_change_log=%s, denom_layers=%d)",
  851. archive_id,
  852. tray_changes,
  853. _layer_denom_hint,
  854. )
  855. # ``tracking.layer_usage`` was serialized to JSON so int keys
  856. # come back as strings. Restore them for the split math.
  857. layer_usage = None
  858. if layer_usage_raw:
  859. try:
  860. layer_usage = {
  861. int(layer): {int(fid): mm for fid, mm in filaments.items()}
  862. for layer, filaments in layer_usage_raw.items()
  863. }
  864. except (TypeError, ValueError, AttributeError):
  865. # AttributeError catches ``inner.items()`` when the
  866. # inner value isn't dict-shaped (corrupt JSON row).
  867. # Missing gcode falls through to the linear-ratio
  868. # branch inside ``compute_tray_split_grams`` — still
  869. # gives a correct split, just less precise.
  870. layer_usage = None
  871. split_updated, split_handled = await _report_spool_usage_split_by_tray_changes(
  872. client,
  873. filament_usage,
  874. tray_changes,
  875. ams_trays,
  876. layer_usage,
  877. filament_properties,
  878. _total_layers,
  879. _layer_denom_hint,
  880. f"Archive {archive_id}",
  881. printer_serial,
  882. printer_id=printer_id,
  883. slot_colors_out=slot_colors,
  884. )
  885. spools_updated += split_updated
  886. handled_global_tray_ids |= split_handled
  887. else:
  888. logger.info("[SPOOLMAN] Reporting per-filament usage for archive %s", archive_id)
  889. usage_items = [(u.get("slot_id", 0), u.get("used_g", 0)) for u in filament_usage]
  890. spools_updated = await _report_spool_usage_for_slots(
  891. client,
  892. usage_items,
  893. ams_trays,
  894. slot_to_tray,
  895. f"Archive {archive_id}",
  896. printer_serial,
  897. printer_id=printer_id,
  898. slot_colors_out=slot_colors,
  899. )
  900. # Track which physical slots the 3MF path already covered so
  901. # Path 2 doesn't double-charge them.
  902. for u in filament_usage:
  903. slot_id = u.get("slot_id", 0)
  904. handled_global_tray_ids.add(_resolve_global_tray_id(slot_id, slot_to_tray, ams_trays))
  905. # --- Path 2: AMS remain%-delta for slots 3MF didn't cover -------
  906. # Triggered for no-3MF "Untitled" prints (#1820) AND for partial
  907. # 3MF coverage (slots whose filament_id wasn't in slice_info).
  908. if tray_remain_start:
  909. from backend.app.services.printer_manager import printer_manager
  910. current = printer_manager.get_status(printer_id)
  911. current_lookup = _snapshot_tray_remain(current.raw_data) if current and current.raw_data else {}
  912. fallback_updates = await _report_remain_delta_for_slots(
  913. client,
  914. printer_id=printer_id,
  915. tray_remain_start=tray_remain_start,
  916. current_lookup=current_lookup,
  917. handled_global_tray_ids=handled_global_tray_ids,
  918. archive_id=archive_id,
  919. slot_colors_out=slot_colors,
  920. )
  921. spools_updated += fallback_updates
  922. if spools_updated == 0:
  923. logger.info("[SPOOLMAN] Archive %s: no spools updated", archive_id)
  924. else:
  925. logger.info("[SPOOLMAN] Archive %s: updated %s spool(s)", archive_id, spools_updated)
  926. # Stamp the archive's filament colour from the matched Spoolman spools
  927. # so it reflects the curated inventory colour, not the slicer's 3MF
  928. # value (#1494) — mirrors the built-in inventory path in usage_tracker.
  929. await _apply_spool_colors_to_archive(db, archive_id, filament_usage, slot_colors)
  930. async def _report_remain_delta_for_slots(
  931. client,
  932. *,
  933. printer_id: int,
  934. tray_remain_start: dict[str, dict],
  935. current_lookup: dict[str, dict],
  936. handled_global_tray_ids: set[int],
  937. archive_id: int,
  938. slot_colors_out: dict[int, str] | None = None,
  939. ) -> int:
  940. """AMS remain%-delta path: write ``(start - current) * filament.weight``
  941. grams to Spoolman for slots the 3MF path didn't cover.
  942. Mirrors ``usage_tracker.on_print_complete`` Path 2: per-slot, gated on a
  943. valid current ``remain%``, skipped on spool swap (``tray_uuid`` changed),
  944. using the resolved spool's filament reference weight rather than MQTT's
  945. unreliable ``tray_weight`` (which is the failure mode #1119 documented).
  946. """
  947. spools_updated = 0
  948. for slot_key, start in tray_remain_start.items():
  949. try:
  950. ams_id_str, tray_id_str = slot_key.split("-", 1)
  951. ams_id, tray_id = int(ams_id_str), int(tray_id_str)
  952. except (ValueError, AttributeError):
  953. continue
  954. # Skip slots already handled by the 3MF path. Encoding mirrors
  955. # build_ams_tray_lookup: VT trays land at 254/255, AMS-HT keeps
  956. # its native id (>=128), regular AMS slots are ams_id*4+tray_id.
  957. if ams_id == 255:
  958. global_tray_id = 254 + tray_id
  959. elif ams_id >= 128:
  960. global_tray_id = ams_id
  961. else:
  962. global_tray_id = ams_id * 4 + tray_id
  963. if global_tray_id in handled_global_tray_ids:
  964. continue
  965. current = current_lookup.get(slot_key)
  966. if not current:
  967. logger.debug("[SPOOLMAN] AMS%d-T%d: no current remain%% at completion, skipping fallback", ams_id, tray_id)
  968. continue
  969. # Spool swap mid-print — tray_uuid changed. We don't know how much
  970. # of the print went to which spool; skip rather than mis-attribute.
  971. start_uuid = (start.get("tray_uuid") or "").lower()
  972. cur_uuid = (current.get("tray_uuid") or "").lower()
  973. if start_uuid and cur_uuid and start_uuid != cur_uuid:
  974. logger.info(
  975. "[SPOOLMAN] AMS%d-T%d: spool swapped mid-print (uuid changed), skipping remain-delta", ams_id, tray_id
  976. )
  977. continue
  978. delta_pct = start["remain"] - current["remain"]
  979. if delta_pct <= 0:
  980. continue # No consumption captured at AMS granularity, or refilled
  981. spool_id = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  982. if spool_id is None:
  983. logger.debug("[SPOOLMAN] AMS%d-T%d: no Spoolman slot assignment, skipping fallback", ams_id, tray_id)
  984. continue
  985. # Look up the spool's filament reference weight. Use a fresh GET so
  986. # we don't depend on a stale cached_spools list. Failure here is
  987. # silent-skip rather than fatal — other slots can still be written.
  988. try:
  989. spool = await client.get_spool(spool_id)
  990. except Exception as exc: # noqa: BLE001
  991. logger.debug("[SPOOLMAN] AMS%d-T%d: get_spool(%s) failed: %s", ams_id, tray_id, spool_id, exc)
  992. continue
  993. filament = spool.get("filament") or {}
  994. ref_weight = filament.get("weight")
  995. if not ref_weight or ref_weight <= 0:
  996. logger.debug(
  997. "[SPOOLMAN] AMS%d-T%d: spool %s has no filament.weight, skipping remain-delta",
  998. ams_id,
  999. tray_id,
  1000. spool_id,
  1001. )
  1002. continue
  1003. grams_used = round((delta_pct / 100.0) * ref_weight, 2)
  1004. if grams_used <= 0:
  1005. continue
  1006. try:
  1007. await client.use_spool(spool_id, grams_used)
  1008. except Exception as exc: # noqa: BLE001
  1009. logger.warning(
  1010. "[SPOOLMAN] AMS%d-T%d: use_spool(%s, %.2fg) failed: %s", ams_id, tray_id, spool_id, grams_used, exc
  1011. )
  1012. continue
  1013. spools_updated += 1
  1014. if slot_colors_out is not None:
  1015. color = filament.get("color_hex")
  1016. if color:
  1017. # No 3MF slot_id for this path — use the AMS slot key so the
  1018. # colour map can still be inspected by callers if needed.
  1019. # The archive-colour rewrite (#1494) keys on 3MF slot_ids so
  1020. # remain-delta-only prints intentionally don't participate
  1021. # in that rewrite (matches usage_tracker's slot_id=None).
  1022. slot_colors_out[-(global_tray_id + 1)] = color
  1023. logger.info(
  1024. "[SPOOLMAN] Archive %s AMS%d-T%d: %.2fg via remain-delta (%d%% of %.0fg) -> spool %s",
  1025. archive_id,
  1026. ams_id,
  1027. tray_id,
  1028. grams_used,
  1029. delta_pct,
  1030. ref_weight,
  1031. spool_id,
  1032. )
  1033. return spools_updated
  1034. async def _apply_spool_colors_to_archive(
  1035. db,
  1036. archive_id: int,
  1037. filament_usage: list[dict],
  1038. slot_colors: dict[int, str],
  1039. ) -> None:
  1040. """Overwrite an archive's ``filament_color`` with the colours of the
  1041. Spoolman spools that fed the print (#1494).
  1042. All-or-nothing, exactly like the built-in inventory path: the colour is
  1043. only rewritten when every used slot resolved to a spool that carries a
  1044. colour, so a partial match never drops slots from the archive.
  1045. """
  1046. if not slot_colors:
  1047. return
  1048. from backend.app.models.archive import PrintArchive
  1049. from backend.app.services.usage_tracker import (
  1050. _archive_colors_from_spools,
  1051. _spool_color_to_hex,
  1052. )
  1053. results = [{"slot_id": sid, "color": _spool_color_to_hex(hex_)} for sid, hex_ in slot_colors.items()]
  1054. colors = _archive_colors_from_spools(filament_usage, results)
  1055. if not colors:
  1056. return
  1057. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1058. if archive is None:
  1059. return
  1060. joined = ",".join(colors)
  1061. if joined != archive.filament_color:
  1062. logger.info(
  1063. "[SPOOLMAN] Archive %s filament_color %r -> %r (from Spoolman spools)",
  1064. archive_id,
  1065. archive.filament_color,
  1066. joined,
  1067. )
  1068. archive.filament_color = joined
  1069. await db.commit()