spoolman_tracking.py 23 KB

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