- kurgan/hw/client.py: HardwareClient polls the service's state once a second on its own thread, reconnecting (and greeting again) whenever the pipe breaks, and sends the app's chase clock with each poll. Profile and RAM lighting changes are sent at once: bad values are ValueError before anything is sent; an unreachable or refusing service is HardwareUnavailable. A state that stops arriving (5 s) or a service loop that stops publishing (15 s) counts as unavailable. PipeTransport for the real pipe, LocalTransport (same encoding and checks, no pipe) for --demo and tests. - Telemetry: the CPU package temperature and power (CpuSensors(package=...)) and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come from the service; the app opens neither PawnIO nor the Commander PRO. "hardware service" is its own health source, and while it's down the missing CPU temperature isn't reported a second time. - The fan UI, profile buttons and fan history come from the service's state; the RAM lighting zone goes through it (LightingService(ram=...)), and the case fan and GPU zones stay local. The alert monitor balloons "Hardware service unavailable"; the header shows a hardware service pill instead of the admin-rights one (and warns if the app itself runs elevated); the tray lines read the service's fans. POSTs answer 503 while it's unavailable. - Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the service owns those now. - settings.json: cooling and lighting.memory are legacy. Old files keep them (still validated), nothing reads them, and defaults no longer add them. - --demo runs the real HardwareService in-process on the demo fakes, with its settings in demo-hw-settings.json, through the same client. - --preview reads the CPU temperature and fan power from the service too. - Tests: 13 for the client (including a real pipe end to end); the alert, lighting, settings and web tests follow the new shapes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
171 lines
8.2 KiB
Python
171 lines
8.2 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 hardware service keeps its own
|
|
temperature reads on purpose: cooling must not depend on this app staying healthy. Its CPU
|
|
package temperature and power and its fan RPMs come here through kurgan.hw.client.)
|
|
"""
|
|
|
|
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
|
|
EMPTY_READS = 3 # consecutive empty readings before a source counts as failing
|
|
SERVICE_SOURCE = "hardware service"
|
|
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, hw=None):
|
|
"""hw: the hardware service client (its error says why it's unavailable); listed in
|
|
health() as its own source, so its absence isn't also reported as a missing CPU temperature."""
|
|
self.cpu, self.gpu, self.system, self.hw = cpu, gpu, system, hw
|
|
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._failures: dict[str, tuple[float, str]] = {} # source -> (monotonic, message) of its latest failed read
|
|
self._empty: dict[str, int] = {} # source -> consecutive empty readings
|
|
|
|
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."""
|
|
# The sensor classes don't raise when their device is lost (they back off and return
|
|
# empty readings), so a reading without a temperature counts as failing too.
|
|
hw_error = None if self.hw is None else self._source(SERVICE_SOURCE, lambda: self.hw.error, None,
|
|
missing=lambda error: error)
|
|
c = self._source("CPU sensors", self.cpu.read, Readings(),
|
|
missing=lambda r: None if r.temp is not None or hw_error is not None else
|
|
f"no CPU temperature ({getattr(self.cpu, 'status', None) or 'reader unavailable'})")
|
|
g = self._source("GPU sensors", self.gpu.read, Readings(),
|
|
missing=lambda r: None if r.temp is not None else "no GPU readings (driver unavailable)")
|
|
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, missing: Callable | None = None):
|
|
"""read(*args), or fallback if it raises. Failures are kept for health(); so is a result
|
|
that missing(result) describes as empty (a message), once EMPTY_READS in a row were."""
|
|
try:
|
|
result = read(*args)
|
|
except Exception as e:
|
|
# The loop retries every second, so log each failing source at most once a minute.
|
|
now = time.monotonic()
|
|
last = self._failures.get(name)
|
|
if last is None or now - last[0] >= 60:
|
|
log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True)
|
|
self._failures[name] = (now, f"{type(e).__name__}: {e}")
|
|
return fallback
|
|
problem = missing(result) if missing is not None else None
|
|
if problem is None:
|
|
self._empty.pop(name, None)
|
|
if self._failures.pop(name, None) is not None: # reading again: healthy
|
|
log.info("%s reading again", name)
|
|
return result
|
|
self._empty[name] = self._empty.get(name, 0) + 1
|
|
if self._empty[name] >= EMPTY_READS: # one empty read at startup or a glitch proves nothing
|
|
if name not in self._failures:
|
|
log.warning("%s: %s", name, problem)
|
|
self._failures[name] = (time.monotonic(), problem)
|
|
return result
|
|
|
|
def health(self) -> dict[str, dict]:
|
|
"""Sources whose latest read failed: name -> {"error", "age_s"}. Empty while every source reads."""
|
|
now = time.monotonic()
|
|
return {name: {"error": message, "age_s": round(now - when, 1)}
|
|
for name, (when, message) in self._failures.items()}
|
|
|
|
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, "health": self.health()}
|
|
return {
|
|
"seq": s.seq, "t": s.t,
|
|
"health": self.health(),
|
|
"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), "partial": not s.power.complete,
|
|
"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}
|