"""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)