Privilege split 6/11: the app reads and drives the hardware through the service

- 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>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:41:51 +13:00
1 parent 3e84ab1322
commit eb771656fb
15 files changed
+803 -179

No files matched your search

+2 -2
View File
@@ -249,8 +249,8 @@ tray menu, then run:
```
`--identify` leaves the selected group at 100%, rather than guessing its previous profile. Do not
guess the port mapping. `--gpu-fan-ports 4,5,6` overrides the saved ports for one run, and
`--no-gpu-fan-control` turns fan control off for one run.
guess the port mapping. (The app's old `--gpu-fan-ports` and `--no-gpu-fan-control` options are
gone: the hardware service owns the fans and reads the mapping from its own settings.)
**Controller ownership:** exit iCUE, FanControl and other Commander PRO tools. If you run OpenRGB,
disable its **Corsair Commander Pro** and **Corsair Lighting Node Core** detectors in both
+68 -83
View File
@@ -1,12 +1,13 @@
"""The Kurgan: one process for the LCD, fans, lighting, the local LLM servers and the web UI.
"""The Kurgan: one process for the LCD, lighting, the local LLM servers and the web UI.
Run: python -m kurgan (console, Ctrl+C to stop)
Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs, elevated)
Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs)
Preview: python -m kurgan --preview x.png (render one LCD frame from live sensors and exit)
Needs admin rights for PawnIO (CPU temperature/power, motherboard top fans, RAM lighting);
without them those parts show "--" or stay idle and everything else works. The LLM servers
are always started without admin rights (see kurgan/ai/launcher.py).
The fans, the CPU package temperature and power, and the RAM lighting belong to the hardware
service (kurgan.hw, the "The Kurgan hardware" Windows service): this app shows what it reports
and asks it for changes, over a named pipe. While the service is unavailable those parts show
"--" and everything else works; the fans never depend on this app.
"""
from __future__ import annotations
@@ -70,21 +71,28 @@ def _parse_color(text: str) -> tuple[int, int, int]:
ALERT_SECONDS = 5.0 # how often the alert monitor looks for things starting to go wrong
def alert_states(fans, ai, telemetry) -> dict[str, str]:
"""What is wrong right now: key -> message, for the things worth one balloon each."""
def alert_states(cooling: dict | None, ai, telemetry) -> dict[str, str]:
"""What is wrong right now: key -> message, for the things worth one balloon each.
cooling: the hardware service's fan state (HardwareClient.cooling())."""
from kurgan.telemetry.service import SERVICE_SOURCE
states = {}
if fans is not None:
for group in fans.groups:
if group.status.startswith(("FAILSAFE", "CONTROL ERROR")):
states[f"fans/{group.name}"] = f"{group.name} case fans: {group.status}"
if fans.top is not None and fans.top.status.startswith(("FAILSAFE", "UNAVAILABLE")):
states["fans/top"] = f"Top fans: {fans.top.status}"
if cooling is not None:
for group in cooling.get("groups") or ():
if group["status"].startswith(("FAILSAFE", "CONTROL ERROR")):
states[f"fans/{group['name']}"] = f"{group['name']} case fans: {group['status']}"
top = cooling.get("top")
if top is not None and top["status"].startswith(("FAILSAFE", "UNAVAILABLE")):
states["fans/top"] = f"Top fans: {top['status']}"
if ai is not None:
for backend in ai.snapshot()["backends"]:
if backend["error"]:
states[f"ai/{backend['key']}"] = f"{backend['label']}: {backend['error']}"
for name, info in telemetry.health().items():
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
if name == SERVICE_SOURCE:
states["hw"] = f"Hardware service unavailable: {info['error']}"
else:
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
return states
@@ -125,8 +133,6 @@ def balloon(messages: list[str]) -> tuple[str, str]:
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
from kurgan.cooling.control import parse_ports
ap = argparse.ArgumentParser(prog="python -m kurgan", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port", type=int, help="web UI port (default: settings.json web.port, 8080)")
@@ -150,14 +156,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
ap.add_argument("--load-hot", type=float, default=80.0)
ap.add_argument("--gpu-load", choices=("windows", "nvml"), default="windows")
ap.add_argument("--same-direction", action="store_true", help=argparse.SUPPRESS)
# Lighting: these override the saved mode for this run only (the web UI saves it).
# Lighting: these override the saved mode for this run only (the web UI saves it). The RAM
# has none: the hardware service drives it, and only the web UI changes it.
fans = ap.add_mutually_exclusive_group()
fans.add_argument("--rgb-temperature", action="store_true", help="case fan LEDs: temperature (this run)")
fans.add_argument("--rgb-side-chase", action="store_true", help="case fan LEDs: red side chase (this run)")
memory = ap.add_mutually_exclusive_group()
memory.add_argument("--rgb-memory-temperature", action="store_true", help="RAM: temperature (this run)")
memory.add_argument("--rgb-memory-side-chase", action="store_true", help="RAM: red side chase (this run)")
memory.add_argument("--rgb-memory-off", action="store_true", help="RAM: off (this run)")
gpu = ap.add_mutually_exclusive_group()
gpu.add_argument("--rgb-gpu-side-chase", action="store_true", help="GPU LEDs: red side chase (this run)")
gpu.add_argument("--rgb-gpu-off", action="store_true", help="GPU LEDs: off (this run)")
@@ -165,12 +168,6 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
ap.add_argument("--rgb-chase-fast-ms", type=float, default=25.0, help="ms per chase LED at full power")
ap.add_argument("--rgb-chase-idle-watts", type=float, default=150.0)
ap.add_argument("--rgb-chase-full-watts", type=float, default=550.0)
# Cooling
fan_options = ap.add_mutually_exclusive_group()
fan_options.add_argument("--gpu-fan-ports", type=parse_ports, metavar="1,2,3",
help="override the saved GPU-side Commander PRO ports for this run")
fan_options.add_argument("--no-gpu-fan-control", action="store_true",
help="disable case/top fan control for this run")
ap.add_argument("-v", "--verbose", action="store_true")
args = ap.parse_args(argv)
for name in ("rgb_chase_step_ms", "rgb_chase_fast_ms"):
@@ -181,8 +178,6 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
if not (math.isfinite(args.rgb_chase_idle_watts) and math.isfinite(args.rgb_chase_full_watts)
and args.rgb_chase_full_watts > args.rgb_chase_idle_watts):
ap.error("--rgb-chase-full-watts must be above --rgb-chase-idle-watts")
if args.preview and args.gpu_fan_ports:
ap.error("--preview cannot be combined with --gpu-fan-ports")
args.interval = max(0.25, min(2.0, args.interval))
return args
@@ -191,9 +186,6 @@ def lighting_overrides(args: argparse.Namespace) -> dict[str, str]:
overrides = {}
if args.rgb_temperature or args.rgb_side_chase:
overrides["case_fans"] = "temperature" if args.rgb_temperature else "chase"
if args.rgb_memory_temperature or args.rgb_memory_side_chase or args.rgb_memory_off:
overrides["memory"] = ("temperature" if args.rgb_memory_temperature else
"chase" if args.rgb_memory_side_chase else "off")
if args.rgb_gpu_side_chase or args.rgb_gpu_off:
overrides["gpu"] = "chase" if args.rgb_gpu_side_chase else "off"
return overrides
@@ -203,10 +195,10 @@ class Kurgan:
"""Owns the capabilities and answers the web UI and the tray."""
def __init__(self, args: argparse.Namespace, settings):
from kurgan.cooling.control import CaseFanControl, TopFanCurve
from kurgan.cooling.profiles import PROFILES
from kurgan.display.renderer import DashboardRenderer
from kurgan.display.service import DisplayService
from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, LocalTransport,
PipeTransport, RamLighting)
from kurgan.lighting.service import LightingService
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.telemetry.service import Telemetry
@@ -221,13 +213,19 @@ class Kurgan:
temp_warn=args.temp_warn, temp_hot=args.temp_hot,
load_warn=args.load_warn, load_hot=args.load_hot)
hw = None
self.hw_service = None # the hardware service, when it runs in-process (--demo)
if args.demo:
from kurgan import demo
hw = demo.hardware()
self.system = hw["system"] if hw else SystemPower()
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(),
self.hw_service = demo.hardware_service(os.path.join(paths.DATA_DIR, "demo-hw-settings.json"))
self.hw = HardwareClient(lambda: LocalTransport(self.hw_service.dispatch))
self.system = demo.FakeSystem(CommanderReadings(self.hw))
else:
self.hw = HardwareClient(PipeTransport)
self.system = SystemPower(fans=CommanderReadings(self.hw))
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(package=CpuPackage(self.hw)),
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
self.system, args.interval)
self.system, args.interval, hw=self.hw)
self.recorder = None
if not args.demo: # simulated samples must not mix into the real records
from kurgan.telemetry.record import Recorder
@@ -236,28 +234,12 @@ class Kurgan:
self.display = None if (args.no_lcd or hw) else DisplayService(
DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness)
cooling = settings.section("cooling")
self.fan_note = None
self.fans: CaseFanControl | None = None
gpu_ports = None if args.no_gpu_fan_control else (args.gpu_fan_ports or cooling.get("gpu_ports"))
if gpu_ports:
top = cooling.get("top_channels")
top_curve = None
if top:
top_curve = TopFanCurve(tuple(top), board_factory=hw["board"]) if hw else TopFanCurve(tuple(top))
self.fans = CaseFanControl(self.system.fans, tuple(gpu_ports),
tuple(cooling.get("cpu_ports") or ()) or None, top_curve,
profile=PROFILES[cooling["profile"]], sensors=hw["fan_sensors"] if hw else None)
self.system.fans.controlled = True
else:
self.fan_note = ("Fan control is off for this run (--no-gpu-fan-control)." if args.no_gpu_fan_control
else "Fan control isn't set up: save the Commander PRO ports first (see README).")
self.lighting = LightingService(
settings, self.theme,
(args.rgb_chase_step_ms / 1000, args.rgb_chase_fast_ms / 1000,
args.rgb_chase_idle_watts, args.rgb_chase_full_watts),
lighting_overrides(args), **(hw["lighting"] if hw else {}))
lighting_overrides(args), ram=RamLighting(self.hw), **(hw["lighting"] if hw else {}))
self.hw.chase = self.lighting.chase_clock # keeps the RAM chase in step with the others
self.ai = None
if not args.no_ai:
from kurgan.ai.service import AiService
@@ -270,15 +252,12 @@ class Kurgan:
# -- lifecycle
def _fan_row(self, t: float) -> tuple:
cpu, top = self.fans.cpu, self.fans.top
return (round(t, 1), self.fans.gpu.duty, None if cpu is None else cpu.duty, None if top is None else top.duty)
def _on_sample(self, sample) -> None:
p = sample.power
self.lighting.on_telemetry(sample.cpu.temp, sample.gpu.temp, p.total)
if self.fans is not None:
self.fan_history.append(self._fan_row(sample.t))
row = self.hw.cooling()["row"] # (t, gpu duty, cpu duty, top duty), from the service's last pass
if row and (not self.fan_history or row[0] > self.fan_history[-1][0]):
self.fan_history.append(tuple(row))
if self.tray is not None:
fmt = lambda v: "--" if v is None else f"{v:.0f}"
self.tray.set_tooltip(f"{APP_NAME}\nTotal {fmt(p.total)} W: CPU {fmt(p.cpu)}, "
@@ -292,9 +271,11 @@ class Kurgan:
def start(self, port: int, tray: bool) -> None:
from kurgan.web.server import WebServer
if self.hw_service is not None: # --demo
self._thread("hw-loop", self.hw_service.run, self.stop)
self._threads.append(self.hw_service.start_lighting(self.stop))
self._thread("hw-client", self.hw.run, self.stop)
self._thread("telemetry", self.telemetry.run, self.stop)
if self.fans is not None:
self._thread("case-fans", self.fans.run, self.stop)
self.lighting.start(self.stop)
if self.display is not None:
self._thread("display", self.display.run, self.stop)
@@ -319,7 +300,7 @@ class Kurgan:
if self.tray is None:
continue # no icon, no balloons -- and no baseline burnt before the icon exists
try:
states = alert_states(self.fans, self.ai, self.telemetry)
states = alert_states(self.hw.cooling(), self.ai, self.telemetry)
except Exception:
log.exception("Alert check failed")
continue
@@ -371,7 +352,6 @@ class Kurgan:
if self.recorder is not None:
self.recorder.close() # after the telemetry thread has stopped writing
self.lighting.join()
self.system.fans.close()
# -- the web UI's API
@@ -395,10 +375,8 @@ class Kurgan:
"pid": os.getpid(), "token": me},
"telemetry": self.telemetry.snapshot(),
"display": self.display.snapshot() if self.display else {"status": "Off (--no-lcd)", "connected": False},
"cooling": ({**self.fans.snapshot(), "note": None, "row": self.fan_history[-1] if self.fan_history else None}
if self.fans is not None
else {"profile": self.settings.get("cooling", "profile"), "groups": [], "top": None,
"note": self.fan_note, "row": None}),
"hardware": self.hw.snapshot(),
"cooling": self.hw.cooling(),
"lighting": self.lighting.snapshot(),
"ai": self.ai.snapshot() if self.ai else None,
}
@@ -418,13 +396,8 @@ class Kurgan:
self.lighting.set_mode(zone, mode)
def set_fan_profile(self, key: str) -> None:
from kurgan.cooling.profiles import PROFILES
if key not in PROFILES:
raise ValueError(f"Unknown fan profile {key!r}")
self.settings.update("cooling", profile=key)
if self.fans is not None:
self.fans.apply_profile(PROFILES[key])
"""The hardware service applies and saves it; ValueError or HardwareUnavailable."""
self.hw.set_profile(key)
def set_ai(self, backend: str | None, variant: str | None) -> None:
if self.ai is None:
@@ -439,15 +412,20 @@ class Kurgan:
# -- tray
def tray_lines(self) -> list[str]:
from kurgan.cooling.profiles import PROFILES
lines = []
if self.display is not None:
lines.append(self.display.status)
if self.fans is not None:
profile = self.fans.profile.name
groups = ", ".join(f"{g.name} {g.duty}%" for g in self.fans.groups)
top = f", top {self.fans.top.duty}%" if self.fans.top is not None else ""
cooling = self.hw.cooling()
if cooling["groups"]:
profile = PROFILES[cooling["profile"]].name if cooling["profile"] in PROFILES else cooling["profile"]
groups = ", ".join(f"{g['name']} {g['duty']}%" for g in cooling["groups"])
top = f", top {cooling['top']['duty']}%" if cooling["top"] is not None else ""
lines.append(f"Fans: {profile} ({groups}{top})")
elif self.fan_note:
elif self.hw.error is not None:
lines.append("Fans: hardware service unavailable")
else:
lines.append("Fans: not controlled")
modes = {z["key"]: z["mode"] for z in self.lighting.snapshot()["zones"]}
lines.append(f"Lighting: case fans {modes['case_fans']}, RAM {modes['memory']}, GPU {modes['gpu']}")
@@ -470,14 +448,21 @@ def main(argv: list[str] | None = None) -> int:
if args.preview:
from kurgan.display.renderer import DashboardRenderer
from kurgan.hw.client import CommanderReadings, CpuPackage, HardwareClient
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.telemetry.service import Telemetry
from kurgan.theme import Theme
from kurgan.telemetry.service import Telemetry
telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower())
hw = HardwareClient()
hw.poll()
telemetry = Telemetry(CpuSensors(package=CpuPackage(hw)), GpuSensors(load_source=args.gpu_load),
SystemPower(fans=CommanderReadings(hw)), hw=hw)
telemetry.read()
time.sleep(1.0) # let counters and the energy meter accumulate
hw.poll()
sample = telemetry.read()
if hw.error is not None:
log.warning("Hardware service unavailable, so no CPU temperature or fan power: %s", hw.error)
theme = Theme(accent=_parse_color(args.accent), psu_watts=max(100.0, args.psu_watts))
DashboardRenderer(theme, rotate180=args.rotate180).render(sample.cpu, sample.gpu, sample.power).save(
args.preview)
+27 -9
View File
@@ -1,8 +1,9 @@
"""Simulated sensors and devices for `python -m kurgan --demo`.
Lets the web UI and the AI swapping be worked on while the real Kurgan owns the hardware:
nothing here touches USB, PawnIO, the SMBus or NVAPI. Run it with its own data folder and
web port, e.g.
nothing here touches USB, PawnIO, the SMBus or NVAPI. The hardware service runs in-process on
these fakes (hardware_service), and the app talks to it through the same client and protocol
as to the real one, just without the pipe. Run it with its own data folder and web port, e.g.
$env:KURGAN_DATA_DIR = "$env:TEMP\\kurgan-demo"; python -m kurgan --demo --port 18080 --no-tray
"""
@@ -65,8 +66,8 @@ class FakeCommander:
class FakeSystem:
def __init__(self):
self.fans = FakeCommander()
def __init__(self, fans=None):
self.fans = fans if fans is not None else FakeCommander() # the app passes the service's RPMs
def read(self, cpu: Readings, gpu: Readings) -> PowerReadings:
parts = {"Motherboard & chipset": 15.0, "Memory (4 modules)": 10 + 0.1 * (cpu.load or 0),
@@ -139,8 +140,25 @@ class FakeLights:
def hardware() -> dict:
return {
"cpu": FakeCpu(), "gpu": FakeGpu(), "system": FakeSystem(), "board": FakeBoard,
"fan_sensors": (FakeGpu, FakeCpuTemperature),
"lighting": {"rgb": FakeLights("case fans"), "memory": FakeLights("RAM"), "gpu": FakeLights("GPU")},
}
"""The app's own devices."""
return {"cpu": FakeCpu(), "gpu": FakeGpu(),
"lighting": {"rgb": FakeLights("case fans"), "gpu": FakeLights("GPU")}}
# The demo's hardware service has its fans set up: GPU side on ports 4-6, CPU side on 1-3, top 2 and 5.
DEMO_COOLING = {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]}
def hardware_service(settings_path: str):
"""A kurgan.hw.service.HardwareService on the fakes, with its settings in settings_path."""
from kurgan.hw import settings as hw_settings
from kurgan.hw.service import HardwareService
from kurgan.settings import Settings, SettingsError
try:
settings, error = Settings(settings_path, None, seed={"cooling": DEMO_COOLING},
validator=hw_settings.validate), None
except (OSError, SettingsError) as e:
settings, error = None, str(e)
return HardwareService(settings, error, commander=FakeCommander(), board_factory=FakeBoard,
gpu_factory=FakeGpu, cpu=FakeCpuTemperature(), memory=FakeLights("RAM"))
+301
View File
@@ -0,0 +1,301 @@
"""The app's side of the hardware service: a client that keeps reconnecting.
A background thread asks the service for its state once a second (and sends the app's chase
clock for the RAM lighting); the web UI's profile and RAM lighting changes are sent at once.
While the service can't be reached, every reading from it is None or empty, `error` says why,
and the changes raise HardwareUnavailable (the web API answers 503).
The service itself never depends on the app: it controls the fans whether or not anything is
connected. The app only shows what the service reports and asks it for changes.
client = HardwareClient(PipeTransport) the real service, over \\\\.\\pipe\\kurgan-hw
client = HardwareClient(lambda: LocalTransport(service.dispatch, version)) --demo, tests
"""
from __future__ import annotations
import itertools
import logging
import threading
import time
from typing import Callable
from kurgan import APP_NAME, __version__
from kurgan.cooling.profiles import PROFILES
from kurgan.hw import protocol
from kurgan.hw.protocol import PIPE_NAME, PROTOCOL_VERSION, ProtocolError, RemoteError, Unavailable
log = logging.getLogger(__name__)
POLL_SECONDS = 1.0
CALL_SECONDS = 2.0 # how long one request may take
STALE_SECONDS = 5.0 # no state received for this long: the service is unreachable
STALL_SECONDS = 15.0 # the service's own state this old: its loop is stuck (it waits 5 s after an error)
BUSY_SECONDS = 5.0 # how long a change waits for the connection
SERVICE_NAME = "hardware service" # the telemetry health source
class HardwareUnavailable(Unavailable):
"""The hardware service can't be reached, or can't do that right now."""
class PipeTransport:
"""One connection to the service's pipe, speaking the protocol."""
def __init__(self, name: str = PIPE_NAME, timeout: float = CALL_SECONDS, **pipe_options):
from kurgan.hw.pipe import PipeClient
self._pipe = PipeClient(name, timeout, **pipe_options) # checks the pipe's owner by default
self._ids = itertools.count(1)
def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS):
request_id = next(self._ids)
line = self._pipe.request(protocol.encode_request(op, args, request_id), timeout)
return protocol.decode_reply(line, request_id)
def close(self) -> None:
self._pipe.close()
class LocalTransport:
"""The same conversation, encoded and checked the same way, without a pipe: --demo and tests."""
def __init__(self, dispatch: Callable[[str, dict], object], service_version: str = __version__):
self._session = protocol.Session(dispatch, service_version)
self._ids = itertools.count(1)
self.closed = False
def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS):
if self.closed:
raise OSError("connection closed")
request_id = next(self._ids)
reply, close = self._session.handle(protocol.encode_request(op, args, request_id).rstrip(b"\n"))
if close:
self.closed = True
return protocol.decode_reply(reply.rstrip(b"\n"), request_id)
def close(self) -> None:
self.closed = True
# Error replies that mean the two sides don't understand each other: drop the connection.
_MISMATCH = (protocol.VERSION, protocol.BAD_REQUEST, protocol.UNKNOWN_OP, protocol.HELLO_FIRST, protocol.TOO_LARGE)
class HardwareClient:
def __init__(self, connect: Callable[[], object] = PipeTransport, *, poll_seconds: float = POLL_SECONDS,
chase: Callable[[], dict | None] | None = None):
"""connect() opens a transport (OSError if it can't). chase() gives the ram_chase
arguments to send with each poll, or None."""
self._connect = connect
self.poll_seconds = poll_seconds
self.chase = chase
self._lock = threading.Lock() # one request at a time on the connection
self._transport = None
self._state: dict | None = None
self._state_at = 0.0 # time.monotonic() of the last state received
self._error: str | None = "not connected yet"
self.service: dict | None = None # the service's hello reply
self._last_profile: str | None = None
self._last_ram_mode: str | None = None
# -- the connection
def _drop(self) -> None:
if self._transport is not None:
try:
self._transport.close()
except Exception:
pass
self._transport = None
def _call(self, op: str, args: dict | None = None):
"""One request; the caller holds self._lock. HardwareUnavailable or ValueError."""
try:
if self._transport is None:
transport = self._connect()
try:
hello = transport.call("hello", {"protocol": PROTOCOL_VERSION,
"client": f"{APP_NAME} {__version__}"})
except BaseException:
transport.close()
raise
self._transport, self.service = transport, hello
log.info("Connected to the hardware service (version %s)", hello.get("service"))
return self._transport.call(op, args)
except RemoteError as e:
if e.code == protocol.INVALID:
raise ValueError(str(e)) from None
if e.code in _MISMATCH:
self._drop()
hint = "; re-run setup.ps1 so the app and the service match" if e.code in (
protocol.VERSION, protocol.UNKNOWN_OP) else ""
raise HardwareUnavailable(f"the hardware service refused the request ({e}){hint}") from None
raise HardwareUnavailable(str(e)) from None # UNAVAILABLE, INTERNAL: still connected
except ProtocolError as e:
self._drop()
raise HardwareUnavailable(f"bad reply from the hardware service: {e}") from None
except OSError as e:
self._drop()
raise HardwareUnavailable(str(e) or type(e).__name__) from None
def _store(self, state) -> None:
if not isinstance(state, dict):
raise HardwareUnavailable("bad state from the hardware service")
self._state, self._state_at = state, time.monotonic()
self._last_profile = (state.get("cooling") or {}).get("profile", self._last_profile)
self._last_ram_mode = ((state.get("lighting") or {}).get("memory") or {}).get("mode", self._last_ram_mode)
def _set_error(self, error: str | None) -> None:
if error != self._error:
if error is None:
log.info("Hardware service reachable")
else:
log.warning("Hardware service unavailable: %s", error)
self._error = error
def poll(self) -> None:
"""Fetch the state (and send the chase clock); never raises."""
try:
chase = self.chase() if self.chase is not None else None
except Exception:
log.exception("Chase clock failed")
chase = None
try:
with self._lock:
state = self._call("state")
if chase is not None:
self._call("ram_chase", chase)
self._store(state)
age = time.time() - state["t"] if isinstance(state.get("t"), (int, float)) else 0.0
self._set_error(None if age <= STALL_SECONDS else
f"the hardware service's loop has stalled (its state is {age:.0f} s old)")
except (HardwareUnavailable, ValueError) as e:
self._set_error(str(e))
except Exception as e:
log.exception("Hardware service poll failed")
self._set_error(f"{type(e).__name__}: {e}")
def run(self, stop: threading.Event) -> None:
while not stop.is_set():
self.poll()
stop.wait(self.poll_seconds)
with self._lock:
self._drop()
def _command(self, op: str, args: dict) -> None:
if not self._lock.acquire(timeout=BUSY_SECONDS):
raise HardwareUnavailable("the hardware service is busy; try again")
try:
state = self._call(op, args)
finally:
self._lock.release()
self._store(state)
# -- what the app reads
@property
def error(self) -> str | None:
"""Why the service's readings can't be used now, or None."""
if self._error is None and time.monotonic() - self._state_at > STALE_SECONDS:
return "no state from the hardware service"
return self._error
@property
def state(self) -> dict | None:
"""The service's latest state while it's fresh, else None."""
return self._state if self.error is None else None
def snapshot(self) -> dict:
"""For the web UI's state."""
state = self.state
service = (state or {}).get("service") or {}
return {"available": state is not None, "error": self.error,
"version": service.get("version"), "pid": service.get("pid"), "uptime": service.get("uptime"),
"settings_error": service.get("settings_error")}
def cooling(self) -> dict:
"""The service's fan state, as the web UI shows it."""
state = self.state
if state is not None:
return state["cooling"]
return {"profile": self._last_profile, "groups": [], "top": None, "row": None,
"note": (f"Hardware service unavailable: {self.error}. The service controls the fans, "
"not this app: no fan readings or changes until it's back.")}
def cpu(self) -> dict:
state = self.state
if state is None:
return {"temp": None, "power": None, "error": f"hardware service unavailable: {self.error}"}
return state["cpu"]
def fan_rpms(self) -> list[int]:
state = self.state
return list(state["commander"]["rpms"]) if state is not None else []
def ram_lighting(self) -> dict:
state = self.state
if state is not None:
return state["lighting"]["memory"]
return {"mode": self._last_ram_mode, "status": f"Hardware service unavailable: {self.error}"}
# -- what the app changes
def set_profile(self, key: str) -> None:
if key not in PROFILES:
raise ValueError(f"Unknown fan profile {key!r}")
self._command("set_profile", {"profile": key})
def set_ram_lighting(self, mode: str) -> None:
self._command("set_ram_lighting", {"mode": mode})
class CpuPackage:
"""The CPU package temperature and power, read by the service (PawnIO needs it elevated);
stands in for kurgan.telemetry.sensors.IntelPackage in the app's CpuSensors."""
def __init__(self, client: HardwareClient):
self.client = client
def read(self) -> tuple[float | None, float | None]:
cpu = self.client.cpu()
return cpu.get("temp"), cpu.get("power")
@property
def status(self) -> str:
cpu = self.client.cpu()
return "ok" if cpu.get("temp") is not None else (cpu.get("error") or "no reading")
class CommanderReadings:
"""The Commander PRO's fan RPMs, read by the service; stands in for CommanderPro in the
app's power model (SystemPower)."""
controlled = True
def __init__(self, client: HardwareClient):
self.client = client
def read(self) -> list[int]:
return self.client.fan_rpms()
def close(self) -> None:
pass
class RamLighting:
"""The RAM lighting zone, driven by the service; the lighting service's memory zone."""
def __init__(self, client: HardwareClient):
self.client = client
@property
def mode(self) -> str | None:
return self.client.ram_lighting()["mode"]
@property
def status(self) -> str:
return self.client.ram_lighting()["status"]
def set_mode(self, mode: str) -> None:
self.client.set_ram_lighting(mode)
+38 -24
View File
@@ -1,21 +1,26 @@
"""Lighting service: one worker per device, one mode per zone, saved in settings.json.
"""Lighting service: one worker per device, one mode per zone.
Zones and their modes (see kurgan.settings.LIGHTING_MODES):
case_fans Lighting Node CORE QL120 LEDs: off (hardware effect), temperature, chase
memory Dominator DDR5: off (held dark while running), temperature, chase
gpu ASUS RTX 4090 LED row: off (its own effect), chase
The three chases share one power-paced clock, so they stay in step.
The case fan and GPU zones run here and are saved in settings.json. The RAM is on the SMBus,
which needs PawnIO and so admin rights: the hardware service drives it and keeps its mode in
hw-settings.json; this service only shows it and asks for changes (kurgan.hw.client.RamLighting).
The three chases share one power-paced clock, so they stay in step: the RAM's in the hardware
service is kept in step by sending it this clock once a second (chase_clock).
"""
from __future__ import annotations
import logging
import threading
import time
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting
from kurgan.lighting.gpu import GpuLighting
from kurgan.lighting.memory import MemoryLighting
from kurgan.settings import LIGHTING_MODES, Settings
from kurgan.theme import Theme
@@ -23,19 +28,22 @@ log = logging.getLogger(__name__)
ZONE_LABELS = {"case_fans": "Case fan LEDs", "memory": "RAM", "gpu": "GPU"}
MODE_LABELS = {"off": "Off", "temperature": "Temperature", "chase": "Red side chase"}
REMOTE_ZONES = ("memory",) # driven by the hardware service
LOCAL_ZONES = tuple(zone for zone in LIGHTING_MODES if zone not in REMOTE_ZONES)
class LightingService:
def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float],
overrides: dict[str, str] | None = None, *, rgb=None, memory=None, gpu=None):
overrides: dict[str, str] | None = None, *, ram, rgb=None, gpu=None):
"""chase: (idle s/LED, full-power s/LED, idle watts, full watts).
overrides: modes for this run only (CLI flags), not saved."""
overrides: case fan and GPU modes for this run only (CLI flags), not saved.
ram: the RAM zone in the hardware service (mode, status, set_mode)."""
self._settings = settings
self._lock = threading.Lock()
self._events = {zone: {mode: threading.Event() for mode in modes if mode != "off"}
for zone, modes in LIGHTING_MODES.items()}
self._events = {zone: {mode: threading.Event() for mode in LIGHTING_MODES[zone] if mode != "off"}
for zone in LOCAL_ZONES}
self._overridden = set(overrides or ())
modes = settings.section("lighting")
modes = {zone: mode for zone, mode in settings.section("lighting").items() if zone in LOCAL_ZONES}
modes.update(overrides or {})
self._modes: dict[str, str] = {}
for zone, mode in modes.items():
@@ -44,8 +52,8 @@ class LightingService:
self.timing = ChaseTiming(step, fast, (idle_w, full_w))
self.timing.reset(SIDE_CHASE_BOTTOM_STEP)
self.rgb = rgb or RGBLighting(theme, step, fast, (idle_w, full_w), chase_timing=self.timing)
self.memory = memory or MemoryLighting(theme, chase_timing=self.timing)
self.gpu = gpu or GpuLighting(self.timing)
self.ram = ram
self._threads: list[threading.Thread] = []
self._power: float | None = None
@@ -63,7 +71,6 @@ class LightingService:
e = self._events
for name, target, args in (
("case-fan-lighting", self.rgb.run, (stop, e["case_fans"]["temperature"], e["case_fans"]["chase"])),
("memory-lighting", self.memory.run, (stop, e["memory"]["temperature"], e["memory"]["chase"])),
("gpu-lighting", self.gpu.run, (stop, e["gpu"]["chase"]))):
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
thread.start()
@@ -76,33 +83,40 @@ class LightingService:
def on_telemetry(self, cpu_temp: float | None, gpu_temp: float | None, total_watts: float | None) -> None:
self._power = total_watts
self.rgb.set_temperature(cpu_temp, gpu_temp)
self.rgb.set_power(total_watts)
self.memory.set_temperature(cpu_temp, gpu_temp)
self.memory.set_power(total_watts)
self.rgb.set_power(total_watts) # sets the shared clock's pace
def mode(self, zone: str) -> str:
return self._modes[zone]
def chase_clock(self) -> dict:
"""The shared chase clock now, as the hardware service's ram_chase takes it."""
phase, rate = self.timing.sample(time.monotonic())
return {"phase": phase, "rate": rate, "power": self._power}
def mode(self, zone: str) -> str | None:
return self.ram.mode if zone in REMOTE_ZONES else self._modes[zone]
def set_mode(self, zone: str, mode: str) -> None:
"""Save first, then switch, so a failed save leaves the lighting as it was."""
if zone not in LIGHTING_MODES or mode not in LIGHTING_MODES[zone]:
raise ValueError(f"Unknown lighting {zone!r} mode {mode!r}")
with self._lock:
self._settings.update("lighting", **{zone: mode})
self._overridden.discard(zone)
self._apply(zone, mode)
if zone in REMOTE_ZONES:
self.ram.set_mode(mode) # the hardware service saves it
else:
with self._lock:
self._settings.update("lighting", **{zone: mode})
self._overridden.discard(zone)
self._apply(zone, mode)
log.info("%s lighting: %s", ZONE_LABELS[zone], mode)
def statuses(self) -> dict[str, str]:
return {"case_fans": self.rgb.status, "memory": self.memory.status, "gpu": self.gpu.status}
return {"case_fans": self.rgb.status, "memory": self.ram.status, "gpu": self.gpu.status}
def snapshot(self) -> dict:
statuses = self.statuses()
modes = {**self._modes, "memory": self.ram.mode}
# The eased rate once a chase is running; the target rate for the current power until then.
rate = self.timing.rate or self.timing.rate_for(self._power)
chasing = "chase" in self._modes.values()
chasing = "chase" in modes.values()
return {"chase_ms_per_led": round(1000 / rate) if chasing else None,
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": self._modes[zone],
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in modes],
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": modes[zone],
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in zone_modes],
"status": statuses[zone], "this_run_only": zone in self._overridden}
for zone, modes in LIGHTING_MODES.items()]}
for zone, zone_modes in LIGHTING_MODES.items()]}
+26 -18
View File
@@ -3,16 +3,18 @@
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
{
"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5],
"profile": "balanced"},
"lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"},
"lighting": {"case_fans": "chase", "gpu": "off"},
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
"web": {"port": 8080}
}
The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the
rest by the web UI. An invalid file stops The Kurgan from starting rather than silently
dropping fan control. On first start the TT LCD Dashboard's settings are imported.
The web UI writes it. An invalid file stops The Kurgan from starting rather than silently
dropping a setting. On first start the TT LCD Dashboard's settings are imported.
The fans and the RAM lighting belong to the hardware service, in hw-settings.json (see
kurgan.hw.settings). Files from before the privilege split may still hold a `cooling` section
and `lighting.memory`: they're checked as before and kept, but nothing here uses them, and
setup.ps1 moves them to hw-settings.json (kurgan.hw.migrate).
"""
from __future__ import annotations
@@ -38,20 +40,22 @@ LIGHTING_MODES = {
DEFAULT_WEB_PORT = 8080
DEFAULTS = {
"cooling": {"profile": DEFAULT_PROFILE},
"lighting": {zone: "off" for zone in LIGHTING_MODES},
"lighting": {"case_fans": "off", "gpu": "off"},
"ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL,
"idle_stop_minutes": ai_config.IDLE_STOP_MINUTES},
"web": {"port": DEFAULT_WEB_PORT},
}
_OPTIONAL = {
"cooling": {"gpu_ports", "cpu_ports", "top_channels"},
"lighting": set(),
"lighting": {"memory"}, # legacy: the hardware service's now
"ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"},
"web": set(),
}
# Sections only files from before the privilege split have: allowed keys (see the docstring).
LEGACY_SECTIONS = {"cooling": {"profile", "gpu_ports", "cpu_ports", "top_channels"}}
class SettingsError(ValueError):
pass
@@ -101,21 +105,24 @@ def validate(data: object) -> dict:
"""Return a normalised copy with defaults filled in, or raise SettingsError."""
if not isinstance(data, dict):
raise SettingsError("settings must be a JSON object")
unknown = set(data) - set(DEFAULTS)
unknown = set(data) - set(DEFAULTS) - set(LEGACY_SECTIONS)
if unknown:
raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}")
out = copy.deepcopy(DEFAULTS)
for section, values in data.items():
if not isinstance(values, dict):
raise SettingsError(f"{section} must be an object")
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
allowed = LEGACY_SECTIONS[section] if section in LEGACY_SECTIONS else (
set(DEFAULTS[section]) | _OPTIONAL[section])
bad = set(values) - allowed
if bad:
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
out[section].update(values)
out.setdefault(section, {}).update(values)
validate_cooling(out["cooling"])
if "cooling" in out:
out["cooling"] = validate_cooling({"profile": DEFAULT_PROFILE, **out["cooling"]})
for zone, modes in LIGHTING_MODES.items():
if out["lighting"][zone] not in modes:
if zone in out["lighting"] and out["lighting"][zone] not in modes:
raise SettingsError(f"lighting.{zone} must be one of {', '.join(modes)}")
ai = out["ai"]
@@ -209,18 +216,19 @@ class Settings:
log.info("Created %s%s", path, " from the TT LCD Dashboard's settings" if raw else "")
def section(self, name: str) -> dict:
"""A copy of the section ({} for an optional one the file doesn't have)."""
with self._lock:
return copy.deepcopy(self._data[name])
return copy.deepcopy(self._data.get(name, {}))
def get(self, section: str, key: str, default=None):
with self._lock:
return copy.deepcopy(self._data[section].get(key, default))
return copy.deepcopy(self._data.get(section, {}).get(key, default))
def update(self, section: str, **changes) -> None:
"""Validate and save; on any error nothing changes, in memory or on disk."""
with self._lock:
data = copy.deepcopy(self._data)
data[section].update(changes)
data.setdefault(section, {}).update(changes)
data = self._validate(data)
write_json_atomic(self.path, data)
self._data = data
+15 -5
View File
@@ -302,7 +302,9 @@ class CpuSensors:
# it, or a broken driver costs a heavy CreateFile+DeviceIoControl every second.
RETRY_SECONDS = 15.0
def __init__(self):
def __init__(self, package=None):
"""package: where the temperature and power come from instead of PawnIO, e.g. the
hardware service (kurgan.hw.client.CpuPackage): read() -> (temp, power), and status."""
base = r"\Processor Information(_Total)"
self.pdh = PerfCounters({
"utility": base + r"\% Processor Utility",
@@ -310,13 +312,14 @@ class CpuSensors:
"perf": base + r"\% Processor Performance",
"freq": base + r"\Processor Frequency",
})
self.package = package
self.pkg: IntelPackage | None = None
self._pkg_error: str | None = None
self._next_pkg_attempt = 0.0
self._try_pkg()
def _try_pkg(self) -> None:
if self.pkg or time.monotonic() < self._next_pkg_attempt:
if self.package is not None or self.pkg or time.monotonic() < self._next_pkg_attempt:
return
try:
self.pkg = IntelPackage()
@@ -329,6 +332,9 @@ class CpuSensors:
@property
def status(self) -> str:
"""Of the temperature and power reading: "ok", or why not."""
if self.package is not None:
return self.package.status
return "ok" if self.pkg else (self._pkg_error or "not started")
def read(self) -> Readings:
@@ -343,7 +349,9 @@ class CpuSensors:
clock = s["freq"] * s["perf"] / 100.0
temp = power = None
self._try_pkg()
if self.pkg:
if self.package is not None:
temp, power = self.package.read()
elif self.pkg:
try:
temp = self.pkg.temperature()
power = self.pkg.power()
@@ -872,10 +880,12 @@ class StoragePower:
class SystemPower:
"""Everything that isn't the CPU package or the graphics card, in watts."""
def __init__(self, model: PowerModel | None = None):
def __init__(self, model: PowerModel | None = None, fans=None):
"""fans: where the case fan RPMs come from (read() -> list), e.g. the hardware service
(kurgan.hw.client.CommanderReadings); default: the Commander PRO itself."""
self.model = model or PowerModel()
self.dimms = memory_modules()
self.fans = CommanderPro()
self.fans = fans if fans is not None else CommanderPro()
try:
self.storage: StoragePower | None = StoragePower(self.model)
except OSError as e:
+12 -5
View File
@@ -1,8 +1,9 @@
"""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.)
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
@@ -20,6 +21,7 @@ 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")
@@ -43,8 +45,10 @@ def _r(value: float | None, digits: int = 1) -> float | None:
class Telemetry:
def __init__(self, cpu, gpu, system, interval: float = 1.0):
self.cpu, self.gpu, self.system = cpu, gpu, system
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
@@ -61,8 +65,11 @@ class Telemetry:
"""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 else "no CPU temperature (MSR reader unavailable)")
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)
+10 -5
View File
@@ -12,11 +12,12 @@
* /strata/... /llama/... the LLM servers, started on demand (kurgan/web/proxy.py)
The process runs elevated and controls fans, so requests are guarded: the Host header must
name this server (blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header,
which a page on another site can't send without a CORS preflight that this server never
answers. There is no other authentication: anything already running on this PC as you can
use the API.
The fan profile and the RAM lighting are passed on to the hardware service, which answers
503 here while it can't be reached. Requests are guarded: the Host header must name this server
(blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header, which a page on
another site can't send without a CORS preflight that this server never answers. There is no
other authentication: anything already running on this PC as you can use the API (as it could
use the hardware service's pipe directly).
"""
from __future__ import annotations
@@ -29,6 +30,7 @@ import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from kurgan.hw.protocol import Unavailable
from kurgan.web import proxy
log = logging.getLogger(__name__)
@@ -189,6 +191,9 @@ def make_handler(app, port: int):
except (ApiError, ValueError) as e:
status = e.status if isinstance(e, ApiError) else 400
self._json(status, {"error": str(e)})
except Unavailable as e: # the hardware service: unreachable, or can't do it now
log.warning("POST %s: %s", self.path, e)
self._json(503, {"error": f"Hardware service unavailable: {e}"})
except OSError as e:
log.warning("POST %s failed: %s", self.path, e)
self._json(500, {"error": f"Couldn't save the setting: {e}"})
+11 -4
View File
@@ -501,13 +501,20 @@ function renderHeader(s) {
const power = s.telemetry.power;
setText("hero-total", (power?.partial ? "≈" : "") + fmt.n0(power?.total));
const meta = $("meta");
const elevated = s.app.token?.elevated;
const health = Object.entries(s.telemetry.health ?? {});
const hw = s.hardware ?? {};
const health = Object.entries(s.telemetry.health ?? {}).filter(([name]) => name !== "hardware service");
meta.replaceChildren(
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
hw.available
? el("span", { class: "pill", title: `The Kurgan hardware ${hw.version ?? ""} · pid ${hw.pid ?? "?"} · up ${fmt.dur(hw.uptime)}\nFans, CPU temperature and power, RAM lighting` },
el("span", { class: `dot ${hw.settings_error ? "warning" : "good"}` }), "Hardware service")
: el("span", { class: "pill", title: hw.error ?? "" },
el("span", { class: "dot critical" }), "Hardware service unavailable"),
...(s.app.token?.elevated
? [el("span", { class: "pill", title: "The app should run without admin rights; only the hardware service needs them" },
el("span", { class: "dot warning" }), "Running elevated")]
: []),
...(health.length
? [el("span", { class: "pill", title: health.map(([name, h]) => `${name}: ${h.error}`).join("\n") },
el("span", { class: "dot warning" }),
+14 -12
View File
@@ -5,16 +5,10 @@ from kurgan import tray
from kurgan.app import ALERT_REPEAT_SECONDS, alert_states, balloon, due_alerts, new_alerts
def fake_fans(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
group = Mock()
group.name = "GPU"
group.status = gpu_status
top = Mock()
top.status = top_status
fans = Mock()
fans.groups = [group]
fans.top = top
return fans
def fake_cooling(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
"""The hardware service's fan state, as HardwareClient.cooling() returns it."""
return {"profile": "balanced", "groups": [{"name": "GPU", "duty": 40, "status": gpu_status}],
"top": {"duty": 45, "status": top_status}, "note": None, "row": None}
def fake_ai(*errors):
@@ -32,12 +26,12 @@ def fake_health(entries=None):
class AlertStatesTest(unittest.TestCase):
def test_healthy_everything_is_quiet(self):
self.assertEqual(alert_states(fake_fans(), fake_ai(("strata", None), ("llama", None)),
self.assertEqual(alert_states(fake_cooling(), fake_ai(("strata", None), ("llama", None)),
fake_health()), {})
def test_failsafes_errors_and_failing_sources_are_collected(self):
states = alert_states(
fake_fans(gpu_status="FAILSAFE 100%: GPU temperature unavailable",
fake_cooling(gpu_status="FAILSAFE 100%: GPU temperature unavailable",
top_status="UNAVAILABLE (lost); BIOS curve keeps control"),
fake_ai(("strata", "exited (code 3); restarting."), ("llama", None)),
fake_health({"GPU sensors": {"error": "NVMLError: uninitialised", "age_s": 3.0}}))
@@ -50,6 +44,14 @@ class AlertStatesTest(unittest.TestCase):
def test_fans_or_ai_being_off_is_not_an_error(self):
self.assertEqual(alert_states(None, None, fake_health()), {})
not_set_up = {"profile": "balanced", "groups": [], "top": None, "note": "Fan control isn't set up", "row": None}
self.assertEqual(alert_states(not_set_up, None, fake_health()), {})
def test_the_hardware_service_being_unavailable_is_one_alert_of_its_own(self):
states = alert_states({"profile": None, "groups": [], "top": None, "note": "unavailable", "row": None}, None,
fake_health({"hardware service": {"error": "the hardware service isn't running (no pipe)",
"age_s": 0.0}}))
self.assertEqual(states, {"hw": "Hardware service unavailable: the hardware service isn't running (no pipe)"})
class NewAlertsTest(unittest.TestCase):
+212
View File
@@ -0,0 +1,212 @@
import json
import os
import tempfile
import threading
import time
import unittest
from kurgan import demo
from kurgan.hw import client as hw_client
from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, HardwareUnavailable, LocalTransport,
PipeTransport, RamLighting)
from kurgan.hw.pipe import PipeError, PipeServer, current_user_sid, pipe_sddl
from kurgan.hw.protocol import VERSION, RemoteError, Session
from kurgan.telemetry.sensors import CpuSensors, SystemPower
from kurgan.telemetry.service import SERVICE_SOURCE, Telemetry
class Service:
"""The demo's hardware service (the real HardwareService on fakes) and a client to it."""
def __init__(self, test: unittest.TestCase):
directory = tempfile.TemporaryDirectory()
test.addCleanup(directory.cleanup)
self.path = os.path.join(directory.name, "hw-settings.json")
self.service = demo.hardware_service(self.path)
self.service.tick(time.monotonic())
self.connects = 0
self.down = False # the next connects fail, as with no pipe
self.transport: LocalTransport | None = None
def connect(self):
self.connects += 1
if self.down:
raise PipeError("the hardware service isn't running (no pipe)", 2)
self.transport = LocalTransport(self.service.dispatch)
return self.transport
def saved(self) -> dict:
with open(self.path, encoding="utf-8") as stream:
return json.load(stream)
class ClientTest(unittest.TestCase):
def setUp(self):
self.hw = Service(self)
self.client = HardwareClient(self.hw.connect)
def test_reads_the_services_state(self):
self.client.poll()
self.assertIsNone(self.client.error)
cooling = self.client.cooling()
self.assertEqual([g["name"] for g in cooling["groups"]], ["GPU", "CPU"])
self.assertEqual(cooling["profile"], "balanced")
self.assertEqual(len(cooling["row"]), 4)
self.assertIsNotNone(self.client.cpu()["temp"])
self.assertEqual(len(self.client.fan_rpms()), 6)
self.assertEqual(self.client.ram_lighting()["mode"], "off")
snapshot = self.client.snapshot()
self.assertTrue(snapshot["available"])
self.assertEqual(snapshot["pid"], os.getpid())
def test_changes_go_to_the_service_and_are_saved_there(self):
self.client.poll()
self.client.set_profile("quiet")
self.assertEqual(self.client.cooling()["profile"], "quiet") # the reply's state, no poll needed
self.client.set_ram_lighting("chase")
self.assertEqual(RamLighting(self.client).mode, "chase")
self.assertEqual(self.hw.saved()["cooling"]["profile"], "quiet")
self.assertEqual(self.hw.saved()["lighting"]["memory"], "chase")
def test_bad_values_are_value_errors_and_nothing_is_sent(self):
self.client.poll()
for call, value in ((self.client.set_profile, "turbo"), (self.client.set_ram_lighting, "rainbow")):
with self.subTest(value=value), self.assertRaises(ValueError):
call(value)
self.assertEqual(self.hw.saved()["cooling"]["profile"], "balanced")
def test_without_a_service_everything_reads_empty_and_changes_raise(self):
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("isn't running", self.client.error)
self.assertIsNone(self.client.state)
cooling = self.client.cooling()
self.assertEqual((cooling["groups"], cooling["top"], cooling["row"]), ([], None, None))
self.assertIn("Hardware service unavailable", cooling["note"])
self.assertEqual(self.client.fan_rpms(), [])
self.assertEqual(CpuPackage(self.client).read(), (None, None))
self.assertIn("unavailable", CpuPackage(self.client).status)
self.assertIn("unavailable", RamLighting(self.client).status)
self.assertFalse(self.client.snapshot()["available"])
with self.assertRaises(HardwareUnavailable):
self.client.set_profile("quiet")
def test_reconnects_and_greets_again_after_the_service_restarts(self):
self.client.poll()
self.client.set_profile("quiet")
self.hw.transport.close() # the service went away mid-connection
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIsNotNone(self.client.error)
self.assertEqual(self.client.cooling()["profile"], "quiet") # the last one known, for the buttons
self.hw.down = False
with self.assertLogs("kurgan.hw.client", level="INFO"):
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 2) # the failed poll found the old connection broken
self.assertTrue(self.hw.transport._session.greeted)
def test_a_different_protocol_drops_the_connection_and_says_what_to_do(self):
class Old:
closed = False
def call(self, op, args=None, timeout=None):
raise RemoteError(VERSION, "the service speaks protocol 2, the client 1")
def close(self):
self.closed = True
old = Old()
client = HardwareClient(lambda: old)
with self.assertLogs("kurgan.hw.client", level="WARNING"):
client.poll()
self.assertIn("re-run setup.ps1", client.error)
self.assertTrue(old.closed)
def test_a_refusal_by_a_service_that_is_up_keeps_the_connection(self):
self.client.poll()
self.hw.service.settings = None # hw-settings.json turned out invalid
self.hw.service.settings_error = "cooling.profile must be one of ..."
with self.assertRaises(HardwareUnavailable) as raised:
self.client.set_profile("quiet")
self.assertIn("hw-settings.json is invalid", str(raised.exception))
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 1)
def test_a_stuck_service_loop_counts_as_unavailable(self):
self.client.poll()
self.hw.service._snapshot["t"] = time.time() - 60 # the loop stopped publishing a minute ago
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("stalled", self.client.error)
self.assertIsNone(self.client.state)
def test_an_old_state_is_no_state(self):
self.client.poll()
self.client._state_at -= hw_client.STALE_SECONDS + 1 # no poll got through since
self.assertEqual(self.client.error, "no state from the hardware service")
self.assertEqual(self.client.fan_rpms(), [])
def test_each_poll_sends_the_chase_clock(self):
self.client.chase = lambda: {"phase": 123.0, "rate": 9.0, "power": 400.0}
self.client.poll()
chase = self.hw.service.chase
self.assertEqual((chase.phase, chase.rate), (123.0, 9.0))
def test_the_app_side_readers_take_the_services_values(self):
self.client.poll()
state = self.client.state
self.assertEqual(CommanderReadings(self.client).read(), state["commander"]["rpms"])
cpu = CpuSensors(package=CpuPackage(self.client))
self.assertEqual(cpu.read().temp, state["cpu"]["temp"])
self.assertEqual(cpu.status, "ok")
def test_telemetry_lists_the_service_once_not_also_the_cpu_temperature(self):
self.hw.down = True
cpu = CpuSensors(package=CpuPackage(self.client))
fake = demo.FakeGpu()
telemetry = Telemetry(cpu, fake, SystemPower(fans=CommanderReadings(self.client)), hw=self.client)
with self.assertLogs("kurgan", level="WARNING"):
for _ in range(3):
self.client.poll()
sample = telemetry.read()
self.assertIsNone(sample.cpu.temp)
self.assertEqual(list(telemetry.health()), [SERVICE_SOURCE])
self.hw.down = False
with self.assertLogs("kurgan", level="INFO"):
self.client.poll()
telemetry.read()
self.assertEqual(telemetry.health(), {})
class PipeEndToEndTest(unittest.TestCase):
def test_the_client_over_a_real_pipe(self):
me = current_user_sid()
hw = Service(self)
name = rf"\\.\pipe\kurgan-hw-client-test-{os.getpid()}"
server = PipeServer(name, pipe_sddl(me, server_sid=me), lambda: Session(hw.service.dispatch, "test"))
server.start()
self.addCleanup(server.close)
client = HardwareClient(lambda: PipeTransport(name, trusted_owners=None))
deadline = time.monotonic() + 2
while True: # the listener may not have created the pipe yet
with self.assertLogs("kurgan.hw.client", level="INFO"):
client.poll()
if client.error is None or time.monotonic() > deadline:
break
self.assertIsNone(client.error)
client.set_profile("performance")
self.assertEqual(hw.saved()["cooling"]["profile"], "performance")
stop = threading.Event()
thread = threading.Thread(target=client.run, args=(stop,))
thread.start()
stop.set()
thread.join(5)
self.assertFalse(thread.is_alive())
if __name__ == "__main__":
unittest.main()
+49 -8
View File
@@ -18,6 +18,19 @@ class FakeWorker:
pass
class FakeRam:
"""The RAM zone in the hardware service (kurgan.hw.client.RamLighting)."""
def __init__(self):
self.mode, self.status, self.error = "off", "off", None
def set_mode(self, mode):
if self.error is not None:
raise self.error
self.mode = mode
self.status = f"{mode} (service)"
class LightingServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
@@ -25,22 +38,50 @@ class LightingServiceTest(unittest.TestCase):
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
def service(self, overrides=None):
self.ram = FakeRam()
return LightingService(self.settings, Theme(), (0.15, 0.025, 150.0, 550.0), overrides,
rgb=FakeWorker(), memory=FakeWorker(), gpu=FakeWorker())
ram=self.ram, rgb=FakeWorker(), gpu=FakeWorker())
def active(self, service, zone):
return sorted(mode for mode, event in service._events[zone].items() if event.is_set())
def test_saved_modes_start_and_switch_exclusively(self):
self.settings.update("lighting", memory="temperature")
self.settings.update("lighting", case_fans="temperature")
service = self.service()
self.assertEqual(self.active(service, "memory"), ["temperature"])
service.set_mode("memory", "chase")
self.assertEqual(self.active(service, "memory"), ["chase"])
self.assertEqual(self.active(service, "case_fans"), ["temperature"])
service.set_mode("case_fans", "chase")
self.assertEqual(self.active(service, "case_fans"), ["chase"])
self.assertEqual(self.active(service, "gpu"), [])
service.set_mode("case_fans", "off")
self.assertEqual(self.active(service, "case_fans"), [])
service.set_mode("memory", "off")
self.assertEqual(self.active(service, "memory"), [])
self.assertEqual(Settings(self.settings.path, None).get("lighting", "memory"), "off")
self.assertEqual(Settings(self.settings.path, None).get("lighting", "case_fans"), "off")
def test_the_ram_is_the_hardware_services_and_not_saved_here(self):
self.settings.update("lighting", memory="temperature") # an old settings.json: ignored
service = self.service()
self.assertNotIn("memory", service._events)
self.assertEqual(service.mode("memory"), "off")
service.set_mode("memory", "chase")
self.assertEqual(self.ram.mode, "chase")
zone = service.snapshot()["zones"][1]
self.assertEqual((zone["key"], zone["mode"], zone["status"]), ("memory", "chase", "chase (service)"))
self.assertEqual(self.settings.get("lighting", "memory"), "temperature") # left alone
self.assertEqual(service.snapshot()["chase_ms_per_led"], 150) # a RAM chase counts
self.ram.error = OSError("the hardware service isn't running (no pipe)")
with self.assertRaises(OSError):
service.set_mode("memory", "off")
self.assertEqual(service.mode("memory"), "chase")
def test_the_chase_clock_is_what_the_hardware_service_takes(self):
from kurgan.hw.protocol import check_args
service = self.service()
service.on_telemetry(50, 50, 350.0)
clock = service.chase_clock()
self.assertEqual(check_args("ram_chase", clock), clock)
self.assertEqual(clock["power"], 350.0)
later = service.chase_clock()
self.assertGreaterEqual(later["phase"], clock["phase"])
def test_failed_save_leaves_the_lights_as_they_were(self):
service = self.service()
+14 -4
View File
@@ -24,11 +24,21 @@ class ValidateTest(unittest.TestCase):
validate({"cooling": cooling})
def test_lighting_modes_follow_each_zone(self):
self.assertEqual(validate({"lighting": {"memory": "chase"}})["lighting"]["memory"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}):
self.assertEqual(validate({"lighting": {"case_fans": "chase"}})["lighting"]["case_fans"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}, {"memory": "rainbow"}):
with self.subTest(lighting=lighting), self.assertRaises(SettingsError):
validate({"lighting": lighting})
def test_the_hardware_services_old_sections_are_checked_kept_and_never_added(self):
self.assertNotIn("cooling", validate({}))
self.assertNotIn("memory", validate({})["lighting"])
old = validate({"cooling": {"profile": "quiet", "gpu_ports": [4, 5, 6]}, "lighting": {"memory": "chase"}})
self.assertEqual(old["cooling"], {"profile": "quiet", "gpu_ports": [4, 5, 6]})
self.assertEqual(old["lighting"]["memory"], "chase")
self.assertEqual(validate({"cooling": {"gpu_ports": [4, 5, 6]}})["cooling"]["profile"], "balanced")
with self.assertRaises(SettingsError):
validate({"cooling": {"profile": "quiet", "fans": 3}})
def test_ai_choices_and_ports(self):
self.assertEqual(validate({"ai": {"active": "llama"}})["ai"]["active"], "llama")
for ai in ({"active": "ollama"}, {"strata_model": "q8"}, {"strata_port": 80},
@@ -95,8 +105,8 @@ class SettingsFileTest(unittest.TestCase):
def test_returned_sections_are_copies(self):
settings = Settings(self.path, None)
settings.section("lighting")["memory"] = "chase"
self.assertEqual(settings.get("lighting", "memory"), "off")
settings.section("lighting")["case_fans"] = "chase"
self.assertEqual(settings.get("lighting", "case_fans"), "off")
if __name__ == "__main__":
+4
View File
@@ -3,6 +3,7 @@ import json
import socket
import unittest
from kurgan.hw.client import HardwareUnavailable
from kurgan.web.server import WebServer
@@ -28,6 +29,8 @@ class FakeApp:
self.calls.append(("profile", profile))
if profile == "full-disk":
raise OSError("disk full")
if profile == "no-service":
raise HardwareUnavailable("the hardware service isn't running (no pipe)")
def set_ai(self, backend, variant):
self.calls.append(("ai", backend, variant))
@@ -119,6 +122,7 @@ class WebServerTest(unittest.TestCase):
("/api/lighting", b"x" * 20000, 400, "oversized"),
("/api/ai/active", {"backend": 3}, 400, "string or null"),
("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"),
("/api/cooling/profile", {"profile": "no-service"}, 503, "isn't running"),
("/api/fans", {"x": 1}, 404, None))
for path, body, expected, message in cases:
with self.subTest(path=path, body=body):