Files
the_kurgan/kurgan/demo.py
T
paulandClaude Opus 5.5 eb771656fb 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>
2026-12-05 19:41:51 +13:00

165 lines
5.5 KiB
Python

"""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. 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
"""
from __future__ import annotations
import math
import threading
import time
from kurgan.telemetry.readings import PowerReadings, Readings
_T0 = time.monotonic()
def _wave(period: float, phase: float = 0.0) -> float:
"""0..1, slowly rising and falling."""
return 0.5 + 0.5 * math.sin((time.monotonic() - _T0) * 2 * math.pi / period + phase)
class FakeCpu:
status = "simulated"
def read(self) -> Readings:
load = 5 + 70 * _wave(150) ** 3
return Readings(temp=38 + 0.5 * load, load=load, clock=1200 + 40 * load, power=15 + 1.6 * load)
class FakeGpu:
def read(self) -> Readings:
load = 2 + 95 * _wave(90, 1.0) ** 4
return Readings(temp=34 + 0.42 * load, load=load, clock=210 + 26 * load, power=18 + 4.2 * load)
def memory(self) -> tuple[int, int]:
return int((1.4 + 18 * _wave(300, 2.0)) * 2**30), 24 * 2**30
class FakeCommander:
controlled = False
def __init__(self):
self.duty = {p: 100 for p in range(1, 7)}
def _rpm(self, port: int) -> int:
return int(525 + 9.75 * self.duty[port])
def read(self) -> list[int]:
return [self._rpm(p) for p in range(1, 7)]
def set_duty(self, ports, duty: int) -> dict[int, int]:
for p in ports:
self.duty[p] = duty
return {p: self._rpm(p) for p in ports}
def full_speed(self) -> dict[int, int]:
return self.set_duty(range(1, 7), 100)
def close(self) -> None:
pass
class FakeSystem:
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),
"Case fans (6, Commander PRO)": sum(2 * (r / 1500) ** 2.5 for r in self.fans.read()),
"USB devices & RGB lighting (fixed)": 12.0}
return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=sum(parts.values()), parts=parts)
class FakeBoard:
BIOS_RPM = 700 # what a channel left to the BIOS curve turns at
def __init__(self):
self.mask = 0
self.duties: dict[int, int] = {}
def manual_mask(self) -> int:
return self.mask
def rpms(self) -> list[int]:
"""All 16 tachs, like Nct6687.rpms(): 14 RPM per % of duty, a fixed speed under the BIOS."""
return [14 * self.duties.get(c, 0) if self.mask >> c & 1 else self.BIOS_RPM for c in range(16)]
def set_manual(self, channels, duty: int) -> None:
self.mask |= sum(1 << c for c in channels)
self.duties.update((c, duty) for c in channels)
def set_auto(self, channels) -> None:
self.mask &= ~sum(1 << c for c in channels)
def close(self) -> None:
pass
class FakeCpuTemperature:
"""Stands in for cooling.control.CpuTemperature (the service's PawnIO reader)."""
error = None
def __init__(self):
self.temp = self.power = None
def read(self, now: float) -> float:
reading = FakeCpu().read()
self.temp, self.power = reading.temp, reading.power
return reading.temp
def close(self) -> None:
pass
class FakeLights:
"""Stands in for a lighting worker: reports which pattern it would be running."""
def __init__(self, device: str):
self.device = device
self.status = "off"
def set_temperature(self, cpu_temp, gpu_temp=None) -> None:
pass
def set_power(self, total_watts) -> None:
pass
def run(self, stop: threading.Event, *events: threading.Event) -> None:
names = ("temperature", "chase") if len(events) == 2 else ("chase",)
while not stop.is_set():
active = [n for n, e in zip(names, events) if e.is_set()]
self.status = f"{active[0].capitalize()} on the {self.device} (simulated)" if active else "off"
stop.wait(0.2)
def hardware() -> dict:
"""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"))