"""Starting and stopping the hardware service's parts: settings, the hardware loop, RAM lighting and the pipe. python -m kurgan.hw in a console (elevated), Ctrl+C to stop: for debugging, with the real service stopped (only one copy runs) As a Windows service it is started through hw_service.py (see kurgan/hw/winservice.py). """ from __future__ import annotations import argparse import ctypes import logging import logging.handlers import os import sys import threading import winreg from kurgan import __version__, paths log = logging.getLogger("kurgan.hw") SERVICE_NAME = "KurganHw" SERVICE_DISPLAY_NAME = "The Kurgan hardware" PARAMETERS_KEY = rf"SYSTEM\CurrentControlSet\Services\{SERVICE_NAME}\Parameters" INSTANCE_MUTEX = "Global\\KurganHw" STOP_SECONDS = 30.0 # how long a stop may take: the loop's last pass plus handing the fans back def setup_logging(console: bool, verbose: bool = False) -> None: from kurgan.hw.settings import ensure_data_dir ensure_data_dir() handlers: list[logging.Handler] = [logging.handlers.RotatingFileHandler( paths.HW_LOG_PATH, maxBytes=1_000_000, backupCount=3, encoding="utf-8")] if console and sys.stderr is not None: handlers.append(logging.StreamHandler()) logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers, force=True, format="%(asctime)s %(levelname)s %(threadName)s %(name)s: %(message)s") def configured_user_sid() -> str | None: """The installing user's SID, from the service's Parameters key (written by setup.ps1).""" from kurgan.hw.pipe import valid_sid try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, PARAMETERS_KEY) as key: value, kind = winreg.QueryValueEx(key, "UserSid") except OSError: return None if kind != winreg.REG_SZ or not valid_sid(value): log.error("Ignoring the invalid UserSid %r in HKLM\\%s", value, PARAMETERS_KEY) return None return value def user_appdata(sid: str | None) -> str | None: """That user's roaming AppData folder, from their profile's registry entry.""" if sid is None: return None try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, rf"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}") as key: profile = os.path.expandvars(winreg.QueryValueEx(key, "ProfileImagePath")[0]) except OSError: return None return os.path.join(profile, "AppData", "Roaming") def single_instance(): """A handle that keeps a second copy out, or None if one is already running.""" k32 = ctypes.WinDLL("kernel32", use_last_error=True) k32.CreateMutexW.restype = ctypes.c_void_p k32.CloseHandle.argtypes = [ctypes.c_void_p] handle = k32.CreateMutexW(None, False, INSTANCE_MUTEX) if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED if handle: k32.CloseHandle(handle) return None return handle def load_settings(): """(settings, None), or (None, why) when hw-settings.json can't be used.""" from kurgan.hw import settings as hw_settings from kurgan.settings import SettingsError try: return hw_settings.load(), None except (OSError, SettingsError) as e: log.error("hw-settings.json can't be used; holding every case fan at 100%%: %s", e) return None, str(e) def serve(stop: threading.Event, user_sid: str | None, *, service=None, pipe_name: str | None = None) -> None: """Run until `stop` is set. The fans are controlled whatever happens to the pipe.""" from kurgan.hw.pipe import PipeServer, pipe_sddl from kurgan.hw.protocol import PIPE_NAME, Session from kurgan.telemetry import sensors if service is None: from kurgan.hw.service import HardwareService sensors.USER_APPDATA = user_appdata(user_sid) service = HardwareService(*load_settings()) if user_sid is None: log.warning("No user is configured for the pipe (HKLM\\%s UserSid); only SYSTEM and Administrators " "can connect. Run setup.ps1 again.", PARAMETERS_KEY) loop = threading.Thread(target=service.run, args=(stop,), name="hw-loop") loop.start() lighting = service.start_lighting(stop) server = None try: server = PipeServer(pipe_name or PIPE_NAME, pipe_sddl(user_sid), lambda: Session(service.dispatch, __version__)) server.start() log.info("Listening on %s for %s", pipe_name or PIPE_NAME, user_sid or "SYSTEM and Administrators only") except Exception: log.exception("The pipe is unavailable; fan control carries on without it") try: while loop.is_alive() and not stop.wait(1.0): pass finally: stop.set() loop.join(STOP_SECONDS) if server is not None: server.close() lighting.join(10) if loop.is_alive(): log.error("The hardware loop didn't stop within %.0f s", STOP_SECONDS) def main(argv: list[str] | None = None) -> int: from kurgan.hw.pipe import current_user_sid, valid_sid ap = argparse.ArgumentParser(prog="python -m kurgan.hw", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--user-sid", help="the user allowed on the pipe (default: the configured one, else you)") ap.add_argument("-v", "--verbose", action="store_true") args = ap.parse_args(argv) setup_logging(console=True, verbose=args.verbose) if args.user_sid is not None and not valid_sid(args.user_sid): ap.error(f"not a SID: {args.user_sid}") mutex = single_instance() if mutex is None: log.error("The hardware service is already running (Stop-Service %s first)", SERVICE_NAME) return 1 log.info("Starting %s %s in a console (pid %s)", SERVICE_DISPLAY_NAME, __version__, os.getpid()) stop = threading.Event() worker = threading.Thread(target=serve, args=(stop, args.user_sid or configured_user_sid() or current_user_sid()), name="hw-serve") worker.start() try: while worker.is_alive(): worker.join(0.5) except KeyboardInterrupt: log.info("Stopping") stop.set() worker.join(STOP_SECONDS + 15) return 0