kprofile_drift.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. """Put a slot's stored K-profile back when the printer has lost the selection.
  2. A tray's ``cali_idx`` can fall back to -1 without anything else in the AMS
  3. report changing: an X1 Carbon power-cycled mid-print came back with every slot
  4. on the default K while spools, tags and remain% were exactly as before (#3219).
  5. ``on_ams_change`` is keyed on tray_type / tag_uid / remain, so it never saw
  6. that, and two queued jobs went out on the default K.
  7. This module re-selects the stored profile for such a slot. It acts only when
  8. the selection is *lost* (``cali_idx`` -1 or missing), never when the slot
  9. holds a different real profile: that one was picked on purpose, in Bambu
  10. Studio for example. A profile picked in Bambuddy's Configure Slot dialog is
  11. saved as the spool's stored profile anyway, but a "Default" pick there is not
  12. saved anywhere, so it is recorded through ``note_slot_configured`` and left
  13. alone too.
  14. Two callers: the status handler, on every push while the printer is idle, and
  15. the print scheduler, just before it sends a job.
  16. """
  17. import logging
  18. import time
  19. from dataclasses import dataclass
  20. from backend.app.core.database import async_session
  21. from backend.app.services.printer_manager import printer_manager
  22. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  23. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  24. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  25. from backend.app.utils.printer_models import is_dual_nozzle_model
  26. logger = logging.getLogger(__name__)
  27. # States in which re-selecting a profile cannot touch a print. PREPARE and
  28. # SLICING are left out on purpose: the printer is starting a job there.
  29. IDLE_STATES = frozenset({"IDLE", "FINISH", "FAILED"})
  30. # Time between two re-selections of one slot: the push right after a send can
  31. # still show the old value, so an immediate resend would only be noise.
  32. RETRY_INTERVAL_S = 30.0
  33. # Time before a slot with no stored profile is looked up again. Most slots on
  34. # the default K are there on purpose, and on an install with many printers a
  35. # lookup per slot every 30 seconds would add up for nothing. A reconnect (the
  36. # #3219 case) clears this, so a power cycle is still caught at once.
  37. NO_PROFILE_RECHECK_S = 600.0
  38. # Re-selections of one profile before giving up on it. A stored cali_idx the
  39. # printer no longer has will never stick; this keeps that from repeating forever.
  40. MAX_ATTEMPTS = 3
  41. SlotKey = tuple[int, int, int]
  42. @dataclass
  43. class _SlotWatch:
  44. next_check: float = 0.0
  45. attempts: int = 0
  46. gave_up_logged: bool = False
  47. _watches: dict[SlotKey, _SlotWatch] = {}
  48. _default_chosen: set[SlotKey] = set()
  49. _running: set[int] = set()
  50. def note_slot_configured(printer_id: int, ams_id: int, tray_id: int, cali_idx: int) -> None:
  51. """Record a K-profile picked for a slot in Bambuddy's Configure Slot dialog.
  52. A default pick (-1) is respected until the slot is emptied or configured
  53. again. It is not cleared by the slot reporting a real profile, because the
  54. push right after the pick can still carry the old one.
  55. """
  56. key = (printer_id, ams_id, tray_id)
  57. if cali_idx < 0:
  58. _default_chosen.add(key)
  59. else:
  60. _default_chosen.discard(key)
  61. def forget_printer(printer_id: int) -> None:
  62. """Drop the retry bookkeeping for a printer, e.g. when it disconnects.
  63. A reconnect is a fresh start: a profile given up on before may stick now.
  64. A deliberate default pick is kept -- it still describes the slot.
  65. """
  66. for key in [k for k in _watches if k[0] == printer_id]:
  67. del _watches[key]
  68. def _selection_lost(tray: dict) -> bool:
  69. cali_idx = tray.get("cali_idx")
  70. if cali_idx is None:
  71. return True
  72. try:
  73. return int(cali_idx) < 0
  74. except (TypeError, ValueError):
  75. return False
  76. def _loaded_trays(state) -> list[tuple[int, int, int, dict]]:
  77. """``(ams_id, tray_id, global_tray_id, tray)`` for every loaded slot.
  78. External spools use the assignment addressing (ams 255, tray 0/1) and the
  79. global id the print command carries for them (254/255).
  80. """
  81. raw = getattr(state, "raw_data", None) or {}
  82. ams_raw = raw.get("ams")
  83. units = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  84. trays: list[tuple[int, int, int, dict]] = []
  85. for unit in units:
  86. if not isinstance(unit, dict):
  87. continue
  88. try:
  89. ams_id = int(unit.get("id", 0))
  90. except (TypeError, ValueError):
  91. continue
  92. for tray in unit.get("tray") or []:
  93. if not isinstance(tray, dict):
  94. continue
  95. try:
  96. tray_id = int(tray.get("id", 0))
  97. except (TypeError, ValueError):
  98. continue
  99. global_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  100. trays.append((ams_id, tray_id, global_id, tray))
  101. vt_raw = raw.get("vt_tray")
  102. if isinstance(vt_raw, dict):
  103. vt_raw = [vt_raw]
  104. for vt in vt_raw if isinstance(vt_raw, list) else []:
  105. if not isinstance(vt, dict):
  106. continue
  107. try:
  108. vt_id = int(vt.get("id", 254))
  109. except (TypeError, ValueError):
  110. continue
  111. if vt_id in (254, 255):
  112. trays.append((255, vt_id - 254, vt_id, vt))
  113. return trays
  114. def _settle(key: SlotKey, tray: dict) -> bool:
  115. """Clear bookkeeping a slot no longer needs; True if it is a candidate.
  116. A candidate is a loaded slot whose selection is lost and was not set to
  117. the default on purpose.
  118. """
  119. if not tray.get("tray_type"):
  120. _watches.pop(key, None)
  121. _default_chosen.discard(key)
  122. return False
  123. if not _selection_lost(tray):
  124. _watches.pop(key, None)
  125. return False
  126. return key not in _default_chosen
  127. def _due(printer_id: int, key: SlotKey, now: float) -> bool:
  128. watch = _watches.get(key)
  129. if watch is None:
  130. return True
  131. if now < watch.next_check:
  132. return False
  133. if watch.attempts < MAX_ATTEMPTS:
  134. return True
  135. # The last re-selection had its interval to land and the slot is still
  136. # lost: say so once, then leave the slot alone until it changes.
  137. if not watch.gave_up_logged:
  138. watch.gave_up_logged = True
  139. logger.warning(
  140. "[Printer %s] AMS%d-T%d still has no K-profile after %d re-selections of the stored "
  141. "one; giving up until the slot changes. Check that the profile still exists on the printer.",
  142. printer_id,
  143. key[1],
  144. key[2],
  145. MAX_ATTEMPTS,
  146. )
  147. return False
  148. def needs_check(printer_id: int, state) -> bool:
  149. """Cheap test the status handler runs on every push before spawning a check."""
  150. if printer_id in _running:
  151. return False
  152. if not getattr(state, "connected", False):
  153. return False
  154. if (getattr(state, "state", "") or "").upper() not in IDLE_STATES:
  155. return False
  156. now = time.monotonic()
  157. found = False
  158. for ams_id, tray_id, _global_id, tray in _loaded_trays(state):
  159. key = (printer_id, ams_id, tray_id)
  160. if _settle(key, tray) and _due(printer_id, key, now):
  161. found = True
  162. return found
  163. async def reapply_lost_kprofiles(
  164. printer_id: int, global_trays: set[int] | None = None, *, throttle: bool = True
  165. ) -> int:
  166. """Re-select the stored K-profile on every slot whose selection was lost.
  167. ``global_trays`` limits the pass to the trays a print uses. ``throttle``
  168. off is for the dispatch guard: a job about to start must not wait out a
  169. retry interval, and that runs once per job anyway. Returns how many slots
  170. were re-selected.
  171. """
  172. # The dispatch guard runs regardless: a pass already in flight may have
  173. # skipped this job's trays on its retry interval.
  174. if throttle and printer_id in _running:
  175. return 0
  176. state = printer_manager.get_status(printer_id)
  177. client = printer_manager.get_client(printer_id)
  178. if state is None or client is None or not getattr(state, "connected", False):
  179. return 0
  180. model = printer_manager.get_model(printer_id)
  181. nozzles = getattr(state, "nozzles", None) or []
  182. dual_nozzle = is_dual_nozzle_model(model) or (len(nozzles) > 1 and bool(getattr(nozzles[1], "nozzle_diameter", "")))
  183. now = time.monotonic()
  184. candidates = []
  185. for ams_id, tray_id, global_id, tray in _loaded_trays(state):
  186. key = (printer_id, ams_id, tray_id)
  187. if not _settle(key, tray):
  188. continue
  189. if global_trays is not None and global_id not in global_trays:
  190. continue
  191. if throttle and not _due(printer_id, key, now):
  192. continue
  193. # Claimed before the first await, so a push arriving meanwhile does
  194. # not pick the same slot up a second time.
  195. _watches.setdefault(key, _SlotWatch()).next_check = now + RETRY_INTERVAL_S
  196. candidates.append((key, ams_id, tray_id, tray))
  197. if not candidates:
  198. return 0
  199. applied = 0
  200. if throttle:
  201. _running.add(printer_id)
  202. try:
  203. async with async_session() as db:
  204. for key, ams_id, tray_id, tray in candidates:
  205. slot_nozzle = resolve_slot_nozzle(state, ams_id, tray_id, model)
  206. if dual_nozzle:
  207. if slot_nozzle.extruder is None:
  208. # Unknown nozzle on a dual machine: picking extruder 0
  209. # would be a guess, and a wrong guess binds the other
  210. # hotend's calibration.
  211. continue
  212. extruders = [slot_nozzle.extruder]
  213. else:
  214. # One nozzle, but not one extruder number: the external
  215. # holder resolves to 1 (it is H2D's Ext-L), and Configure
  216. # Slot stores the profile under that, while the spool form
  217. # stores 0. Both mean the only nozzle there is.
  218. extruders = list(dict.fromkeys([0, slot_nozzle.extruder_or_default]))
  219. profile = None
  220. for extruder in extruders:
  221. profile = await find_slot_kprofile_for_extruder(
  222. db,
  223. printer_id,
  224. ams_id,
  225. tray_id,
  226. extruder,
  227. slot_nozzle.diameter,
  228. model,
  229. slot_nozzle.flow,
  230. )
  231. if profile is not None:
  232. break
  233. if profile is None or profile.cali_idx is None or profile.cali_idx < 0:
  234. _watches.setdefault(key, _SlotWatch()).next_check = now + NO_PROFILE_RECHECK_S
  235. continue
  236. client.extrusion_cali_sel(
  237. ams_id=ams_id,
  238. tray_id=tray_id,
  239. cali_idx=profile.cali_idx,
  240. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx")),
  241. nozzle_diameter=slot_nozzle.diameter,
  242. )
  243. applied += 1
  244. watch = _watches.setdefault(key, _SlotWatch())
  245. watch.attempts += 1
  246. logger.info(
  247. "[Printer %s] AMS%d-T%d lost its K-profile (cali_idx=%s): re-selected stored "
  248. "profile %r (cali_idx=%d), attempt %d",
  249. printer_id,
  250. ams_id,
  251. tray_id,
  252. tray.get("cali_idx"),
  253. profile.name,
  254. profile.cali_idx,
  255. watch.attempts,
  256. )
  257. except Exception:
  258. logger.exception("[Printer %s] K-profile re-selection failed", printer_id)
  259. finally:
  260. if throttle:
  261. _running.discard(printer_id)
  262. return applied