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

+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)