"""Opt-in temperature control of Commander PRO PWM ports: the GPU-side group follows GPU temperature and an optional CPU-side group follows CPU temperature. Optional motherboard header fans follow the hotter of the two (stopped while cool) and run at 100% while either group works hard.""" from __future__ import annotations import argparse import collections import logging import math import time from kurgan.cooling.board_fans import Nct6687, parse_channels from kurgan.cooling.profiles import BALANCED, FanProfile from kurgan.hardware.hid import HidError from kurgan.telemetry.sensors import CommanderPro, IntelPackage log = logging.getLogger(__name__) # The Balanced profile's curves (the original ones); the active profile can replace them at runtime. CURVE, CPU_CURVE, TOP_CURVE = BALANCED.gpu_curve, BALANCED.cpu_curve, BALANCED.top_curve CPU_AVERAGE = 5 # seconds of CPU package temperature averaged, so momentary spikes don't surge the fans BOOST_ON, BOOST_OFF = 85, 65 # case fan duty (either side) that starts / ends the top-fan boost TOP_START, TOP_STOP = BALANCED.top_start, BALANCED.top_stop # top fans start at / stop below (C) ... TOP_STOP_HOLD = 30 # ... once it has stayed below the stop temperature for this many seconds TOP_KICK, TOP_KICK_SECONDS = 40, 3 # spin-up duty when starting from stopped # Consecutive low/zero-RPM polls (1 s apart) before a stall is believed: one reading can glitch. STALL_READINGS = 3 def parse_ports(text: str) -> tuple[int, ...]: try: ports = tuple(int(p.strip()) for p in text.split(",")) except ValueError as e: raise argparse.ArgumentTypeError("Use three comma-separated ports, e.g. 1,2,3") from e if len(ports) != 3 or len(set(ports)) != 3 or any(p not in range(1, 7) for p in ports): raise argparse.ArgumentTypeError("Specify exactly three distinct Commander PRO ports (1-6)") return ports def _curve_duty(curve: tuple[tuple[int, int], ...], temp: float | None) -> int: if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110: return 100 for (t0, d0), (t1, d1) in zip(curve, curve[1:]): if temp <= t1: return math.ceil(d0 + max(0, temp - t0) * (d1 - d0) / (t1 - t0)) return 100 def gpu_duty(temp: float | None) -> int: return _curve_duty(CURVE, temp) def cpu_duty(temp: float | None) -> int: return _curve_duty(CPU_CURVE, temp) class TopFanCurve: """Motherboard header fans on their own curve from the hotter of CPU/GPU, stopped while cool. They are also held at 100% while either case fan group works hard; on exit the BIOS curve takes over again. A fan that stops turning while commanded to spin raises all of them to 100% and says so (see _tach_stall).""" RETRY = 30.0 def __init__(self, channels: tuple[int, ...], board_factory=Nct6687, profile: FanProfile = BALANCED): self.channels = parse_channels(",".join(map(str, channels))) self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop self.temp: float | None = None self._mask = sum(1 << c for c in self.channels) self._factory = board_factory self.board: Nct6687 | None = None self.boosted = False self.running = False self.duty = 0 self.status = "Starting" self.rpms: dict[int, int] = {} # latest tach reading per channel, for the snapshot self._retry_at = 0.0 self._written: int | None = None self._kick_until = 0.0 self._cool_since: float | None = None self._last_rise = 0.0 self._last_update: float | None = None self._spun: set[int] = set() # channels whose tach has been seen turning self._zeros = collections.Counter() # consecutive zero-RPM polls per channel def apply_profile(self, profile: FanProfile) -> None: self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop def _status(self, text: str, warning: bool = False) -> None: if text != self.status: (log.warning if warning else log.info)("Top fans: %s", text) self.status = text def snapshot(self) -> dict: return {"channels": list(self.channels), "temp": self.temp, "duty": self.duty, "running": self.running, "boosted": self.boosted, "status": self.status, "rpms": {str(c): self._shown_rpm(c) for c in self.channels}, "failsafe": self.status.startswith(("FAILSAFE", "UNAVAILABLE"))} def _shown_rpm(self, channel: int) -> int | None: """The channel's RPM, or None while its tach has never been seen turning: on this board SYS_FAN1's tach isn't wired, and a constant 0 would read as a dead fan.""" rpm = self.rpms.get(channel) return rpm if rpm or channel in self._spun else None def close(self) -> None: if self.board is not None: self.board.close() self.board = None self._written = None def _target(self, case_duty: int, temp: float | None, now: float) -> tuple[int, str]: self.boosted = case_duty >= BOOST_ON or (self.boosted and case_duty > BOOST_OFF) if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110: self.running, self._cool_since = True, None return 100, "FAILSAFE 100%: temperature unavailable" if not self.running and (temp >= self.start or self.boosted): self.running, self._cool_since = True, None self._kick_until = now + TOP_KICK_SECONDS elif self.running and temp < self.stop and not self.boosted: self._cool_since = now if self._cool_since is None else self._cool_since if now - self._cool_since >= TOP_STOP_HOLD: self.running, self._cool_since = False, None else: self._cool_since = None if not self.running: return 0, f"{temp:.0f} C, stopped (start at {self.start} C)" target = _curve_duty(self.curve, temp) if self.boosted: target = 100 if now < self._kick_until: target = max(target, TOP_KICK) return target, f"{temp:.0f} C, {{duty}}%" + (f" (case fans >= {BOOST_ON}%)" if self.boosted else "") def _tach_stall(self, now: float) -> list[int] | None: """Channels whose fan was seen turning but now reads 0 RPM: stalled or unplugged. A channel whose tachometer has never been seen turning (an empty header, or a tach this board doesn't wire to the channel) is left alone, so a wrong channel-to-tach guess cannot cry wolf. Returns the stalled channels; the duty is raised to 100% for the caller to write.""" assert self.board is not None tachs = self.board.rpms() self.rpms = {c: tachs[c] for c in self.channels} if self.duty <= 0 or now < self._kick_until: self._zeros.clear() # stopped or spinning up: zero RPM proves nothing yet return None stalled = [] for c in self.channels: if self.rpms[c] > 0: self._spun.add(c) self._zeros[c] = 0 elif c in self._spun: self._zeros[c] += 1 if self._zeros[c] >= STALL_READINGS: stalled.append(c) if stalled: self.duty, self._last_rise = 100, now return stalled or None def update(self, case_duty: int, temp: float | None, now: float) -> None: self.temp = temp target, text = self._target(case_duty, temp, now) elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update)) self._last_update = now if target == 0 or target >= self.duty: if target > self.duty: self._last_rise = now self.duty = target elif now - self._last_rise >= 10: self.duty = max(target, self.duty - int(2 * elapsed)) if self.board is None and now < self._retry_at: return try: if self.board is None: self.board = self._factory() stalled = self._tach_stall(now) # Compared every poll, so a firmware reset (e.g. after sleep) or a crash is corrected. if self.duty != self._written or self.board.manual_mask() & self._mask != self._mask: self.board.set_manual(self.channels, self.duty) self._written = self.duty if stalled: text = f"FAILSAFE 100%: no RPM on channels {stalled}" self._status(text.format(duty=self.duty), warning=text.startswith("FAILSAFE")) except Exception as e: # Any failure, a bug included: the top fans must not take the case fans' control # loop down with them. Best effort: hand the channels back to the BIOS curve, so a # manual duty left behind (0% included) doesn't persist until the next successful # write or a reboot. if not isinstance(e, (OSError, ValueError)) and not self.status.startswith("UNAVAILABLE"): log.error("Top fan control failed unexpectedly", exc_info=True) held, handed_back = self._written, False try: if self.board is not None: self.board.set_auto(self.channels) handed_back = True except Exception: # the fallback must never mask the original error log.debug("Cannot hand the top fans back to the BIOS curve", exc_info=True) if handed_back: note = "BIOS curve keeps control" elif held is not None: note = f"fans held at the last written duty ({held}%)" else: note = "no duty was ever written" self._status(f"UNAVAILABLE ({e}); {note}", warning=True) self.close() self._retry_at = now + self.RETRY def release(self) -> None: try: if self.board is None: self.board = self._factory() self.board.set_auto(self.channels) self.boosted = self.running = False except (OSError, ValueError): log.exception("Cannot return top fans to the BIOS curve") finally: self.close() class CaseFanGroup: """Three Commander PRO ports following one temperature: immediate rises, slow falls, failsafe 100%.""" def __init__(self, name: str, curve, commander: CommanderPro, ports: tuple[int, ...]): self.name = name self.curve = curve self.ports = parse_ports(",".join(map(str, ports))) self.commander = commander self.status = "Starting" self.duty = 100 self.temp: float | None = None self.rpms: dict[int, int] = {} self._last_update: float | None = None self._last_rise = 0.0 self._started: float | None = None self._lows = {p: 0 for p in self.ports} # consecutive low-RPM polls per port def set_status(self, text: str, warning: bool = False) -> None: if text != self.status: (log.warning if warning else log.info)("%s case fans: %s", self.name, text) self.status = text def snapshot(self) -> dict: return {"name": self.name, "ports": list(self.ports), "temp": self.temp, "duty": self.duty, "rpms": {str(p): self.rpms.get(p) for p in self.ports}, "status": self.status, "failsafe": self.status.startswith(("FAILSAFE", "CONTROL ERROR"))} def update(self, temp: float | None, now: float) -> None: self.temp = temp target = _curve_duty(self.curve, temp) invalid = temp is None or not math.isfinite(temp) or not 0 <= temp <= 110 if self._last_update is None or now - self._last_update > 5: self.duty = 100 self._last_rise = now self._started = now self._lows = {p: 0 for p in self.ports} elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update)) if target >= self.duty: if target > self.duty or invalid: self._last_rise = now self.duty = target elif now - self._last_rise >= 10: self.duty = max(target, self.duty - int(2 * elapsed)) self._last_update = now rpms = self.rpms = self.commander.set_duty(self.ports, self.duty) if self._started is not None and now - self._started >= 10: for p in self.ports: self._lows[p] = self._lows[p] + 1 if rpms.get(p, 0) < 200 else 0 stalled = [p for p in self.ports if self._lows[p] >= STALL_READINGS] if stalled: self.duty = 100 self._last_rise = now self.commander.set_duty(self.ports, 100) self.set_status(f"FAILSAFE 100%: no/low RPM on ports {stalled}", warning=True) return if invalid: self.set_status(f"FAILSAFE 100%: {self.name} temperature unavailable", warning=True) else: self.set_status(f"{self.name} {temp:.0f} C, {self.duty}% PWM; " + ", ".join(f"{p}: {rpms.get(p, 0)} rpm" for p in self.ports)) def failsafe(self) -> None: self.duty = 100 self._last_update = None try: self.commander.set_duty(self.ports, 100) except Exception: # the worker's finally block depends on this never raising log.exception("Cannot set %s case fans to failsafe 100%%; controller unavailable", self.name) class CpuTemperature: """CPU package temperature, averaged over CPU_AVERAGE readings for the fans, and package power. read() returns the average (None while unavailable); `temp` and `power` hold the latest readings and `error` why there are none.""" RETRY_SECONDS = 15.0 # pause after a read failure, so a lost PawnIO device is not re-opened every poll def __init__(self, factory=IntelPackage): self._factory = factory self.pkg: IntelPackage | None = None self._retry_at = 0.0 self._recent: collections.deque[float] = collections.deque(maxlen=CPU_AVERAGE) self.temp: float | None = None self.power: float | None = None self.error: str | None = "not read yet" def read(self, now: float) -> float | None: if self.pkg is None and now >= self._retry_at: try: self.pkg = self._factory() except Exception as e: # PawnIO missing, not admin, ... log.warning("CPU temperature unavailable for fan control: %s", e) self.error = str(e) self._retry_at = now + 60 temp = power = None if self.pkg is not None: try: temp = self.pkg.temperature() power = self.pkg.power() self.error = None if temp is not None else "the package sensor reported no reading" except OSError as e: log.warning("CPU temperature read failed, will retry: %s", e) self.error = str(e) self.close() self._retry_at = now + self.RETRY_SECONDS self.temp, self.power = temp, power if temp is None: self._recent.clear() return None self._recent.append(temp) return sum(self._recent) / len(self._recent) def close(self) -> None: if self.pkg is not None: self.pkg.msr.close() self.pkg = None class CaseFanControl: # Pause after a control error before polling again, so a lost device is not re-opened # (with a full traceback and process enumeration) every second. ERROR_RETRY_SECONDS = 5.0 def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...], cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None, profile: FanProfile = BALANCED): """Driven by the hardware service's loop (kurgan.hw.service): step() once a second with fresh temperatures, shutdown() when it ends.""" self.commander = commander self.profile = profile self._reported: float | None = None # when the last unexpected error was logged self.gpu = CaseFanGroup("GPU", profile.gpu_curve, commander, gpu_ports) self.cpu = CaseFanGroup("CPU", profile.cpu_curve, commander, cpu_ports) if cpu_ports else None if self.cpu is not None and set(self.cpu.ports) & set(self.gpu.ports): raise ValueError("CPU-side and GPU-side ports must not overlap") self.groups = [g for g in (self.gpu, self.cpu) if g is not None] self.top = top if top is not None: top.apply_profile(profile) def apply_profile(self, profile: FanProfile) -> None: """Switch curves; rises take effect on the next poll, falls follow the usual slow ramp-down.""" self.gpu.curve = profile.gpu_curve if self.cpu is not None: self.cpu.curve = profile.cpu_curve if self.top is not None: self.top.apply_profile(profile) self.profile = profile log.info("Fan profile: %s", profile.name) def snapshot(self) -> dict: return {"profile": self.profile.key, "groups": [g.snapshot() for g in self.groups], "top": None if self.top is None else self.top.snapshot()} @property def status(self) -> str: return self.gpu.status def update(self, gpu_temp: float | None, now: float, cpu_temp: float | None = None) -> None: self.gpu.update(gpu_temp, now) if self.cpu is not None: self.cpu.update(cpu_temp, now) if self.top is not None: temps = [gpu_temp] + ([cpu_temp] if self.cpu is not None else []) valid = all(t is not None and math.isfinite(t) and 0 <= t <= 110 for t in temps) self.top.update(max(g.duty for g in self.groups), max(temps) if valid else None, now) def failsafe(self) -> None: for g in self.groups: g.failsafe() def _error(self, text: str) -> None: for g in self.groups: g.set_status(text, warning=True) def _failsafe_top(self) -> None: if self.top is not None: try: # update() never raises for the board, but a bug must not stop the case fans' fail-safe self.top.update(100, None, time.monotonic()) except Exception: log.debug("Top fans: failsafe update failed", exc_info=True) def step(self, gpu_temp: float | None, cpu_temp: float | None, now: float) -> float: """One control pass; never raises. Returns the seconds to wait before the next one. A device error closes the Commander PRO (reopened on the next pass) and fails every fan safe. So does any other error, a bug included: fan control must not end for the life of the service. Those are logged at most once a minute.""" try: self.update(gpu_temp, now, cpu_temp) return 1.0 except (OSError, HidError) as e: self._error(f"CONTROL ERROR: {e}") self.failsafe() self.commander.close() except Exception as e: if self._reported is None or now - self._reported >= 60: self._reported = now log.exception("Case fan control error; failing safe and retrying") self._error(f"CONTROL ERROR: {e}") self.failsafe() self._failsafe_top() return self.ERROR_RETRY_SECONDS def shutdown(self) -> None: """Leave the case fans at 100% and hand the top fans back to the BIOS curve.""" self.failsafe() self.commander.close() if self.top is not None: self.top.release() def main() -> int: ap = argparse.ArgumentParser(description=__doc__) action = ap.add_mutually_exclusive_group(required=True) action.add_argument("--identify", type=parse_ports, metavar="1,2,3", help="raise these three ports to 100%% to identify their physical side") action.add_argument("--save-ports", type=parse_ports, metavar="4,5,6", help="save identified GPU-side ports (hw-settings.json; run elevated)") action.add_argument("--save-cpu-ports", type=parse_ports, metavar="1,2,3", help="save identified CPU-side ports (follow CPU temperature)") action.add_argument("--save-top-channels", type=parse_channels, metavar="2,5", help="save motherboard PWM channels (see board_fans.py) for the top-fan curve") args = ap.parse_args() logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") if args.save_ports or args.save_cpu_ports or args.save_top_channels: from kurgan.hw import settings as hw_settings from kurgan.settings import SettingsError try: # the hardware service's file: only an elevated prompt can write it hw_settings.ensure_data_dir() settings = hw_settings.load() if args.save_ports: settings.update("cooling", gpu_ports=list(args.save_ports)) elif args.save_cpu_ports: settings.update("cooling", cpu_ports=list(args.save_cpu_ports)) else: settings.update("cooling", top_channels=list(args.save_top_channels)) except (OSError, SettingsError): log.exception("Cannot save fan configuration") return 1 print(f"Saved {settings.section('cooling')} to {settings.path}.") print("Restart the hardware service to apply it (elevated): Restart-Service KurganHw") return 0 commander = CommanderPro() try: rpms = commander.set_duty(args.identify, 100) print(f"Ports {args.identify} set to 100%. They will stay at 100% after this test.") time.sleep(5) rpms = commander.set_duty(args.identify, 100) print("RPMs: " + ", ".join(f"{p}: {rpm}" for p, rpm in rpms.items())) return 0 except (OSError, HidError) as e: log.error("Identification failed: %s%s", e, " (stop the hardware service first, elevated: " "Stop-Service KurganHw)" if "in use" in str(e) else "") return 1 finally: commander.close() if __name__ == "__main__": raise SystemExit(main())