Files
the_kurgan/kurgan/telemetry/service.py
T
paul d637d46777 Fail safe, not dead: bound the HID cancel wait, isolate sensor failures, keep the fan worker alive
- hid.py: after a timed-out HID operation, wait at most 1 s for the driver to
  finish the cancelled IRP; if it does not, mark the channel broken so the
  caller's reconnect path closes it instead of blocking forever on a wedged
  device. Keep abandoned OVERLAPPED/buffer references alive until close so a
  late IRP completion cannot write into reused memory. Check CreateEventW.
- telemetry/service.py: read each source (CPU, GPU, system power, GPU memory)
  independently; a failing source now costs only its own readings instead of
  the whole sample, logged at most once a minute per source.
- sensors.py: the Commander PRO iCUE ownership check runs inside a guard; if
  ownership cannot be established the device is released rather than risking
  swapped replies (and the failure no longer escapes into the sample).
- cooling/control.py: an unexpected exception no longer ends fan control for
  the life of the process; fail safe, log at most once a minute, retry with a
  fresh sensor object after 5 s. failsafe() no longer raises, and control
  errors back off 5 s instead of re-opening the device every second.
2026-12-05 16:47:16 +13:00

135 lines
5.6 KiB
Python

"""Telemetry service: reads every sensor once a second on one thread and shares the result.
The LCD, the lighting, the tray tooltip and the web UI all use these samples, so the hardware
is polled once however many things are watching. (The fan worker keeps its own temperature
reads on purpose: cooling must not depend on any other worker staying healthy.)
"""
from __future__ import annotations
import collections
import logging
import threading
import time
from dataclasses import dataclass, field
from typing import Callable
from kurgan.telemetry.readings import PowerReadings, Readings
log = logging.getLogger(__name__)
HISTORY_SECONDS = 600
SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
@dataclass
class Sample:
seq: int
t: float # time.time()
cpu: Readings = field(default_factory=Readings)
gpu: Readings = field(default_factory=Readings)
power: PowerReadings = field(default_factory=PowerReadings)
vram: tuple[int, int] | None = None # (used, total) bytes
def row(self) -> tuple:
return (round(self.t, 1), _r(self.cpu.temp), _r(self.gpu.temp), _r(self.cpu.load), _r(self.gpu.load),
_r(self.power.cpu), _r(self.power.gpu), _r(self.power.other), _r(self.power.total),
None if self.vram is None else self.vram[0])
def _r(value: float | None, digits: int = 1) -> float | None:
return None if value is None else round(value, digits)
class Telemetry:
def __init__(self, cpu, gpu, system, interval: float = 1.0):
self.cpu, self.gpu, self.system = cpu, gpu, system
self.interval = interval
self._cond = threading.Condition()
self._latest: Sample | None = None
self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval))
self._listeners: list[Callable[[Sample], None]] = []
self._seq = 0
self._last_failure: dict[str, float] = {}
def subscribe(self, listener: Callable[[Sample], None]) -> None:
self._listeners.append(listener)
def read(self) -> Sample:
"""Read every source independently: one failing source costs only its own readings."""
c = self._source("CPU sensors", self.cpu.read, Readings())
g = self._source("GPU sensors", self.gpu.read, Readings())
p = self._source("system power", self.system.read, PowerReadings(), c, g)
vram = self._source("GPU memory", self.gpu.memory, None)
self._seq += 1
return Sample(self._seq, time.time(), c, g, p, vram)
def _source(self, name: str, read: Callable, fallback, *args):
try:
return read(*args)
except Exception as e:
# The loop retries every second, so log each failing source at most once a minute.
if time.monotonic() - self._last_failure.get(name, -1e9) >= 60:
self._last_failure[name] = time.monotonic()
log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True)
return fallback
def run(self, stop: threading.Event) -> None:
while not stop.is_set():
t0 = time.monotonic()
try:
sample = self.read()
except Exception:
log.exception("Sensor read failed; retrying")
stop.wait(5)
continue
with self._cond:
self._latest = sample
self._history.append(sample.row())
self._cond.notify_all()
if sample.seq == 5: # once the counters have settled
fmt = lambda v: "--" if v is None else f"{v:.0f}"
p = sample.power
log.info("Power: CPU %s + GPU %s + other %s = %s W; other = %s", fmt(p.cpu), fmt(p.gpu),
fmt(p.other), fmt(p.total), ", ".join(f"{k} {v:.1f}" for k, v in p.parts.items()))
for listener in self._listeners:
try:
listener(sample)
except Exception:
log.exception("Telemetry listener %r failed", listener)
stop.wait(max(0.0, self.interval - (time.monotonic() - t0)))
with self._cond:
self._cond.notify_all()
@property
def latest(self) -> Sample | None:
with self._cond:
return self._latest
def wait_newer(self, seq: int, timeout: float) -> Sample | None:
"""The first sample after `seq`, or the latest one (possibly None) after `timeout`."""
with self._cond:
self._cond.wait_for(lambda: self._latest is not None and self._latest.seq > seq, timeout)
return self._latest
def snapshot(self) -> dict:
s = self.latest
if s is None:
return {"seq": 0}
return {
"seq": s.seq, "t": s.t,
"cpu": {"temp": _r(s.cpu.temp), "load": _r(s.cpu.load), "clock": _r(s.cpu.clock, 0), "power": _r(s.cpu.power)},
"gpu": {"temp": _r(s.gpu.temp), "load": _r(s.gpu.load), "clock": _r(s.gpu.clock, 0), "power": _r(s.gpu.power),
"vram_used": None if s.vram is None else s.vram[0],
"vram_total": None if s.vram is None else s.vram[1]},
"power": {"cpu": _r(s.power.cpu), "gpu": _r(s.power.gpu), "other": _r(s.power.other),
"total": _r(s.power.total),
"parts": {k: round(v, 1) for k, v in s.power.parts.items()}},
"row": s.row(),
}
def history(self) -> dict:
with self._cond:
rows = list(self._history)
return {"series": SERIES, "rows": rows, "interval": self.interval}