kprofile_drift.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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, *, deleted: bool = False) -> 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 -- unless
  65. the printer was deleted: then it describes nothing, and SQLite gives the id
  66. to the next printer created.
  67. """
  68. for key in [k for k in _watches if k[0] == printer_id]:
  69. del _watches[key]
  70. if deleted:
  71. for key in [k for k in _default_chosen if k[0] == printer_id]:
  72. _default_chosen.discard(key)
  73. def _selection_lost(tray: dict) -> bool:
  74. cali_idx = tray.get("cali_idx")
  75. if cali_idx is None:
  76. return True
  77. try:
  78. return int(cali_idx) < 0
  79. except (TypeError, ValueError):
  80. return False
  81. def _loaded_trays(state) -> list[tuple[int, int, int, dict]]:
  82. """``(ams_id, tray_id, global_tray_id, tray)`` for every loaded slot.
  83. External spools use the assignment addressing (ams 255, tray 0/1) and the
  84. global id the print command carries for them (254/255).
  85. """
  86. raw = getattr(state, "raw_data", None) or {}
  87. ams_raw = raw.get("ams")
  88. units = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  89. trays: list[tuple[int, int, int, dict]] = []
  90. for unit in units:
  91. if not isinstance(unit, dict):
  92. continue
  93. try:
  94. ams_id = int(unit.get("id", 0))
  95. except (TypeError, ValueError):
  96. continue
  97. for tray in unit.get("tray") or []:
  98. if not isinstance(tray, dict):
  99. continue
  100. try:
  101. tray_id = int(tray.get("id", 0))
  102. except (TypeError, ValueError):
  103. continue
  104. global_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  105. trays.append((ams_id, tray_id, global_id, tray))
  106. vt_raw = raw.get("vt_tray")
  107. if isinstance(vt_raw, dict):
  108. vt_raw = [vt_raw]
  109. for vt in vt_raw if isinstance(vt_raw, list) else []:
  110. if not isinstance(vt, dict):
  111. continue
  112. try:
  113. vt_id = int(vt.get("id", 254))
  114. except (TypeError, ValueError):
  115. continue
  116. if vt_id in (254, 255):
  117. trays.append((255, vt_id - 254, vt_id, vt))
  118. return trays
  119. def _settle(key: SlotKey, tray: dict) -> bool:
  120. """Clear bookkeeping a slot no longer needs; True if it is a candidate.
  121. A candidate is a loaded slot whose selection is lost and was not set to
  122. the default on purpose.
  123. """
  124. if not tray.get("tray_type"):
  125. _watches.pop(key, None)
  126. _default_chosen.discard(key)
  127. return False
  128. if not _selection_lost(tray):
  129. _watches.pop(key, None)
  130. return False
  131. return key not in _default_chosen
  132. def _due(printer_id: int, key: SlotKey, now: float) -> bool:
  133. watch = _watches.get(key)
  134. if watch is None:
  135. return True
  136. if now < watch.next_check:
  137. return False
  138. if watch.attempts < MAX_ATTEMPTS:
  139. return True
  140. # The last re-selection had its interval to land and the slot is still
  141. # lost: say so once, then leave the slot alone until it changes.
  142. if not watch.gave_up_logged:
  143. watch.gave_up_logged = True
  144. logger.warning(
  145. "[Printer %s] AMS%d-T%d still has no K-profile after %d re-selections of the stored "
  146. "one; giving up until the slot changes. Check that the profile still exists on the printer.",
  147. printer_id,
  148. key[1],
  149. key[2],
  150. MAX_ATTEMPTS,
  151. )
  152. return False
  153. def needs_check(printer_id: int, state) -> bool:
  154. """Cheap test the status handler runs on every push before spawning a check."""
  155. if printer_id in _running:
  156. return False
  157. if not getattr(state, "connected", False):
  158. return False
  159. if (getattr(state, "state", "") or "").upper() not in IDLE_STATES:
  160. return False
  161. now = time.monotonic()
  162. found = False
  163. for ams_id, tray_id, _global_id, tray in _loaded_trays(state):
  164. key = (printer_id, ams_id, tray_id)
  165. if _settle(key, tray) and _due(printer_id, key, now):
  166. found = True
  167. return found
  168. async def reapply_lost_kprofiles(
  169. printer_id: int, global_trays: set[int] | None = None, *, throttle: bool = True
  170. ) -> int:
  171. """Re-select the stored K-profile on every slot whose selection was lost.
  172. ``global_trays`` limits the pass to the trays a print uses. ``throttle``
  173. off is for the dispatch guard: a job about to start must not wait out a
  174. retry interval, and that runs once per job anyway. Returns how many slots
  175. were re-selected.
  176. """
  177. # The dispatch guard runs regardless: a pass already in flight may have
  178. # skipped this job's trays on its retry interval.
  179. if throttle and printer_id in _running:
  180. return 0
  181. state = printer_manager.get_status(printer_id)
  182. client = printer_manager.get_client(printer_id)
  183. if state is None or client is None or not getattr(state, "connected", False):
  184. return 0
  185. model = printer_manager.get_model(printer_id)
  186. nozzles = getattr(state, "nozzles", None) or []
  187. dual_nozzle = is_dual_nozzle_model(model) or (len(nozzles) > 1 and bool(getattr(nozzles[1], "nozzle_diameter", "")))
  188. now = time.monotonic()
  189. candidates = []
  190. for ams_id, tray_id, global_id, tray in _loaded_trays(state):
  191. key = (printer_id, ams_id, tray_id)
  192. if not _settle(key, tray):
  193. continue
  194. if global_trays is not None and global_id not in global_trays:
  195. continue
  196. if throttle and not _due(printer_id, key, now):
  197. continue
  198. # Claimed before the first await, so a push arriving meanwhile does
  199. # not pick the same slot up a second time.
  200. _watches.setdefault(key, _SlotWatch()).next_check = now + RETRY_INTERVAL_S
  201. candidates.append((key, ams_id, tray_id, tray))
  202. if not candidates:
  203. return 0
  204. applied = 0
  205. if throttle:
  206. _running.add(printer_id)
  207. try:
  208. async with async_session() as db:
  209. for key, ams_id, tray_id, tray in candidates:
  210. slot_nozzle = resolve_slot_nozzle(state, ams_id, tray_id, model)
  211. if dual_nozzle:
  212. if slot_nozzle.extruder is None:
  213. # Unknown nozzle on a dual machine: picking extruder 0
  214. # would be a guess, and a wrong guess binds the other
  215. # hotend's calibration.
  216. continue
  217. extruders = [slot_nozzle.extruder]
  218. else:
  219. # One nozzle, but not one extruder number: the external
  220. # holder resolves to 1 (it is H2D's Ext-L), and Configure
  221. # Slot stores the profile under that, while the spool form
  222. # stores 0. Both mean the only nozzle there is.
  223. extruders = list(dict.fromkeys([0, slot_nozzle.extruder_or_default]))
  224. profile = None
  225. for extruder in extruders:
  226. profile = await find_slot_kprofile_for_extruder(
  227. db,
  228. printer_id,
  229. ams_id,
  230. tray_id,
  231. extruder,
  232. slot_nozzle.diameter,
  233. model,
  234. slot_nozzle.flow,
  235. )
  236. if profile is not None:
  237. break
  238. if profile is None or profile.cali_idx is None or profile.cali_idx < 0:
  239. _watches.setdefault(key, _SlotWatch()).next_check = now + NO_PROFILE_RECHECK_S
  240. continue
  241. client.extrusion_cali_sel(
  242. ams_id=ams_id,
  243. tray_id=tray_id,
  244. cali_idx=profile.cali_idx,
  245. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx")),
  246. nozzle_diameter=slot_nozzle.diameter,
  247. )
  248. applied += 1
  249. watch = _watches.setdefault(key, _SlotWatch())
  250. watch.attempts += 1
  251. logger.info(
  252. "[Printer %s] AMS%d-T%d lost its K-profile (cali_idx=%s): re-selected stored "
  253. "profile %r (cali_idx=%d), attempt %d",
  254. printer_id,
  255. ams_id,
  256. tray_id,
  257. tray.get("cali_idx"),
  258. profile.name,
  259. profile.cali_idx,
  260. watch.attempts,
  261. )
  262. except Exception:
  263. logger.exception("[Printer %s] K-profile re-selection failed", printer_id)
  264. finally:
  265. if throttle:
  266. _running.discard(printer_id)
  267. return applied