- 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>
235 lines
9.8 KiB
Python
235 lines
9.8 KiB
Python
"""The Kurgan's settings: one JSON file, validated when loaded and before every save.
|
|
|
|
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
|
|
|
|
{
|
|
"lighting": {"case_fans": "chase", "gpu": "off"},
|
|
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
|
|
"web": {"port": 8080}
|
|
}
|
|
|
|
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
|
|
|
|
import argparse
|
|
import copy
|
|
import json
|
|
import logging
|
|
import os
|
|
import threading
|
|
|
|
from kurgan import paths
|
|
from kurgan.ai import config as ai_config
|
|
from kurgan.cooling.profiles import DEFAULT_PROFILE, PROFILES
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
LIGHTING_MODES = {
|
|
"case_fans": ("off", "temperature", "chase"), # Lighting Node CORE (QL120 fan LEDs)
|
|
"memory": ("off", "temperature", "chase"), # Dominator Platinum DDR5
|
|
"gpu": ("off", "chase"), # ASUS ROG STRIX RTX 4090
|
|
}
|
|
DEFAULT_WEB_PORT = 8080
|
|
|
|
DEFAULTS = {
|
|
"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 = {
|
|
"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
|
|
|
|
|
|
def _ports(value, where: str) -> list[int]:
|
|
from kurgan.cooling.control import parse_ports
|
|
|
|
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
|
raise SettingsError(f"{where} must be an array of integers")
|
|
try:
|
|
return list(parse_ports(",".join(map(str, value))))
|
|
except argparse.ArgumentTypeError as e:
|
|
raise SettingsError(f"{where}: {e}") from None
|
|
|
|
|
|
def _port_number(value, where: str) -> int:
|
|
if type(value) is not int or not 1024 <= value <= 65535:
|
|
raise SettingsError(f"{where} must be a TCP port number 1024-65535")
|
|
return value
|
|
|
|
|
|
def validate_cooling(cooling: dict) -> dict:
|
|
"""Check and normalise a cooling section in place (also used for the hardware service's)."""
|
|
if cooling["profile"] not in PROFILES:
|
|
raise SettingsError(f"cooling.profile must be one of {', '.join(PROFILES)}")
|
|
if ("cpu_ports" in cooling or "top_channels" in cooling) and "gpu_ports" not in cooling:
|
|
raise SettingsError("cooling: save the GPU-side ports (gpu_ports) first")
|
|
for key in ("gpu_ports", "cpu_ports"):
|
|
if key in cooling:
|
|
cooling[key] = _ports(cooling[key], f"cooling.{key}")
|
|
if set(cooling.get("cpu_ports", ())) & set(cooling.get("gpu_ports", ())):
|
|
raise SettingsError("cooling: cpu_ports and gpu_ports must not overlap")
|
|
if "top_channels" in cooling:
|
|
from kurgan.cooling.board_fans import parse_channels
|
|
|
|
value = cooling["top_channels"]
|
|
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
|
raise SettingsError("cooling.top_channels must be an array of integers")
|
|
try:
|
|
cooling["top_channels"] = list(parse_channels(",".join(map(str, value))))
|
|
except argparse.ArgumentTypeError as e:
|
|
raise SettingsError(f"cooling.top_channels: {e}") from None
|
|
return cooling
|
|
|
|
|
|
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) - 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")
|
|
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.setdefault(section, {}).update(values)
|
|
|
|
if "cooling" in out:
|
|
out["cooling"] = validate_cooling({"profile": DEFAULT_PROFILE, **out["cooling"]})
|
|
for zone, modes in LIGHTING_MODES.items():
|
|
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"]
|
|
if ai["active"] is not None and ai["active"] not in ai_config.BACKENDS:
|
|
raise SettingsError(f"ai.active must be null or one of {', '.join(ai_config.BACKENDS)}")
|
|
if ai["strata_model"] not in ai_config.STRATA_MODELS:
|
|
raise SettingsError(f"ai.strata_model must be one of {', '.join(ai_config.STRATA_MODELS)}")
|
|
if type(ai["idle_stop_minutes"]) is not int or not 0 <= ai["idle_stop_minutes"] <= 1440:
|
|
raise SettingsError("ai.idle_stop_minutes must be 0 (never) to 1440")
|
|
for key in ("strata_root", "llama_server", "llama_presets", "llama_model"):
|
|
if key in ai and (not isinstance(ai[key], str) or not ai[key]):
|
|
raise SettingsError(f"ai.{key} must be a non-empty string")
|
|
for key in ("strata_port", "llama_port"):
|
|
if key in ai:
|
|
_port_number(ai[key], f"ai.{key}")
|
|
if ai.get("strata_port", ai_config.STRATA_PORT) == ai.get("llama_port", ai_config.LLAMA_PORT):
|
|
raise SettingsError("ai: Strata and llama.cpp need different ports")
|
|
_port_number(out["web"]["port"], "web.port")
|
|
return out
|
|
|
|
|
|
def write_json_atomic(path: str, data: dict) -> None:
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
temporary = path + ".tmp"
|
|
try:
|
|
with open(temporary, "w", encoding="utf-8") as stream:
|
|
json.dump(data, stream, indent=2)
|
|
stream.write("\n")
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, path)
|
|
finally:
|
|
if os.path.exists(temporary):
|
|
os.remove(temporary)
|
|
|
|
|
|
def _legacy(legacy_dir: str) -> dict:
|
|
"""The TT LCD Dashboard's fan-control.json, memory-lighting.json and gpu-lighting.json."""
|
|
data: dict = {}
|
|
|
|
def read(name: str):
|
|
try:
|
|
with open(os.path.join(legacy_dir, name), encoding="utf-8") as stream:
|
|
return json.load(stream)
|
|
except FileNotFoundError:
|
|
return None
|
|
except ValueError as e:
|
|
raise SettingsError(f"{legacy_dir}\\{name}: {e}") from None
|
|
|
|
fans = read("fan-control.json")
|
|
if fans is not None:
|
|
if not isinstance(fans, dict) or not set(fans) <= {"gpu_ports", "cpu_ports", "top_channels"}:
|
|
raise SettingsError(f"{legacy_dir}\\fan-control.json has unexpected contents")
|
|
data["cooling"] = dict(fans)
|
|
for name, zone in (("memory-lighting.json", "memory"), ("gpu-lighting.json", "gpu")):
|
|
mode = read(name)
|
|
if mode is not None:
|
|
if not isinstance(mode, dict) or set(mode) != {"mode"}:
|
|
raise SettingsError(f"{legacy_dir}\\{name} has unexpected contents")
|
|
data.setdefault("lighting", {})[zone] = mode["mode"]
|
|
return data
|
|
|
|
|
|
class Settings:
|
|
"""Thread-safe: the web server, the tray and the CLI all go through update()."""
|
|
|
|
def __init__(self, path: str = paths.SETTINGS_PATH, legacy_dir: str | None = paths.LEGACY_DIR,
|
|
seed: dict | None = None, validator=None):
|
|
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags).
|
|
validator: the file's validate() (default: this module's, for settings.json)."""
|
|
self.path = path
|
|
self._validate = validator or validate
|
|
self._lock = threading.RLock()
|
|
self.created = False
|
|
try:
|
|
with open(path, encoding="utf-8") as stream:
|
|
raw = json.load(stream)
|
|
except FileNotFoundError:
|
|
raw = _legacy(legacy_dir) if legacy_dir else {}
|
|
for section, values in (seed or {}).items():
|
|
raw.setdefault(section, {}).update(values)
|
|
self.created = True
|
|
except ValueError as e:
|
|
raise SettingsError(f"{path}: {e}") from None
|
|
try:
|
|
self._data = self._validate(raw)
|
|
except SettingsError as e:
|
|
raise SettingsError(f"{path}: {e}") from None
|
|
if self.created:
|
|
write_json_atomic(path, self._data)
|
|
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.get(name, {}))
|
|
|
|
def get(self, section: str, key: str, default=None):
|
|
with self._lock:
|
|
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.setdefault(section, {}).update(changes)
|
|
data = self._validate(data)
|
|
write_json_atomic(self.path, data)
|
|
self._data = data
|