"""The app's side of the hardware service: a client that keeps reconnecting. A background thread asks the service for its state once a second (and sends the app's chase clock for the RAM lighting); the web UI's profile and RAM lighting changes are sent at once. While the service can't be reached, every reading from it is None or empty, `error` says why, and the changes raise HardwareUnavailable (the web API answers 503). The service itself never depends on the app: it controls the fans whether or not anything is connected. The app only shows what the service reports and asks it for changes. client = HardwareClient(PipeTransport) the real service, over \\\\.\\pipe\\kurgan-hw client = HardwareClient(lambda: LocalTransport(service.dispatch, version)) --demo, tests """ from __future__ import annotations import itertools import logging import threading import time from typing import Callable from kurgan import APP_NAME, __version__ from kurgan.cooling.profiles import PROFILES from kurgan.hw import protocol from kurgan.hw.protocol import PIPE_NAME, PROTOCOL_VERSION, ProtocolError, RemoteError, Unavailable log = logging.getLogger(__name__) POLL_SECONDS = 1.0 CALL_SECONDS = 2.0 # how long one request may take STALE_SECONDS = 5.0 # no state received for this long: the service is unreachable STALL_SECONDS = 15.0 # the service's own state this old: its loop is stuck (it waits 5 s after an error) BUSY_SECONDS = 5.0 # how long a change waits for the connection SERVICE_NAME = "hardware service" # the telemetry health source class HardwareUnavailable(Unavailable): """The hardware service can't be reached, or can't do that right now.""" class PipeTransport: """One connection to the service's pipe, speaking the protocol.""" def __init__(self, name: str = PIPE_NAME, timeout: float = CALL_SECONDS, **pipe_options): from kurgan.hw.pipe import PipeClient self._pipe = PipeClient(name, timeout, **pipe_options) # checks the pipe's owner by default self._ids = itertools.count(1) def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS): request_id = next(self._ids) line = self._pipe.request(protocol.encode_request(op, args, request_id), timeout) return protocol.decode_reply(line, request_id) def close(self) -> None: self._pipe.close() class LocalTransport: """The same conversation, encoded and checked the same way, without a pipe: --demo and tests.""" def __init__(self, dispatch: Callable[[str, dict], object], service_version: str = __version__): self._session = protocol.Session(dispatch, service_version) self._ids = itertools.count(1) self.closed = False def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS): if self.closed: raise OSError("connection closed") request_id = next(self._ids) reply, close = self._session.handle(protocol.encode_request(op, args, request_id).rstrip(b"\n")) if close: self.closed = True return protocol.decode_reply(reply.rstrip(b"\n"), request_id) def close(self) -> None: self.closed = True # Error replies that mean the two sides don't understand each other: drop the connection. _MISMATCH = (protocol.VERSION, protocol.BAD_REQUEST, protocol.UNKNOWN_OP, protocol.HELLO_FIRST, protocol.TOO_LARGE) class HardwareClient: def __init__(self, connect: Callable[[], object] = PipeTransport, *, poll_seconds: float = POLL_SECONDS, chase: Callable[[], dict | None] | None = None): """connect() opens a transport (OSError if it can't). chase() gives the ram_chase arguments to send with each poll, or None.""" self._connect = connect self.poll_seconds = poll_seconds self.chase = chase self._lock = threading.Lock() # one request at a time on the connection self._transport = None self._state: dict | None = None self._state_at = 0.0 # time.monotonic() of the last state received self._error: str | None = "not connected yet" self.service: dict | None = None # the service's hello reply self._last_profile: str | None = None self._last_ram_mode: str | None = None # -- the connection def _drop(self) -> None: if self._transport is not None: try: self._transport.close() except Exception: pass self._transport = None def _call(self, op: str, args: dict | None = None): """One request; the caller holds self._lock. HardwareUnavailable or ValueError.""" try: if self._transport is None: transport = self._connect() try: hello = transport.call("hello", {"protocol": PROTOCOL_VERSION, "client": f"{APP_NAME} {__version__}"}) except BaseException: transport.close() raise self._transport, self.service = transport, hello log.info("Connected to the hardware service (version %s)", hello.get("service")) return self._transport.call(op, args) except RemoteError as e: if e.code == protocol.INVALID: raise ValueError(str(e)) from None if e.code in _MISMATCH: self._drop() hint = "; re-run setup.ps1 so the app and the service match" if e.code in ( protocol.VERSION, protocol.UNKNOWN_OP) else "" raise HardwareUnavailable(f"the hardware service refused the request ({e}){hint}") from None raise HardwareUnavailable(str(e)) from None # UNAVAILABLE, INTERNAL: still connected except ProtocolError as e: self._drop() raise HardwareUnavailable(f"bad reply from the hardware service: {e}") from None except OSError as e: self._drop() raise HardwareUnavailable(str(e) or type(e).__name__) from None def _store(self, state) -> None: if not isinstance(state, dict): raise HardwareUnavailable("bad state from the hardware service") self._state, self._state_at = state, time.monotonic() self._last_profile = (state.get("cooling") or {}).get("profile", self._last_profile) self._last_ram_mode = ((state.get("lighting") or {}).get("memory") or {}).get("mode", self._last_ram_mode) def _set_error(self, error: str | None) -> None: if error != self._error: if error is None: log.info("Hardware service reachable") else: log.warning("Hardware service unavailable: %s", error) self._error = error def poll(self) -> None: """Fetch the state (and send the chase clock); never raises.""" try: chase = self.chase() if self.chase is not None else None except Exception: log.exception("Chase clock failed") chase = None try: with self._lock: state = self._call("state") if chase is not None: self._call("ram_chase", chase) self._store(state) age = time.time() - state["t"] if isinstance(state.get("t"), (int, float)) else 0.0 self._set_error(None if age <= STALL_SECONDS else f"the hardware service's loop has stalled (its state is {age:.0f} s old)") except (HardwareUnavailable, ValueError) as e: self._set_error(str(e)) except Exception as e: log.exception("Hardware service poll failed") self._set_error(f"{type(e).__name__}: {e}") def run(self, stop: threading.Event) -> None: while not stop.is_set(): self.poll() stop.wait(self.poll_seconds) with self._lock: self._drop() def _command(self, op: str, args: dict) -> None: if not self._lock.acquire(timeout=BUSY_SECONDS): raise HardwareUnavailable("the hardware service is busy; try again") try: state = self._call(op, args) finally: self._lock.release() self._store(state) # -- what the app reads @property def error(self) -> str | None: """Why the service's readings can't be used now, or None.""" if self._error is None and time.monotonic() - self._state_at > STALE_SECONDS: return "no state from the hardware service" return self._error @property def state(self) -> dict | None: """The service's latest state while it's fresh, else None.""" return self._state if self.error is None else None def snapshot(self) -> dict: """For the web UI's state.""" state = self.state service = (state or {}).get("service") or {} return {"available": state is not None, "error": self.error, "version": service.get("version"), "pid": service.get("pid"), "uptime": service.get("uptime"), "settings_error": service.get("settings_error")} def cooling(self) -> dict: """The service's fan state, as the web UI shows it.""" state = self.state if state is not None: return state["cooling"] return {"profile": self._last_profile, "groups": [], "top": None, "row": None, "note": (f"Hardware service unavailable: {self.error}. The service controls the fans, " "not this app: no fan readings or changes until it's back.")} def cpu(self) -> dict: state = self.state if state is None: return {"temp": None, "power": None, "error": f"hardware service unavailable: {self.error}"} return state["cpu"] def fan_rpms(self) -> list[int]: state = self.state return list(state["commander"]["rpms"]) if state is not None else [] def ram_lighting(self) -> dict: state = self.state if state is not None: return state["lighting"]["memory"] return {"mode": self._last_ram_mode, "status": f"Hardware service unavailable: {self.error}"} # -- what the app changes def set_profile(self, key: str) -> None: if key not in PROFILES: raise ValueError(f"Unknown fan profile {key!r}") self._command("set_profile", {"profile": key}) def set_ram_lighting(self, mode: str) -> None: self._command("set_ram_lighting", {"mode": mode}) class CpuPackage: """The CPU package temperature and power, read by the service (PawnIO needs it elevated); stands in for kurgan.telemetry.sensors.IntelPackage in the app's CpuSensors.""" def __init__(self, client: HardwareClient): self.client = client def read(self) -> tuple[float | None, float | None]: cpu = self.client.cpu() return cpu.get("temp"), cpu.get("power") @property def status(self) -> str: cpu = self.client.cpu() return "ok" if cpu.get("temp") is not None else (cpu.get("error") or "no reading") class CommanderReadings: """The Commander PRO's fan RPMs, read by the service; stands in for CommanderPro in the app's power model (SystemPower).""" controlled = True def __init__(self, client: HardwareClient): self.client = client def read(self) -> list[int]: return self.client.fan_rpms() def close(self) -> None: pass class RamLighting: """The RAM lighting zone, driven by the service; the lighting service's memory zone.""" def __init__(self, client: HardwareClient): self.client = client @property def mode(self) -> str | None: return self.client.ram_lighting()["mode"] @property def status(self) -> str: return self.client.ram_lighting()["status"] def set_mode(self, mode: str) -> None: self.client.set_ram_lighting(mode)