Files
the_kurgan/kurgan/hw/settings.py
T
paulandClaude Opus 5.5 7190db733f Privilege split 4/11: the kurgan.hw service process
- 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>
2026-12-05 19:28:32 +13:00

90 lines
3.9 KiB
Python

"""The hardware service's settings: %ProgramData%\\Kurgan\\hw-settings.json.
{
"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3],
"top_channels": [2, 5]},
"lighting": {"memory": "off"}
}
The cooling section is checked exactly as settings.json's was (kurgan.settings.validate_cooling);
the lighting section holds the RAM zone only, which the service drives. The folder is writable
by SYSTEM and Administrators only, and readable by users: the service writes the file when the
app changes the profile or the RAM lighting, and the port mapping is saved from an elevated
`python -m kurgan.cooling.control --save-ports ...`.
An invalid file doesn't stop the service: it holds every case fan at 100% and says why in its
state, so the app can show it (see kurgan.hw.service).
"""
from __future__ import annotations
import copy
import ctypes
import ctypes.wintypes as wt
import os
from kurgan import paths
from kurgan.cooling.profiles import DEFAULT_PROFILE
from kurgan.settings import LIGHTING_MODES, Settings, SettingsError, validate_cooling
DEFAULTS = {
"cooling": {"profile": DEFAULT_PROFILE},
"lighting": {"memory": "off"},
}
_OPTIONAL = {"cooling": {"gpu_ports", "cpu_ports", "top_channels"}, "lighting": set()}
# The data folder: SYSTEM and Administrators full control, users read, nothing inherited.
DATA_DIR_SDDL = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)"
def validate(data: object) -> dict:
"""A normalised copy with defaults filled in, or 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"])
if out["lighting"]["memory"] not in LIGHTING_MODES["memory"]:
raise SettingsError(f"lighting.memory must be one of {', '.join(LIGHTING_MODES['memory'])}")
return out
def load(path: str = paths.HW_SETTINGS_PATH) -> Settings:
"""The service's settings (created with the defaults if missing); OSError or SettingsError."""
return Settings(path, legacy_dir=None, validator=validate)
class _SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
def ensure_data_dir(path: str = paths.HW_DATA_DIR) -> None:
"""Create the data folder, if missing, with DATA_DIR_SDDL (setup.ps1 also resets it)."""
if os.path.isdir(path):
return
os.makedirs(os.path.dirname(path), exist_ok=True)
adv = ctypes.WinDLL("advapi32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
descriptor = ctypes.c_void_p()
adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
k32.CreateDirectoryW.argtypes = [wt.LPCWSTR, ctypes.POINTER(_SecurityAttributes)]
k32.LocalFree.argtypes = [ctypes.c_void_p]
if not adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(DATA_DIR_SDDL, 1, ctypes.byref(descriptor), None):
raise ctypes.WinError(ctypes.get_last_error())
try:
attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
if not k32.CreateDirectoryW(path, ctypes.byref(attributes)) and not os.path.isdir(path):
raise ctypes.WinError(ctypes.get_last_error())
finally:
k32.LocalFree(descriptor)