Files
paulandClaude Opus 5.5 b983528183 Review fixes: demo fans, record averages and restarts, combined alerts, quiet sensors
- demo.py: FakeBoard grows rpms(). The top fans' stall check (b2da221) called
  it, so under --demo every poll raised AttributeError and the case fans sat
  in CONTROL ERROR at 100%.
- control.py: TopFanCurve.update hands the headers back to the BIOS on any
  failure, a bug included, instead of letting it escape into the case fans'
  loop (unexpected errors are logged with a traceback once). The worker's
  catch-all now fails the top fans safe as well as the case fans, as the
  device-error path already did. The snapshot gives None for a channel whose
  tach has never turned, and the UI says "no tach reading" (and "Channel",
  not "Port") rather than showing SYS_FAN1's unwired tach as a dead fan.
- record.py: an hour's average is over the samples that carried the metric,
  not all of them: a GPU that dropped out for half an hour no longer halves
  its recorded power. Lines carry the count as a fourth number; the reader
  weights by it, and treats three-number lines as before.
- record.py: the hour in progress is checkpointed to records-current.json
  every minute and on close and resumed at start, so a hard stop (schtasks
  /End, the documented restart) loses at most a minute instead of the hour;
  a checkpoint from an earlier hour is written out at start. A failing write
  no longer stops recording for the run: it is logged at most once an hour
  and finished hours wait in memory (up to 48) until the disk works.
- app.py: alerts that start together share one balloon (Windows shows one at
  a time, so each notify() replaced the last), shortened to fit 255
  characters; a problem that clears and comes back balloons again only after
  10 minutes.
- telemetry/service.py: health also counts a source that returns no
  temperature three reads running. GpuSensors and CpuSensors don't raise
  when their device is lost, so a lost GPU driver used to show as healthy.
- hid.py: buffers of IRPs the driver never finished cancelling are kept for
  the life of the process; freeing them with their channel could still let a
  late completion write into reused memory.
- Tests: 13 new (160 pass). README updated to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:31:11 +13:00

510 lines
24 KiB
Python

"""The Kurgan: one process for the LCD, fans, 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)
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).
"""
from __future__ import annotations
import argparse
import collections
import ctypes
import logging
import logging.handlers
import math
import os
import sys
import threading
import time
from kurgan import APP_NAME, __version__, paths
log = logging.getLogger("kurgan")
INSTANCE_MUTEXES = ("Local\\TheKurgan", "Local\\TTLcdDashboard") # the second keeps an old dashboard copy out
DEMO_MUTEXES = ("Local\\TheKurganDemo",)
def _setup_logging(verbose: bool) -> None:
os.makedirs(paths.DATA_DIR, exist_ok=True)
handlers: list[logging.Handler] = [
logging.handlers.RotatingFileHandler(paths.LOG_PATH, maxBytes=1_000_000, backupCount=2, encoding="utf-8")
]
if sys.stderr is not None:
handlers.append(logging.StreamHandler())
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
def _single_instance(names=INSTANCE_MUTEXES) -> list | None:
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateMutexW.restype = ctypes.c_void_p
k32.CloseHandle.argtypes = [ctypes.c_void_p]
handles = []
for name in names:
handle = k32.CreateMutexW(None, False, name)
if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED
for h in handles + ([handle] if handle else []):
k32.CloseHandle(h)
return None
handles.append(handle)
return handles
def _message_box(text: str) -> None:
try:
ctypes.WinDLL("user32").MessageBoxW(None, text, APP_NAME, 0x10 | 0x10000)
except Exception:
pass
def _parse_color(text: str) -> tuple[int, int, int]:
text = text.lstrip("#")
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
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."""
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 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"
return states
ALERT_REPEAT_SECONDS = 600.0 # a problem that clears and comes back balloons again only after this
def new_alerts(known: dict[str, str], states: dict[str, str]) -> list[tuple[str, str]]:
"""(key, message) for alerts that are new since the last look; recovered ones stay quiet."""
return [(key, states[key]) for key in sorted(states.keys() - known.keys())]
def due_alerts(new: list[tuple[str, str]], alerted: dict[str, float], now: float) -> list[tuple[str, str]]:
"""The new alerts not already ballooned in the last ALERT_REPEAT_SECONDS; records them in
`alerted` (key -> when). A flapping problem balloons once, not every time it comes back."""
due = [(key, message) for key, message in new if now - alerted.get(key, -1e18) >= ALERT_REPEAT_SECONDS]
alerted.update((key, now) for key, _ in due)
return due
def balloon(messages: list[str]) -> tuple[str, str]:
"""One balloon (title, text) for all of them: Windows shows one balloon at a time, so a
second notify() would only replace the first. The text holds up to 255 characters."""
if len(messages) == 1:
return APP_NAME, messages[0]
lines: list[str] = []
for i, message in enumerate(messages):
rest = len(messages) - i - 1
tail = f"\n...and {rest} more" if rest else ""
if len("\n".join(lines + [message])) + len(tail) > 255:
if not lines: # the first one alone is too long: shorten it
lines.append(message[:255 - len(tail) - 3] + "...")
lines.append(tail.lstrip("\n"))
else: # the previous round made sure this note fits
lines.append(f"...and {rest + 1} more")
break
lines.append(message)
return f"{APP_NAME}: {len(messages)} problems", "\n".join(filter(None, lines))
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)")
ap.add_argument("--no-ai", action="store_true", help="don't start or watch the LLM servers")
ap.add_argument("--no-lcd", action="store_true", help="don't drive the LCD (sensors keep running)")
ap.add_argument("--no-tray", action="store_true", help="don't show the notification-area icon")
ap.add_argument("--preview", metavar="PNG", help="render one LCD frame from live sensors to a PNG and exit")
ap.add_argument("--demo", action="store_true",
help="simulated sensors and devices, no LCD (set KURGAN_DATA_DIR for separate settings)")
# LCD
ap.add_argument("--interval", type=float, default=1.0, help="seconds between sensor reads/LCD frames (max 2)")
ap.add_argument("--brightness", type=int, default=100, help="LCD backlight 0-100")
ap.add_argument("--rotate180", action="store_true", help="flip the image if the panel is mounted upside down")
ap.add_argument("--accent", default="e81c2c", help="LCD title colour as hex")
ap.add_argument("--psu-watts", type=float, default=1000.0, help="power supply rating; fills the power tank")
ap.add_argument("--cpu-temp-max", type=float, default=100.0)
ap.add_argument("--gpu-temp-max", type=float, default=90.0)
ap.add_argument("--temp-warn", type=float, default=50.0, help="gauges and lighting turn yellow here")
ap.add_argument("--temp-hot", type=float, default=80.0, help="gauges and lighting turn red above this")
ap.add_argument("--load-warn", type=float, default=50.0)
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).
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)")
ap.add_argument("--rgb-chase-step-ms", type=float, default=150.0, help="ms per chase LED at idle power")
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"):
if not math.isfinite(getattr(args, name)) or getattr(args, name) < 20:
ap.error(f"--{name.replace('_', '-')} must be finite and at least 20")
if args.rgb_chase_fast_ms > args.rgb_chase_step_ms:
ap.error("--rgb-chase-fast-ms can't be slower than --rgb-chase-step-ms")
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
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
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.lighting.service import LightingService
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.telemetry.service import Telemetry
from kurgan.theme import Theme
self.args = args
self.settings = settings
self.started = time.time()
self.stop = threading.Event()
self.theme = Theme(accent=_parse_color(args.accent), cpu_temp_range=(20.0, args.cpu_temp_max),
gpu_temp_range=(20.0, args.gpu_temp_max), psu_watts=max(100.0, args.psu_watts),
temp_warn=args.temp_warn, temp_hot=args.temp_hot,
load_warn=args.load_warn, load_hot=args.load_hot)
hw = None
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(),
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
self.system, args.interval)
self.recorder = None
if not args.demo: # simulated samples must not mix into the real records
from kurgan.telemetry.record import Recorder
self.recorder = Recorder(paths.DATA_DIR)
self.telemetry.subscribe(self.recorder.on_sample)
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 {}))
self.ai = None
if not args.no_ai:
from kurgan.ai.service import AiService
self.ai = AiService(settings)
self.web = None
self.tray = None
self._threads: list[threading.Thread] = []
self.fan_history: collections.deque[tuple] = collections.deque(maxlen=self.telemetry._history.maxlen)
self.telemetry.subscribe(self._on_sample)
# -- 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))
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)}, "
f"GPU {fmt(p.gpu)}, other {fmt(p.other)}")
def _thread(self, name: str, target, *args) -> None:
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
thread.start()
self._threads.append(thread)
def start(self, port: int, tray: bool) -> None:
from kurgan.web.server import WebServer
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)
if self.ai is not None:
self.ai.set_public_url(f"http://127.0.0.1:{port}")
self._threads += self.ai.start(self.stop)
try:
self.web = WebServer(self, port)
self.web.start()
except OSError as e:
log.error("Web UI unavailable on port %s: %s", port, e)
if tray:
self._start_tray()
self._thread("alerts", self._alert_monitor, self.stop)
def _alert_monitor(self, stop: threading.Event) -> None:
"""Balloon tips for things starting to go wrong. The first look is the baseline: what
is already wrong at startup sits in the tray menu and the UI, it doesn't need a balloon."""
known: dict[str, str] | None = None
alerted: dict[str, float] = {} # key -> when it last ballooned
while not stop.wait(ALERT_SECONDS):
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)
except Exception:
log.exception("Alert check failed")
continue
if known is None:
known = states
continue
due = due_alerts(new_alerts(known, states), alerted, time.monotonic())
for _, message in due:
log.warning("Alert: %s", message)
if due:
self.tray.notify(*balloon([message for _, message in due]), warning=True)
known = states
def _start_tray(self) -> None:
from kurgan.tray import ICON_PATH, TrayIcon
try:
self.tray = TrayIcon(APP_NAME, ICON_PATH, on_exit=self.stop.set,
on_open=self.open_ui if self.web else None, status_lines=self.tray_lines)
self.tray.start()
except Exception:
log.exception("Tray icon unavailable")
self.tray = None
def open_ui(self) -> None:
from kurgan.ai.launcher import open_url
try:
open_url(self.web.url)
except OSError:
log.exception("Couldn't open the browser")
def wait(self) -> None:
try:
while not self.stop.wait(1):
pass
except KeyboardInterrupt:
self.stop.set()
def close(self) -> None:
self.stop.set()
if self.web is not None:
self.web.close()
if self.tray is not None:
self.tray.close()
deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly
for thread in self._threads:
thread.join(max(0.1, deadline - time.monotonic()))
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
def config(self) -> dict:
from kurgan.cooling.profiles import PROFILES
return {"app": APP_NAME, "version": __version__,
"profiles": [p.as_dict() for p in PROFILES.values()],
"theme": {"temp_warn": self.theme.temp_warn, "temp_hot": self.theme.temp_hot,
"psu_watts": self.theme.psu_watts}}
def state(self) -> dict:
from kurgan.ai.launcher import token_info
try:
me = token_info()
except OSError:
me = None
return {
"app": {"name": APP_NAME, "version": __version__, "uptime": round(time.time() - self.started),
"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}),
"lighting": self.lighting.snapshot(),
"ai": self.ai.snapshot() if self.ai else None,
}
def history(self) -> dict:
return {**self.telemetry.history(),
"fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}}
def records(self, days: int) -> dict:
from kurgan.telemetry.record import RETENTION_DAYS, load
if not isinstance(days, int) or not 1 <= days <= RETENTION_DAYS:
raise ValueError(f"days must be a whole number from 1 to {RETENTION_DAYS}")
return load(paths.DATA_DIR, days)
def set_lighting(self, zone: str, mode: str) -> None:
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])
def set_ai(self, backend: str | None, variant: str | None) -> None:
if self.ai is None:
raise ValueError("AI management is off for this run (--no-ai)")
self.ai.set_active(backend, variant)
def ai_model(self, action: str) -> None:
if self.ai is None:
raise ValueError("AI management is off for this run (--no-ai)")
self.ai.model_action(action)
# -- tray
def tray_lines(self) -> list[str]:
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 ""
lines.append(f"Fans: {profile} ({groups}{top})")
elif self.fan_note:
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']}")
if self.ai is not None:
ai = self.ai.snapshot()
active = next((b for b in ai["backends"] if b["key"] == ai["active"]), None)
if active is None:
lines.append("AI: none selected")
else:
lines.append(f"AI: {active['label']} - {active['process']}, model {active['model']['state']}")
if self.web is not None:
lines.append(f"Web UI: {self.web.url}")
return lines
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
_setup_logging(args.verbose)
from kurgan.settings import Settings, SettingsError
if args.preview:
from kurgan.display.renderer import DashboardRenderer
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.theme import Theme
from kurgan.telemetry.service import Telemetry
telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower())
telemetry.read()
time.sleep(1.0) # let counters and the energy meter accumulate
sample = telemetry.read()
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)
print(f"Wrote {args.preview}")
return 0
mutexes = _single_instance(DEMO_MUTEXES if args.demo else INSTANCE_MUTEXES)
if mutexes is None:
log.error("Another copy of The Kurgan (or the TT LCD Dashboard) is already running")
return 1
try:
settings = Settings(seed={"lighting": lighting_overrides(args)})
except (OSError, SettingsError) as e:
log.error("Invalid settings; refusing to start: %s", e)
_message_box(f"The Kurgan didn't start: its settings are invalid.\n\n{e}\n\nLog: {paths.LOG_PATH}")
return 1
port = args.port or settings.get("web", "port")
log.info("Starting %s %s (pid %s)", APP_NAME, __version__, os.getpid())
try:
app = Kurgan(args, settings)
except ValueError:
log.exception("Invalid configuration; refusing to start")
return 1
app.start(port, tray=not args.no_tray)
app.wait()
log.info("Stopping")
app.close()
log.info("Stopped")
return 0