spoolman_tracking.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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 f"{_hash_serial_to_hex32(printer_serial)}{_to_fixed_hex(ams_id, 4)}{_to_fixed_hex(tray_id, 4)}"
  55. def _resolve_spool_tag(tray_info: dict, printer_serial: str = "", global_tray_id: int | None = None) -> str:
  56. """Get the best spool identifier from tray info (prefer tray_uuid over tag_uid).
  57. Returns empty string if no usable identifier is found.
  58. """
  59. tray_uuid = str(tray_info.get("tray_uuid", "") or "")
  60. tag_uid = str(tray_info.get("tag_uid", "") or "")
  61. if tray_uuid and tray_uuid != _ZERO_UUID and _is_non_zero_identifier(tray_uuid):
  62. return tray_uuid
  63. if tag_uid and tag_uid != _ZERO_TAG_UID and _is_non_zero_identifier(tag_uid):
  64. return tag_uid
  65. if global_tray_id is not None:
  66. return _get_fallback_spool_tag(printer_serial, global_tray_id)
  67. return ""
  68. async def _get_printer_serial(printer_id: int) -> str:
  69. """Get printer serial for deterministic fallback tag generation."""
  70. from backend.app.models.printer import Printer
  71. from backend.app.services.printer_manager import printer_manager
  72. printer_info = printer_manager.get_printer(printer_id)
  73. if printer_info and printer_info.serial_number:
  74. return printer_info.serial_number
  75. async with async_session() as db:
  76. result = await db.execute(select(Printer.serial_number).where(Printer.id == printer_id))
  77. serial_number = result.scalar_one_or_none()
  78. return serial_number or ""
  79. def _resolve_global_tray_id(slot_id: int, slot_to_tray: list | None, ams_trays: dict | None = None) -> int:
  80. """Map a 1-based slot_id to a global_tray_id using optional custom mapping.
  81. Custom mapping: slot_to_tray[slot_id - 1] is used when >= 0.
  82. A value of -1 in the custom mapping means the slicer routed this slot to
  83. the external spool. BambuStudio converts virtual tray IDs (254/255) to -1
  84. in the flat ams_mapping array before sending to the printer — see
  85. start_print() in bambu_mqtt.py which documents this convention. We mirror
  86. it here: when -1 is seen, look up the external spool's actual
  87. global_tray_id (254/255) in ams_trays rather than falling through to the
  88. position-based default (which would map slot_id=1 to the first AMS tray
  89. and credit an unrelated spool — see #1276, regression of #853).
  90. Position-based default: uses sorted ams_trays keys so external spools (ID 254/255)
  91. naturally follow standard AMS trays, matching the slicer's slot numbering.
  92. Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools).
  93. """
  94. if slot_to_tray and slot_id <= len(slot_to_tray):
  95. mapped_tray = slot_to_tray[slot_id - 1]
  96. if mapped_tray >= 0:
  97. return mapped_tray
  98. if mapped_tray == -1 and ams_trays:
  99. # -1 means external spool. 254 = VIRTUAL_TRAY_DEPUTY_ID (main on
  100. # single-nozzle, left/deputy on H2D dual-nozzle); 255 =
  101. # VIRTUAL_TRAY_MAIN_ID. Prefer 254 when both exist since that's
  102. # what single-nozzle printers report via tray_now.
  103. for ext_id in (254, 255):
  104. if ext_id in ams_trays:
  105. return ext_id
  106. # Position-based default: sort available tray IDs so external spools (254/255)
  107. # come after standard AMS trays, matching the slicer's slot assignment order.
  108. if ams_trays:
  109. sorted_tray_ids = sorted(ams_trays.keys())
  110. if slot_id <= len(sorted_tray_ids):
  111. return sorted_tray_ids[slot_id - 1]
  112. return slot_id - 1
  113. def build_ams_tray_lookup(raw_data: dict) -> dict[int, dict]:
  114. """Build lookup of global_tray_id -> tray info from printer state.
  115. Returns: {0: {"tray_uuid": "...", "tag_uid": "...", "tray_type": "..."}, ...}
  116. """
  117. lookup = {}
  118. ams_data = raw_data.get("ams", [])
  119. for ams_unit in ams_data:
  120. ams_id = int(ams_unit.get("id", 0))
  121. for tray in ams_unit.get("tray", []):
  122. tray_id = int(tray.get("id", 0))
  123. # AMS-HT units have IDs starting at 128 with a single tray
  124. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  125. lookup[global_tray_id] = {
  126. "tray_uuid": tray.get("tray_uuid", ""),
  127. "tag_uid": tray.get("tag_uid", ""),
  128. "tray_type": tray.get("tray_type", ""),
  129. }
  130. # External spool(s) (vt_tray is a list, global_tray_id from each entry's "id")
  131. for vt in raw_data.get("vt_tray") or []:
  132. if vt.get("tray_type"):
  133. tray_id = int(vt.get("id", 254))
  134. lookup[tray_id] = {
  135. "tray_uuid": vt.get("tray_uuid", ""),
  136. "tag_uid": vt.get("tag_uid", ""),
  137. "tray_type": vt.get("tray_type", ""),
  138. }
  139. return lookup
  140. async def store_print_data(
  141. printer_id: int,
  142. archive_id: int,
  143. file_path: str,
  144. db,
  145. printer_manager,
  146. ams_mapping: list[int] | None = None,
  147. ):
  148. """Store Spoolman tracking data at print start (persisted to database).
  149. Per-print tracking is the primary weight-update path for Spoolman, mirroring
  150. how the internal Filament Inventory works. The legacy AMS-remain%-based sync
  151. is no longer used as a weight writer (#1119), so this runs whenever Spoolman
  152. is enabled regardless of the deprecated `spoolman_disable_weight_sync` flag.
  153. """
  154. from backend.app.api.routes.settings import get_setting
  155. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  156. from backend.app.models.print_queue import PrintQueueItem
  157. from backend.app.utils.threemf_tools import (
  158. extract_filament_properties_from_3mf,
  159. extract_filament_usage_from_3mf,
  160. extract_layer_filament_usage_from_3mf,
  161. )
  162. # Check if Spoolman is enabled
  163. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  164. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  165. return
  166. # Get 3MF file path
  167. full_path = app_settings.base_dir / file_path
  168. if not full_path.exists():
  169. logger.debug("[SPOOLMAN] 3MF file not found: %s", full_path)
  170. return
  171. # Extract per-filament usage from 3MF (total usage per slot)
  172. filament_usage = extract_filament_usage_from_3mf(full_path)
  173. if not filament_usage:
  174. logger.debug("[SPOOLMAN] No filament usage data in 3MF for archive %s", archive_id)
  175. return
  176. # Get current AMS tray state
  177. state = printer_manager.get_status(printer_id)
  178. ams_trays = {}
  179. if state and state.raw_data:
  180. ams_trays = build_ams_tray_lookup(state.raw_data)
  181. # Prefer the explicit mapping captured from the print command, then fall back
  182. # to any queue mapping stored for scheduled/reprint jobs.
  183. slot_to_tray = ams_mapping if ams_mapping is not None else None
  184. if not slot_to_tray:
  185. queue_result = await db.execute(
  186. select(PrintQueueItem)
  187. .where(PrintQueueItem.archive_id == archive_id)
  188. .where(PrintQueueItem.status == "printing")
  189. )
  190. queue_item = queue_result.scalar_one_or_none()
  191. if queue_item and queue_item.ams_mapping:
  192. try:
  193. slot_to_tray = json.loads(queue_item.ams_mapping)
  194. except json.JSONDecodeError:
  195. pass # Ignore malformed AMS mapping; fall back to default slot assignment
  196. # Parse G-code for per-layer filament usage (for accurate partial usage tracking)
  197. layer_usage = extract_layer_filament_usage_from_3mf(full_path)
  198. layer_usage_json = None
  199. if layer_usage:
  200. # Convert int keys to string for JSON serialization
  201. layer_usage_json = {str(k): v for k, v in layer_usage.items()}
  202. logger.debug("[SPOOLMAN] Parsed %s layers from G-code", len(layer_usage))
  203. # Extract filament properties (density, diameter) for mm -> grams conversion
  204. filament_properties = extract_filament_properties_from_3mf(full_path)
  205. # Delete any existing row for this printer/archive (shouldn't exist, but just in case)
  206. await db.execute(
  207. delete(ActivePrintSpoolman)
  208. .where(ActivePrintSpoolman.printer_id == printer_id)
  209. .where(ActivePrintSpoolman.archive_id == archive_id)
  210. )
  211. # Insert new tracking data
  212. tracking = ActivePrintSpoolman(
  213. printer_id=printer_id,
  214. archive_id=archive_id,
  215. filament_usage=filament_usage,
  216. ams_trays=ams_trays,
  217. slot_to_tray=slot_to_tray,
  218. layer_usage=layer_usage_json,
  219. filament_properties=filament_properties,
  220. )
  221. db.add(tracking)
  222. await db.commit()
  223. logger.info("[SPOOLMAN] Stored tracking data for print: printer=%s, archive=%s", printer_id, archive_id)
  224. logger.debug("[SPOOLMAN] Filament usage: %s", filament_usage)
  225. logger.debug("[SPOOLMAN] AMS trays: %s", list(ams_trays.keys()))
  226. if slot_to_tray:
  227. logger.debug("[SPOOLMAN] Custom slot mapping: %s", slot_to_tray)
  228. if layer_usage_json:
  229. logger.debug("[SPOOLMAN] Layer usage data available for partial tracking")
  230. async def cleanup_tracking(
  231. printer_id: int,
  232. archive_id: int,
  233. db,
  234. last_layer_num: int | None = None,
  235. last_progress: int | None = None,
  236. ):
  237. """Report partial usage and clean up Spoolman tracking data for failed/aborted prints."""
  238. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  239. # Get tracking data first (needed for partial usage reporting)
  240. result = await db.execute(
  241. select(ActivePrintSpoolman)
  242. .where(ActivePrintSpoolman.printer_id == printer_id)
  243. .where(ActivePrintSpoolman.archive_id == archive_id)
  244. )
  245. tracking = result.scalar_one_or_none()
  246. if not tracking:
  247. logger.debug("[SPOOLMAN] No tracking data to clean up for printer=%s, archive=%s", printer_id, archive_id)
  248. return
  249. # Try to report partial usage before cleanup
  250. try:
  251. await _report_partial_usage(
  252. printer_id,
  253. tracking,
  254. last_layer_num=last_layer_num,
  255. last_progress=last_progress,
  256. )
  257. except Exception as e:
  258. logger.warning("[SPOOLMAN] Partial usage report failed: %s", e)
  259. # Delete tracking data
  260. await db.execute(
  261. delete(ActivePrintSpoolman)
  262. .where(ActivePrintSpoolman.printer_id == printer_id)
  263. .where(ActivePrintSpoolman.archive_id == archive_id)
  264. )
  265. await db.commit()
  266. logger.debug("[SPOOLMAN] Cleaned up tracking data for printer=%s, archive=%s", printer_id, archive_id)
  267. async def _get_spoolman_client_with_fallback():
  268. """Get Spoolman client, initializing from settings if needed.
  269. Returns (client, is_healthy) tuple. Client may be None.
  270. """
  271. client = await get_spoolman_client()
  272. if not client:
  273. async with async_session() as db:
  274. from backend.app.api.routes.settings import get_setting
  275. spoolman_url = await get_setting(db, "spoolman_url")
  276. if spoolman_url:
  277. try:
  278. client = await init_spoolman_client(spoolman_url)
  279. except ValueError as exc:
  280. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  281. return None
  282. if not client:
  283. return None
  284. if not await client.health_check():
  285. logger.warning("Spoolman health check failed; skipping usage reporting")
  286. return None
  287. return client
  288. async def _report_spool_usage_for_slots(
  289. client,
  290. filament_usage_items: list[tuple[int, float]],
  291. ams_trays: dict[int, dict],
  292. slot_to_tray: list | None,
  293. method_label: str,
  294. printer_serial: str = "",
  295. ) -> int:
  296. """Report usage to Spoolman for a list of (slot_id, grams) pairs.
  297. Returns number of spools successfully updated.
  298. """
  299. spools_updated = 0
  300. for slot_id, grams_used in filament_usage_items:
  301. if grams_used <= 0:
  302. continue
  303. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  304. tray_info = ams_trays.get(global_tray_id)
  305. if not tray_info:
  306. logger.debug("[SPOOLMAN] Slot %s: no tray at global_tray_id %s", slot_id, global_tray_id)
  307. continue
  308. is_external = global_tray_id >= 254
  309. tray_type = tray_info.get("tray_type", "")
  310. logger.debug(
  311. "[SPOOLMAN] Slot %s resolved to global_tray_id %s (tray_type=%s, external=%s)",
  312. slot_id,
  313. global_tray_id,
  314. tray_type or "unknown",
  315. is_external,
  316. )
  317. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  318. if not spool_tag:
  319. logger.debug("[SPOOLMAN] Slot %s: no identifier for tray %s", slot_id, global_tray_id)
  320. continue
  321. spool = await client.find_spool_by_tag(spool_tag)
  322. if not spool:
  323. logger.debug("[SPOOLMAN] Slot %s: no spool for tag %s...", slot_id, spool_tag[:16])
  324. continue
  325. try:
  326. await client.use_spool(spool["id"], grams_used)
  327. logger.info("[SPOOLMAN] %s: slot %s: %sg -> spool %s", method_label, slot_id, grams_used, spool["id"])
  328. spools_updated += 1
  329. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  330. logger.warning("[SPOOLMAN] Failed to record usage for spool %s: %s", spool["id"], exc)
  331. return spools_updated
  332. async def _report_partial_usage(
  333. printer_id: int,
  334. tracking,
  335. last_layer_num: int | None = None,
  336. last_progress: int | None = None,
  337. ):
  338. """Report partial filament usage based on actual G-code layer data.
  339. Uses per-layer cumulative extrusion from G-code parsing for accurate
  340. multi-material tracking. Falls back to linear interpolation if G-code
  341. data is unavailable.
  342. """
  343. from backend.app.services.printer_manager import printer_manager
  344. from backend.app.utils.threemf_tools import get_cumulative_usage_at_layer, mm_to_grams
  345. async with async_session() as db:
  346. from backend.app.api.routes.settings import get_setting
  347. # Check if partial usage reporting is enabled (default: true)
  348. report_partial = await get_setting(db, "spoolman_report_partial_usage")
  349. if report_partial and report_partial.lower() == "false":
  350. logger.debug("[SPOOLMAN] Partial usage reporting disabled by setting")
  351. return
  352. # Check if Spoolman is enabled
  353. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  354. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  355. return
  356. # Get current printer state for layer progress.
  357. # On failed/aborted prints the firmware may already reset to IDLE with layer=0,
  358. # so we fall back to completion-time hints captured from MQTT.
  359. state = printer_manager.get_status(printer_id)
  360. current_layer = state.layer_num if state else None
  361. total_layers = state.total_layers if state else None
  362. if (not current_layer or current_layer <= 0) and last_layer_num and last_layer_num > 0:
  363. current_layer = last_layer_num
  364. logger.debug("[SPOOLMAN] Using captured last_layer_num=%s for partial usage", current_layer)
  365. progress_ratio_from_event = None
  366. if last_progress is not None:
  367. try:
  368. progress_ratio_from_event = min(max(float(last_progress), 0.0), 100.0) / 100.0
  369. except (TypeError, ValueError):
  370. progress_ratio_from_event = None
  371. if (not current_layer or current_layer <= 0) and progress_ratio_from_event and total_layers and total_layers > 0:
  372. current_layer = max(1, int(round(total_layers * progress_ratio_from_event)))
  373. logger.debug(
  374. "[SPOOLMAN] Estimated layer from last_progress=%s%% and total_layers=%s -> %s",
  375. last_progress,
  376. total_layers,
  377. current_layer,
  378. )
  379. if not current_layer or current_layer <= 0:
  380. logger.debug(
  381. "[SPOOLMAN] No progress to report (layer 0/unknown, last_layer_num=%s, last_progress=%s)",
  382. last_layer_num,
  383. last_progress,
  384. )
  385. return
  386. logger.info("[SPOOLMAN] Reporting partial usage at layer %s/%s", current_layer, total_layers or "?")
  387. # Get tracking data
  388. layer_usage = tracking.layer_usage
  389. filament_properties = tracking.filament_properties or {}
  390. filament_usage = tracking.filament_usage or []
  391. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  392. slot_to_tray = tracking.slot_to_tray
  393. printer_serial = await _get_printer_serial(printer_id)
  394. client = await _get_spoolman_client_with_fallback()
  395. if not client:
  396. logger.warning("[SPOOLMAN] Not reachable for partial usage reporting")
  397. return
  398. # Try to use accurate G-code parsed data
  399. if layer_usage:
  400. layer_usage_int = {
  401. int(layer): {int(fid): mm for fid, mm in filaments.items()} for layer, filaments in layer_usage.items()
  402. }
  403. usage_mm = get_cumulative_usage_at_layer(layer_usage_int, current_layer)
  404. if usage_mm:
  405. logger.info("[SPOOLMAN] Using G-code parsed data for layer %s", current_layer)
  406. # Build (slot_id, grams) list using Spoolman densities with 3MF fallback
  407. usage_items = []
  408. for filament_id, mm_used in usage_mm.items():
  409. slot_id = filament_id + 1 # filament_id is 0-based, slot_id is 1-based
  410. # Get density from Spoolman (most accurate), fall back to 3MF, then PLA default
  411. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  412. tray_info = ams_trays.get(global_tray_id)
  413. density = None
  414. diameter = 1.75
  415. if tray_info:
  416. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  417. if spool_tag:
  418. spool = await client.find_spool_by_tag(spool_tag)
  419. if spool:
  420. filament_data = spool.get("filament", {})
  421. density = filament_data.get("density")
  422. diameter = filament_data.get("diameter", 1.75)
  423. if not density:
  424. props = filament_properties.get(str(slot_id), filament_properties.get(slot_id, {}))
  425. density = props.get("density", 1.24)
  426. logger.debug("[SPOOLMAN] Using fallback density %s for slot %s", density, slot_id)
  427. grams_used = round(mm_to_grams(mm_used, diameter, density), 2)
  428. usage_items.append((slot_id, grams_used))
  429. spools_updated = await _report_spool_usage_for_slots(
  430. client, usage_items, ams_trays, slot_to_tray, "Partial (G-code)", printer_serial
  431. )
  432. if spools_updated > 0:
  433. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using G-code data", spools_updated)
  434. return
  435. # Fallback: linear interpolation (if no G-code data available)
  436. progress_ratio = None
  437. if total_layers and total_layers > 0:
  438. progress_ratio = min(current_layer / total_layers, 1.0)
  439. elif progress_ratio_from_event is not None:
  440. progress_ratio = progress_ratio_from_event
  441. if progress_ratio is None:
  442. logger.debug(
  443. "[SPOOLMAN] Cannot use linear fallback: total_layers=%s, last_progress=%s",
  444. total_layers,
  445. last_progress,
  446. )
  447. return
  448. logger.info("[SPOOLMAN] Falling back to linear interpolation (%s)", progress_ratio)
  449. usage_items = []
  450. for usage in filament_usage:
  451. slot_id = usage.get("slot_id", 0)
  452. total_used_g = usage.get("used_g", 0)
  453. if total_used_g > 0:
  454. partial_used_g = round(total_used_g * progress_ratio, 2)
  455. usage_items.append((slot_id, partial_used_g))
  456. spools_updated = await _report_spool_usage_for_slots(
  457. client, usage_items, ams_trays, slot_to_tray, "Partial (linear)", printer_serial
  458. )
  459. if spools_updated > 0:
  460. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using linear interpolation", spools_updated)
  461. async def report_usage(printer_id: int, archive_id: int):
  462. """Report filament usage to Spoolman after print completion.
  463. Uses per-filament usage data captured at print start to report
  464. usage to the correct spools.
  465. """
  466. async with async_session() as db:
  467. from backend.app.api.routes.settings import get_setting
  468. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  469. # Get tracking data stored at print start
  470. result = await db.execute(
  471. select(ActivePrintSpoolman)
  472. .where(ActivePrintSpoolman.printer_id == printer_id)
  473. .where(ActivePrintSpoolman.archive_id == archive_id)
  474. )
  475. tracking = result.scalar_one_or_none()
  476. if not tracking:
  477. logger.info("[SPOOLMAN] No tracking data for print (printer=%s, archive=%s)", printer_id, archive_id)
  478. return
  479. filament_usage = tracking.filament_usage or []
  480. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  481. slot_to_tray = tracking.slot_to_tray
  482. printer_serial = await _get_printer_serial(printer_id)
  483. # Delete tracking row (we're done with it)
  484. await db.delete(tracking)
  485. await db.commit()
  486. if not filament_usage:
  487. logger.debug("[SPOOLMAN] No filament usage data for archive %s", archive_id)
  488. return
  489. # Check if Spoolman is enabled
  490. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  491. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  492. return
  493. client = await _get_spoolman_client_with_fallback()
  494. if not client:
  495. logger.warning("[SPOOLMAN] Not reachable for usage reporting")
  496. return
  497. logger.info("[SPOOLMAN] Reporting per-filament usage for archive %s", archive_id)
  498. usage_items = [(u.get("slot_id", 0), u.get("used_g", 0)) for u in filament_usage]
  499. spools_updated = await _report_spool_usage_for_slots(
  500. client, usage_items, ams_trays, slot_to_tray, f"Archive {archive_id}", printer_serial
  501. )
  502. if spools_updated == 0:
  503. logger.info("[SPOOLMAN] Archive %s: no spools updated", archive_id)
  504. else:
  505. logger.info("[SPOOLMAN] Archive %s: updated %s spool(s)", archive_id, spools_updated)