"""The hardware service's work: fan control on its own temperature readings, RAM lighting, and the state snapshot the app reads over the pipe. One loop, once a second (HardwareService.run): read the CPU package (PawnIO MSR: temperature and power) and the GPU (NVML: temperature) run the fan curves (CaseFanControl.step), or, while the port mapping isn't saved, only read the Commander PRO's RPMs, or, while hw-settings.json is invalid, hold every fan at 100% publish a snapshot for the pipe Nothing on the pipe side takes a lock the loop needs, and every read the loop makes is guarded, so neither a client nor a sensor fault can stop it. When it ends, the case fans are left at 100% and the top fans go back to the BIOS curve, as The Kurgan always did on exit. """ from __future__ import annotations import logging import math import os import threading import time from kurgan import __version__ from kurgan.cooling.board_fans import Nct6687 from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve from kurgan.cooling.profiles import PROFILES from kurgan.hw.protocol import PROTOCOL_VERSION, Unavailable from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP log = logging.getLogger(__name__) ERROR_RETRY_SECONDS = 5.0 LOG_EVERY = 60.0 # seconds between repeats of the same failure in the log def _clean(value): """JSON-safe copy: NaN and infinities become None (the protocol refuses them).""" if isinstance(value, float): return value if math.isfinite(value) else None if isinstance(value, dict): return {str(k): _clean(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [_clean(v) for v in value] return value class SyncedChase: """The RAM chase's clock in the service, a stand-in for the app's ChaseTiming. The app sends its clock (phase, rate) about once a second (ram_chase); in between, and when the app is gone, the phase runs on at the last rate. Both processes read time.monotonic(), which on Windows is the system-wide performance counter, so no offset needs translating.""" IDLE_RATE = 1 / 0.15 # LEDs per second: the app's default idle pace (--rgb-chase-step-ms 150) def __init__(self): self._lock = threading.Lock() self.phase = float(SIDE_CHASE_BOTTOM_STEP) self.rate = self.IDLE_RATE self.last_time: float | None = None def sync(self, phase: float, rate: float, now: float) -> None: with self._lock: self.phase, self.rate, self.last_time = phase, rate, now def reset(self, phase: float = 0.0) -> None: with self._lock: self.phase, self.last_time = phase, None def set_power(self, total_watts: float | None) -> None: pass # the pace comes with the phase def rate_for(self, total_watts: float | None) -> float: return self.rate def sample(self, now: float) -> tuple[float, float]: with self._lock: if self.last_time is None: self.last_time = now self.phase += self.rate * max(0.0, now - self.last_time) self.last_time = max(now, self.last_time) return self.phase, self.rate class HardwareService: def __init__(self, settings, settings_error: str | None = None, *, commander=None, board_factory=Nct6687, gpu_factory=None, cpu=None, memory=None): """settings: kurgan.hw.settings.load(), or None when hw-settings.json is invalid (settings_error says why). The rest replace the real hardware in tests and --demo.""" from kurgan.telemetry.sensors import CommanderPro, GpuSensors self.started = time.time() self.settings = settings self.settings_error = settings_error self.commander = commander if commander is not None else CommanderPro() self.cpu = cpu if cpu is not None else CpuTemperature() self._gpu_factory = gpu_factory or (lambda: GpuSensors(load_source="nvml")) self._gpu = None self.gpu_temp: float | None = None self.gpu_error: str | None = "not read yet" self.chase = SyncedChase() if memory is None: from kurgan.lighting.memory import MemoryLighting from kurgan.theme import Theme memory = MemoryLighting(Theme(), chase_timing=self.chase) self.memory = memory self._memory_events = {"temperature": threading.Event(), "chase": threading.Event()} self._memory_mode = "off" self._lock = threading.Lock() # settings changes (pipe threads); the loop never takes it self._failures: dict[str, float] = {} # what -> when it was last logged self._rpms: list[int] = [] self._seq = 0 self.fans: CaseFanControl | None = None self.note: str | None = None # Kept here so neither the loop nor `state` ever waits on the settings file's lock. self._profile: str | None = None if settings is None else settings.get("cooling", "profile") if settings is None: self.note = (f"hw-settings.json is invalid, so every case fan is held at 100%: {settings_error}. " "Fix the file, then restart the hardware service.") else: cooling = settings.section("cooling") if cooling.get("gpu_ports"): top = None if cooling.get("top_channels"): top = TopFanCurve(tuple(cooling["top_channels"]), board_factory=board_factory) self.fans = CaseFanControl(self.commander, tuple(cooling["gpu_ports"]), tuple(cooling.get("cpu_ports") or ()) or None, top, profile=PROFILES[cooling["profile"]]) self.commander.controlled = True else: self.note = "Fan control isn't set up: save the Commander PRO ports first (see README)." self._apply_memory(settings.get("lighting", "memory")) self._snapshot = self._build(time.time()) # -- the loop def _logged(self, what: str, now: float) -> bool: """True when a failure of `what` should be logged now (at most once a LOG_EVERY).""" last = self._failures.get(what) if last is None or now - last >= LOG_EVERY: self._failures[what] = now return True return False def _read_gpu(self, now: float) -> float | None: try: if self._gpu is None: self._gpu = self._gpu_factory() temp = self._gpu.read().temp self.gpu_error = None if temp is not None else "no GPU temperature (driver unavailable?)" return temp except Exception as e: # rebuilt on the next pass if self._logged("gpu", now): log.warning("GPU temperature read failed; the GPU-side fans fail safe: %s", e, exc_info=True) self.gpu_error = f"{type(e).__name__}: {e}" self._gpu = None return None def _read_cpu(self, now: float) -> float | None: try: return self.cpu.read(now) except Exception as e: if self._logged("cpu", now): log.warning("CPU temperature read failed; the CPU-side fans fail safe: %s", e, exc_info=True) self.cpu.temp = self.cpu.power = None self.cpu.error = f"{type(e).__name__}: {e}" return None def _full_speed(self, now: float) -> float: try: self._rpms = sorted(self.commander.full_speed().values()) return 1.0 except Exception as e: if self._logged("full-speed", now): log.error("Can't hold the case fans at 100%%: %s", e) self.commander.close() self._rpms = [] return ERROR_RETRY_SECONDS def tick(self, now: float) -> float: """One pass of the loop; never raises. Returns the seconds until the next.""" delay = 1.0 try: self.gpu_temp = self._read_gpu(now) cpu_average = self._read_cpu(now) if self.fans is not None: delay = self.fans.step(self.gpu_temp, cpu_average, now) self._rpms = self.commander.read() elif self.settings is None: delay = self._full_speed(now) else: self._rpms = self.commander.read() # read-only, for the app's power estimate self.memory.set_temperature(self.cpu.temp, self.gpu_temp) except Exception: if self._logged("loop", now): log.exception("Hardware loop error; failing safe and retrying") if self.fans is not None: self.fans.failsafe() delay = ERROR_RETRY_SECONDS try: self._snapshot = self._build(time.time()) except Exception: if self._logged("snapshot", now): log.exception("Can't build the state snapshot") return delay def run(self, stop: threading.Event) -> None: log.info("Hardware loop started (%s)", "fan control on" if self.fans is not None else "fans held at 100%" if self.settings is None else "fan control not set up") try: while not stop.is_set(): stop.wait(self.tick(time.monotonic())) finally: if self.fans is not None: self.fans.shutdown() else: self.commander.close() self.cpu.close() log.info("Hardware loop stopped; case fans at 100%%, top fans on the BIOS curve") def start_lighting(self, stop: threading.Event) -> threading.Thread: e = self._memory_events thread = threading.Thread(target=self.memory.run, args=(stop, e["temperature"], e["chase"]), name="memory-lighting", daemon=True) thread.start() return thread # -- state def _build(self, t: float) -> dict: fans = self.fans if fans is not None: cooling = {**fans.snapshot(), "note": None, "row": [round(t, 1), fans.gpu.duty, None if fans.cpu is None else fans.cpu.duty, None if fans.top is None else fans.top.duty]} else: cooling = {"profile": self._profile, "groups": [], "top": None, "note": self.note, "row": None} self._seq += 1 return _clean({ "service": {"version": __version__, "protocol": PROTOCOL_VERSION, "pid": os.getpid(), "uptime": round(t - self.started), "settings_error": self.settings_error}, "seq": self._seq, "t": round(t, 3), "cpu": {"temp": self.cpu.temp, "power": self.cpu.power, "error": self.cpu.error}, "gpu": {"temp": self.gpu_temp, "error": self.gpu_error}, "commander": {"rpms": list(self._rpms)}, "cooling": cooling, "lighting": {"memory": {"mode": self._memory_mode, "status": self.memory.status}}, }) def snapshot(self) -> dict: """The latest published state, with the current profile and RAM lighting (a change made over the pipe shows at once, not at the next pass).""" state = dict(self._snapshot) state["cooling"] = {**state["cooling"], "profile": self._profile} state["lighting"] = {"memory": {"mode": self._memory_mode, "status": self.memory.status}} return state # -- operations (from the pipe; arguments already checked by the protocol) def _apply_memory(self, mode: str) -> None: for name, event in self._memory_events.items(): # clear the old pattern before setting the new if name != mode: event.clear() if mode != "off": self._memory_events[mode].set() self._memory_mode = mode def _save(self, section: str, **changes) -> None: if self.settings is None: raise Unavailable(f"hw-settings.json is invalid ({self.settings_error}); fix it and restart " "the hardware service") try: self.settings.update(section, **changes) except OSError as e: raise Unavailable(f"couldn't save hw-settings.json: {e}") from None def set_profile(self, key: str) -> None: with self._lock: self._save("cooling", profile=key) self._profile = key if self.fans is not None: self.fans.apply_profile(PROFILES[key]) log.info("Fan profile set to %s by the app", key) def set_ram_lighting(self, mode: str) -> None: with self._lock: self._save("lighting", memory=mode) self._apply_memory(mode) log.info("RAM lighting set to %s by the app", mode) def dispatch(self, op: str, args: dict): if op == "state": return self.snapshot() if op == "set_profile": self.set_profile(args["profile"]) return self.snapshot() if op == "set_ram_lighting": self.set_ram_lighting(args["mode"]) return self.snapshot() if op == "ram_chase": self.chase.sync(args["phase"], args["rate"], time.monotonic()) self.memory.set_power(args["power"]) return None raise ValueError(f"unknown operation {op!r}")