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>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:28:32 +13:00
1 parent 73a424f6a8
commit 7190db733f
11 files changed
+971 -119

No files matched your search

+27 -21
View File
@@ -73,23 +73,8 @@ def _port_number(value, where: str) -> int:
return value
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)
cooling = out["cooling"]
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:
@@ -109,7 +94,26 @@ def validate(data: object) -> dict:
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)}")
@@ -179,9 +183,11 @@ 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):
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags)."""
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:
@@ -195,7 +201,7 @@ class Settings:
except ValueError as e:
raise SettingsError(f"{path}: {e}") from None
try:
self._data = validate(raw)
self._data = self._validate(raw)
except SettingsError as e:
raise SettingsError(f"{path}: {e}") from None
if self.created:
@@ -215,6 +221,6 @@ class Settings:
with self._lock:
data = copy.deepcopy(self._data)
data[section].update(changes)
data = validate(data)
data = self._validate(data)
write_json_atomic(self.path, data)
self._data = data