"""Hosting the hardware service in the Windows service manager, with pywin32 (Decision 0002). setup.ps1 installs it as the "KurganHw" service, LocalSystem, automatic start at boot: "\\python.exe" -I -S -B "\\hw_service.py" The base interpreter, not the venv's python.exe: on Windows that one is a redirector that runs the real interpreter as a child process, and the service manager only talks to the process it started. hw_service.py puts the repo and the venv's packages on the path itself. Stop and shutdown (the service accepts both) end the hardware loop, which leaves the case fans at 100% and hands the top fans back to the BIOS curve. If the service fails unexpectedly the process exits without reporting "stopped", so the service manager's recovery actions (restart after 5 s, 10 s, then 60 s; set by setup.ps1) bring it back. """ from __future__ import annotations import logging import os import sys import threading import pywintypes import servicemanager import win32service import win32serviceutil from kurgan import __version__ from kurgan.hw import main as hw_main log = logging.getLogger("kurgan.hw") ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063 # not started by the service manager class KurganHwService(win32serviceutil.ServiceFramework): _svc_name_ = hw_main.SERVICE_NAME _svc_display_name_ = hw_main.SERVICE_DISPLAY_NAME _svc_description_ = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, " "and the RAM lighting. The app talks to it over \\\\.\\pipe\\kurgan-hw.") def __init__(self, args): super().__init__(args) self.stop = threading.Event() def SvcStop(self) -> None: self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, waitHint=int(hw_main.STOP_SECONDS * 1000)) self.stop.set() def SvcShutdown(self) -> None: # defining it makes the framework accept SERVICE_CONTROL_SHUTDOWN self.SvcStop() def SvcDoRun(self) -> None: try: hw_main.setup_logging(console=False) log.info("Starting %s %s as a service (pid %s)", hw_main.SERVICE_DISPLAY_NAME, __version__, os.getpid()) mutex = hw_main.single_instance() if mutex is None: raise RuntimeError("another copy is running (python -m kurgan.hw in a console?)") hw_main.serve(self.stop, hw_main.configured_user_sid()) log.info("Stopped") except BaseException: fail() def fail() -> None: """Exit at once, without reporting "stopped", so the service manager restarts the service.""" log.exception("The hardware service failed; exiting so the service manager restarts it") logging.shutdown() os._exit(1) def check() -> int: """What setup.ps1 runs before installing: can this interpreter load everything the service needs?""" import pynvml # noqa: F401 (the GPU temperature) from kurgan.hw import service # noqa: F401 (and with it the fan control and the RAM lighting) print(f"ok: {hw_main.SERVICE_DISPLAY_NAME} {__version__}, Python {sys.version.split()[0]} " f"at {sys.executable}") return 0 def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv if argv == ["--check"]: return check() if not argv: servicemanager.Initialize() servicemanager.PrepareToHostSingle(KurganHwService) try: servicemanager.StartServiceCtrlDispatcher() return 0 except pywintypes.error as e: if e.winerror != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: raise return hw_main.main(argv) # started from a console: run there