"""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) Preview: python -m kurgan --preview x.png (render one LCD frame from live sensors and exit) 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 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(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 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(): 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 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: 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). 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)") 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) 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") 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_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.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 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 self.hw_service = None # the hardware service, when it runs in-process (--demo) if args.demo: from kurgan import demo hw = demo.hardware() 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, 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 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) 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), 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 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 _on_sample(self, sample) -> None: p = sample.power self.lighting.on_telemetry(sample.cpu.temp, sample.gpu.temp, p.total) 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)}, " 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 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) 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.hw.cooling(), 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() # -- 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}, "hardware": self.hw.snapshot(), "cooling": self.hw.cooling(), "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: """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: 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]: from kurgan.cooling.profiles import PROFILES lines = [] if self.display is not None: lines.append(self.display.status) 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.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']}") 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.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 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) 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