- kurgan/hw/service.py, HardwareService: one loop a second reads the CPU package (PawnIO MSR: temperature and power) and the GPU (NVML), runs the fan curves, and publishes a state snapshot. It never depends on a client: the pipe side takes no lock the loop needs, every sensor read is guarded (a fault is a missing temperature, so those fans fail safe), and a bug in the loop fails the fans safe and retries. On exit the case fans are left at 100% and the top fans go back to the BIOS curve. - Without saved ports it only reads the Commander PRO's RPMs (for the app's power estimate). With an invalid hw-settings.json it holds every connected PWM fan at 100% (CommanderPro.full_speed) and says why in its state, instead of refusing to start and leaving the fans at their last duty. - State carries the app's cooling snapshot unchanged (profile, groups, top, note, row) plus the CPU temperature and power, GPU temperature, the Commander PRO RPMs and the RAM lighting. NaN never reaches the pipe. - RAM lighting runs in the service; its chase follows the app's clock (SyncedChase, fed by ram_chase) so it stays in step with the other chases. - kurgan/hw/settings.py: %ProgramData%\Kurgan\hw-settings.json, the cooling and RAM lighting sections, as strict as settings.json (validate_cooling is shared). The folder is created SYSTEM/Administrators full, Users read. - kurgan/hw/main.py: serve() wires the loop, the RAM lighting and the pipe (the fans run whatever happens to the pipe); `python -m kurgan.hw` runs it in a console. The pipe user comes from HKLM\...\Services\KurganHw\ Parameters\UserSid; the OpenRGB check reads that user's %APPDATA%. - control.py: CaseFanControl.step() (one guarded pass) and shutdown() replace run(); CpuTemperature also keeps the latest reading, the package power and why it has none. The fan CLI saves to hw-settings.json. - sensors.py: the Commander PRO mutex is Global\KurganCommanderPro, so a console tool in the user's session sees the service's claim. - The app still uses the old worker; it is rewired in step 6. - Tests: 16 new or rewritten (202 pass), including the loop with no client and a stuck client that can't stop fan control. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
227 lines
9.3 KiB
Python
227 lines
9.3 KiB
Python
"""The Kurgan's settings: one JSON file, validated when loaded and before every save.
|
|
|
|
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
|
|
|
|
{
|
|
"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5],
|
|
"profile": "balanced"},
|
|
"lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"},
|
|
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
|
|
"web": {"port": 8080}
|
|
}
|
|
|
|
The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the
|
|
rest by the web UI. An invalid file stops The Kurgan from starting rather than silently
|
|
dropping fan control. On first start the TT LCD Dashboard's settings are imported.
|
|
"""
|
|
|
|
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 = {
|
|
"cooling": {"profile": DEFAULT_PROFILE},
|
|
"lighting": {zone: "off" for zone in LIGHTING_MODES},
|
|
"ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL,
|
|
"idle_stop_minutes": ai_config.IDLE_STOP_MINUTES},
|
|
"web": {"port": DEFAULT_WEB_PORT},
|
|
}
|
|
_OPTIONAL = {
|
|
"cooling": {"gpu_ports", "cpu_ports", "top_channels"},
|
|
"lighting": set(),
|
|
"ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"},
|
|
"web": set(),
|
|
}
|
|
|
|
|
|
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)
|
|
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")
|
|
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
|
|
if bad:
|
|
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
|
|
out[section].update(values)
|
|
|
|
validate_cooling(out["cooling"])
|
|
for zone, modes in LIGHTING_MODES.items():
|
|
if 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:
|
|
with self._lock:
|
|
return copy.deepcopy(self._data[name])
|
|
|
|
def get(self, section: str, key: str, default=None):
|
|
with self._lock:
|
|
return copy.deepcopy(self._data[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[section].update(changes)
|
|
data = self._validate(data)
|
|
write_json_atomic(self.path, data)
|
|
self._data = data
|