The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI
This commit is contained in:
commit
f631386618
71 files changed
+14616
No files matched your search
@@ -0,0 +1,23 @@
|
||||
"""The Kurgan: one local service for this PC's backend systems.
|
||||
|
||||
Capabilities (one subpackage each):
|
||||
telemetry CPU/GPU/whole-PC power sensing, sampled once a second for everything else
|
||||
display the Thermaltake 3.9" LCD dashboard
|
||||
cooling Commander PRO case fans and motherboard top fans, with selectable profiles
|
||||
lighting Lighting Node CORE fan LEDs, Dominator DDR5 RAM and ASUS GPU LEDs
|
||||
ai the local LLM servers (Strata or llama.cpp), one at a time
|
||||
web the control UI and JSON API on 127.0.0.1
|
||||
Shared: hardware (Win32 HID, PawnIO modules), settings, theme, tray.
|
||||
"""
|
||||
|
||||
APP_NAME = "The Kurgan"
|
||||
__version__ = "1.0.0"
|
||||
|
||||
import os as _os
|
||||
|
||||
# Before numpy is imported anywhere: OpenBLAS otherwise commits ~750 MB of per-thread buffers on
|
||||
# this 28-thread CPU, which The Kurgan never uses (its numpy work is a few tiny vectors). The
|
||||
# marker lets the AI launcher give the LLM servers the default back.
|
||||
if "OPENBLAS_NUM_THREADS" not in _os.environ:
|
||||
_os.environ["OPENBLAS_NUM_THREADS"] = "1"
|
||||
_os.environ["KURGAN_PINNED_OPENBLAS"] = "1"
|
||||
@@ -0,0 +1,7 @@
|
||||
"""python -m kurgan"""
|
||||
|
||||
import sys
|
||||
|
||||
from kurgan.app import main
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""AI: the local LLM servers (Strata or llama.cpp), one running at a time."""
|
||||
@@ -0,0 +1,497 @@
|
||||
"""The two LLM servers: how to start and stop each one, and how to watch it.
|
||||
|
||||
Both monitors report the same shape, so the web UI shows either one the same way:
|
||||
model: {"state": offline|unloaded|loading|idle|sleeping|reading|generating|failed, "detail", "id", "context"}
|
||||
live: the request in progress: {"phase", "progress", "read", "total", "generated", "tok_s", "elapsed"}
|
||||
requests: the latest finished requests, newest first
|
||||
averages: prompt-reading and generation speed over those requests
|
||||
Polling never wakes a model: Strata's /health and /metrics and llama-server's /models and
|
||||
/metrics don't count as use. llama's live progress comes from its log, because polling
|
||||
/slots would reset its idle timer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from kurgan import paths
|
||||
from kurgan.ai import config
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
LOG_DIR = os.path.join(paths.DATA_DIR, "logs")
|
||||
KEEP_REQUESTS = 20
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_k32.OpenEventW.argtypes, _k32.OpenEventW.restype = [wt.DWORD, wt.BOOL, wt.LPCWSTR], wt.HANDLE
|
||||
_k32.SetEvent.argtypes, _k32.SetEvent.restype = [wt.HANDLE], wt.BOOL
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
EVENT_MODIFY_STATE = 0x2
|
||||
|
||||
|
||||
def http(method: str, url: str, body: dict | None = None, headers: dict | None = None,
|
||||
timeout: float = 3) -> tuple[int, bytes]:
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(url, data=data, method=method, headers={
|
||||
**({"Content-Type": "application/json"} if body is not None else {}), **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()
|
||||
|
||||
|
||||
def _clock(epoch: float | None) -> str | None:
|
||||
return None if epoch is None else datetime.fromtimestamp(epoch).strftime("%H:%M:%S")
|
||||
|
||||
|
||||
def _rate(tokens: float, ms: float) -> float | None:
|
||||
return round(tokens / ms * 1000, 1) if ms and tokens else None
|
||||
|
||||
|
||||
class Backend:
|
||||
key = "" # also its path on The Kurgan's web server: /<key>/
|
||||
label = ""
|
||||
stop_timeout = 10.0
|
||||
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self.lock = threading.Lock()
|
||||
self.status: dict = self.offline()
|
||||
self.public = "http://127.0.0.1:8080" # The Kurgan's web server; set by the service
|
||||
|
||||
# -- configuration
|
||||
@property
|
||||
def port(self) -> int:
|
||||
"""Where the server listens, on 127.0.0.1, behind The Kurgan."""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def prefix(self) -> str:
|
||||
"""The path the server itself serves under ("" = the root)."""
|
||||
return ""
|
||||
|
||||
def proxy_headers(self) -> dict:
|
||||
"""Headers The Kurgan's proxy sets on every request it passes to this server."""
|
||||
return {}
|
||||
|
||||
def variants(self) -> list[dict]:
|
||||
return []
|
||||
|
||||
def variant(self) -> str | None:
|
||||
return None
|
||||
|
||||
def model_label(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
def model_ids(self) -> list[str]:
|
||||
"""The model ids its /v1/models lists (answered by The Kurgan while the server is stopped)."""
|
||||
raise NotImplementedError
|
||||
|
||||
def links(self) -> dict:
|
||||
return {"chat": f"{self.public}/{self.key}/", "api": f"{self.public}/{self.key}/v1",
|
||||
"internal": f"http://127.0.0.1:{self.port}{self.prefix}/"}
|
||||
|
||||
def check_files(self) -> str | None:
|
||||
"""A reason it can't start (missing file), or None."""
|
||||
return None
|
||||
|
||||
# -- process
|
||||
def command(self) -> tuple[list[str], str, str]:
|
||||
"""(argv, working directory, log file for stdout/stderr)."""
|
||||
raise NotImplementedError
|
||||
|
||||
def before_start(self) -> None:
|
||||
pass
|
||||
|
||||
def request_stop(self, child) -> None:
|
||||
child.kill()
|
||||
|
||||
# -- monitoring
|
||||
@staticmethod
|
||||
def offline() -> dict:
|
||||
return {"model": {"state": "offline", "detail": "", "id": None, "context": None},
|
||||
"live": None, "requests": [], "averages": {"prefill_tps": None, "decode_tps": None, "requests": 0}}
|
||||
|
||||
def poll(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def mark_offline(self) -> None:
|
||||
with self.lock:
|
||||
self.status = self.offline()
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
with self.lock:
|
||||
return json.loads(json.dumps(self.status))
|
||||
|
||||
def load(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def unload(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class StrataBackend(Backend):
|
||||
key = "strata"
|
||||
label = "Strata"
|
||||
stop_timeout = 45.0 # Strata's own --shutdown-timeout is 30 s
|
||||
|
||||
def __init__(self, settings):
|
||||
super().__init__(settings)
|
||||
self._stop_name: str | None = None
|
||||
self._starts = 0
|
||||
|
||||
@property
|
||||
def root(self) -> str:
|
||||
return self.settings.get("ai", "strata_root", config.STRATA_ROOT)
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
return self.settings.get("ai", "strata_port", config.STRATA_PORT)
|
||||
|
||||
def variant(self) -> str:
|
||||
return self.settings.get("ai", "strata_model")
|
||||
|
||||
def variants(self) -> list[dict]:
|
||||
return [{"key": k, "label": label} for k, (label, _, _) in config.STRATA_MODELS.items()]
|
||||
|
||||
def model_label(self) -> str:
|
||||
return config.STRATA_MODELS[self.variant()][0]
|
||||
|
||||
def model_ids(self) -> list[str]:
|
||||
return [config.STRATA_MODELS[self.variant()][2]]
|
||||
|
||||
def _python(self) -> str:
|
||||
return os.path.join(self.root, "terminal", ".venv", "Scripts", "pythonw.exe")
|
||||
|
||||
def check_files(self) -> str | None:
|
||||
config_file = os.path.join(self.root, "terminal", config.STRATA_MODELS[self.variant()][1])
|
||||
for path in (self._python(), config_file):
|
||||
if not os.path.exists(path):
|
||||
return f"Not found: {path}"
|
||||
return None
|
||||
|
||||
def command(self) -> tuple[list[str], str, str]:
|
||||
self._starts += 1
|
||||
self._stop_name = f"Local\\KurganStrataStop-{os.getpid()}-{self._starts}"
|
||||
host = os.path.join(paths.PACKAGE_DIR, "ai", "strata_host.py")
|
||||
argv = [self._python(), host, "--root", self.root, "--config", config.STRATA_MODELS[self.variant()][1],
|
||||
"--port", str(self.port), "--idle-unload", str(config.STRATA_IDLE_UNLOAD),
|
||||
"--stop-event", self._stop_name]
|
||||
return argv, os.path.join(self.root, "terminal"), os.path.join(LOG_DIR, "strata-host.log")
|
||||
|
||||
def request_stop(self, child) -> None:
|
||||
"""Ask Strata to shut down cleanly; the service kills it if it takes too long."""
|
||||
handle = _k32.OpenEventW(EVENT_MODIFY_STATE, False, self._stop_name) if self._stop_name else None
|
||||
if not handle:
|
||||
log.warning("Strata's stop event isn't available; ending it instead")
|
||||
child.kill()
|
||||
return
|
||||
try:
|
||||
_k32.SetEvent(handle)
|
||||
finally:
|
||||
_k32.CloseHandle(handle)
|
||||
|
||||
def _url(self, path: str) -> str:
|
||||
return f"http://127.0.0.1:{self.port}{path}"
|
||||
|
||||
def poll(self) -> None:
|
||||
code, body = http("GET", self._url("/health"))
|
||||
if code != 200:
|
||||
raise ValueError(f"/health returned HTTP {code}")
|
||||
health = json.loads(body)
|
||||
code, body = http("GET", self._url("/metrics"), headers={"Accept": "application/json"})
|
||||
metrics = json.loads(body) if code == 200 else {}
|
||||
live_in = metrics.get("live") or {}
|
||||
state = live_in.get("state") or ("idle" if health.get("loaded") else "unloaded")
|
||||
live = None
|
||||
if state in ("reading", "generating"):
|
||||
read, total = live_in.get("prompt_read"), live_in.get("prompt_total")
|
||||
live = {"phase": state, "read": read, "total": total or live_in.get("prompt_tokens"),
|
||||
"progress": round(read / total, 3) if read is not None and total else None,
|
||||
"generated": live_in.get("generated"), "tok_s": live_in.get("tok_s"),
|
||||
"elapsed": live_in.get("elapsed_s"), "queued": live_in.get("queued")}
|
||||
requests = []
|
||||
for r in (metrics.get("requests") or [])[:KEEP_REQUESTS]:
|
||||
prompt, reused = r.get("prompt_tokens") or 0, r.get("reused") or 0
|
||||
requests.append({"time": _clock(r.get("time")), "status": r.get("finish") or "ok",
|
||||
"prompt": prompt, "reused": reused, "output": r.get("output_tokens") or 0,
|
||||
"prefill_tps": _rate(prompt - reused, r.get("prompt_ms") or 0),
|
||||
"decode_tps": r.get("decode_tok_s"), "duration": r.get("duration_s")})
|
||||
totals = metrics.get("totals") or {}
|
||||
engine = metrics.get("engine") or {}
|
||||
status = {
|
||||
"model": {"state": state, "detail": "", "id": health.get("model"),
|
||||
"context": health.get("max_context"), "engine": engine.get("version")},
|
||||
"live": live, "requests": requests,
|
||||
"averages": {"prefill_tps": _rate((totals.get("prompt_tokens") or 0) - (totals.get("reused") or 0),
|
||||
totals.get("prompt_ms") or 0),
|
||||
"decode_tps": _rate(totals.get("output_tokens") or 0, totals.get("decode_ms") or 0),
|
||||
"requests": totals.get("requests") or 0},
|
||||
}
|
||||
with self.lock:
|
||||
self.status = status
|
||||
|
||||
def load(self) -> None:
|
||||
code, body = http("POST", self._url("/load"), {}, timeout=600)
|
||||
log.info("Strata load: HTTP %s %s", code, body[:200])
|
||||
if code != 200:
|
||||
raise RuntimeError(_error_text(body) or f"Strata load failed (HTTP {code})")
|
||||
|
||||
def unload(self) -> None:
|
||||
code, body = http("POST", self._url("/unload"), {}, timeout=120)
|
||||
log.info("Strata unload: HTTP %s %s", code, body[:200])
|
||||
if code == 409:
|
||||
raise RuntimeError("Strata is answering a request; unload it when it finishes.")
|
||||
if code != 200:
|
||||
raise RuntimeError(_error_text(body) or f"Strata unload failed (HTTP {code})")
|
||||
|
||||
|
||||
def _error_text(body: bytes) -> str | None:
|
||||
try:
|
||||
error = json.loads(body).get("error")
|
||||
return error.get("message") if isinstance(error, dict) else str(error) if error else None
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
# --- llama.cpp log parsing (ported from the Qwen4 service) -------------------------------
|
||||
|
||||
RE_START = re.compile(r"task (\d+) \| processing task")
|
||||
RE_PREFILL = re.compile(r"task (\d+) \| prompt processing, n_tokens =\s*(\d+), progress =\s*([\d.]+), "
|
||||
r"t =\s*([\d.]+) s / ([\d.]+) tokens per second")
|
||||
RE_GEN = re.compile(r"task (\d+) \| n_gen =\s*(\d+), tg =\s*([\d.]+) t/s, tg_3s =\s*([\d.]+) t/s")
|
||||
RE_PROMPT_DONE = re.compile(r"task (\d+) \| prompt eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second")
|
||||
RE_EVAL_DONE = re.compile(r"task (\d+) \|\s+eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second")
|
||||
RE_STOP = re.compile(r"task (\d+) \| stop processing: n_tokens =\s*(\d+), truncated = (\d)")
|
||||
|
||||
|
||||
class LlamaLog:
|
||||
"""Follows llama-server's log for the request in progress and the finished ones."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.lock = threading.Lock()
|
||||
self.current: dict | None = None
|
||||
self.requests: collections.deque[dict] = collections.deque(maxlen=KEEP_REQUESTS)
|
||||
|
||||
def feed(self, line: str, now: float | None = None) -> None:
|
||||
now = time.time() if now is None else now
|
||||
with self.lock:
|
||||
if match := RE_START.search(line):
|
||||
self.current = {"start": now, "phase": "reading", "progress": 0.0, "read": 0, "generated": 0,
|
||||
"prefill_tps": None, "decode_tps": None}
|
||||
return
|
||||
current = self.current
|
||||
if current is None:
|
||||
return
|
||||
if match := RE_PREFILL.search(line):
|
||||
current.update(phase="reading", read=int(match[2]), progress=float(match[3]),
|
||||
prefill_tps=float(match[5]))
|
||||
elif match := RE_GEN.search(line):
|
||||
current.update(phase="generating", generated=int(match[2]), decode_tps=float(match[4]))
|
||||
elif match := RE_PROMPT_DONE.search(line):
|
||||
current.update(prompt_ms=float(match[2]), read=int(match[3]), prefill_final=float(match[4]))
|
||||
elif match := RE_EVAL_DONE.search(line):
|
||||
current.update(decode_ms=float(match[2]), generated=int(match[3]), decode_final=float(match[4]))
|
||||
elif match := RE_STOP.search(line):
|
||||
context = int(match[2])
|
||||
read, generated = current.get("read", 0), current.get("generated", 0)
|
||||
cached = max(0, context - read - generated)
|
||||
self.requests.appendleft({
|
||||
"time": datetime.fromtimestamp(now).strftime("%H:%M:%S"),
|
||||
"status": "truncated" if match[3] == "1" else "ok",
|
||||
"prompt": cached + read, "reused": cached, "output": generated,
|
||||
"prefill_tps": current.get("prefill_final"), "decode_tps": current.get("decode_final"),
|
||||
"duration": round(now - current["start"], 1),
|
||||
"prompt_ms": current.get("prompt_ms", 0.0), "decode_ms": current.get("decode_ms", 0.0),
|
||||
})
|
||||
self.current = None
|
||||
|
||||
def reset(self) -> None:
|
||||
with self.lock:
|
||||
self.current = None
|
||||
|
||||
def snapshot(self) -> tuple[dict | None, list[dict], dict]:
|
||||
with self.lock:
|
||||
requests = list(self.requests)
|
||||
current = dict(self.current) if self.current else None
|
||||
live = None
|
||||
if current:
|
||||
live = {"phase": current["phase"], "progress": current.get("progress"), "read": current.get("read"),
|
||||
"total": None, "generated": current.get("generated"),
|
||||
"tok_s": current.get("decode_tps") if current["phase"] == "generating" else current.get("prefill_tps"),
|
||||
"elapsed": round(time.time() - current["start"], 1), "queued": None}
|
||||
prompt_ms = sum(r["prompt_ms"] for r in requests)
|
||||
decode_ms = sum(r["decode_ms"] for r in requests)
|
||||
averages = {"prefill_tps": _rate(sum(r["prompt"] - r["reused"] for r in requests), prompt_ms),
|
||||
"decode_tps": _rate(sum(r["output"] for r in requests), decode_ms),
|
||||
"requests": len(requests)}
|
||||
public = [{k: v for k, v in r.items() if k not in ("prompt_ms", "decode_ms")} for r in requests]
|
||||
return live, public, averages
|
||||
|
||||
def follow(self, path_fn, stop: threading.Event) -> None:
|
||||
"""Tail the file path_fn() returns, reopening it when it is replaced or truncated."""
|
||||
handle, identity, buffer, path = None, None, b"", None
|
||||
while not stop.is_set():
|
||||
try:
|
||||
wanted = path_fn()
|
||||
if wanted != path:
|
||||
if handle:
|
||||
handle.close()
|
||||
handle, identity, buffer, path = None, None, b"", wanted
|
||||
stat = os.stat(path)
|
||||
if handle is None or (stat.st_ino, stat.st_ctime_ns) != identity or stat.st_size < handle.tell():
|
||||
if handle:
|
||||
handle.close()
|
||||
handle = open(path, "rb")
|
||||
if identity is None:
|
||||
handle.seek(0, os.SEEK_END) # don't replay an old log when first attaching
|
||||
identity, buffer = (stat.st_ino, stat.st_ctime_ns), b""
|
||||
chunk = handle.read()
|
||||
except (OSError, TypeError):
|
||||
chunk = b""
|
||||
if not chunk:
|
||||
stop.wait(0.5)
|
||||
continue
|
||||
buffer += chunk
|
||||
*lines, buffer = buffer.split(b"\n")
|
||||
for line in lines:
|
||||
self.feed(line.decode("utf-8", "replace"))
|
||||
if handle:
|
||||
handle.close()
|
||||
|
||||
|
||||
class LlamaBackend(Backend):
|
||||
key = "llama"
|
||||
label = "llama.cpp"
|
||||
stop_timeout = 10.0
|
||||
LEGACY_LOG = r"D:\AI\models\qwen4-35b-a3b\service\logs\llama-server.log" # while the Qwen4 service runs it
|
||||
|
||||
def __init__(self, settings):
|
||||
super().__init__(settings)
|
||||
self.logparser = LlamaLog()
|
||||
self.owned = False # set by the service: True when The Kurgan started the running server
|
||||
self.load_started: float | None = None
|
||||
self.last_load_seconds: float | None = None
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
return self.settings.get("ai", "llama_port", config.LLAMA_PORT)
|
||||
|
||||
@property
|
||||
def server(self) -> str:
|
||||
return self.settings.get("ai", "llama_server", config.LLAMA_SERVER)
|
||||
|
||||
@property
|
||||
def presets(self) -> str:
|
||||
return self.settings.get("ai", "llama_presets", config.LLAMA_PRESETS)
|
||||
|
||||
@property
|
||||
def model(self) -> str:
|
||||
return self.settings.get("ai", "llama_model", config.LLAMA_MODEL)
|
||||
|
||||
@property
|
||||
def prefix(self) -> str:
|
||||
# The Qwen4 service's own server (before it was retired) serves from the root.
|
||||
return config.LLAMA_PREFIX if self.owned else ""
|
||||
|
||||
def proxy_headers(self) -> dict:
|
||||
# The proxy is the gate (see kurgan/web/proxy.py), so clients there need no key; the key
|
||||
# stays on the server's own port, where a web page could otherwise reach it.
|
||||
return {"Authorization": f"Bearer {config.LLAMA_API_KEY}"}
|
||||
|
||||
def model_label(self) -> str:
|
||||
return config.LLAMA_LABEL if self.model == config.LLAMA_MODEL else self.model
|
||||
|
||||
def model_ids(self) -> list[str]:
|
||||
return [self.model]
|
||||
|
||||
@property
|
||||
def log_path(self) -> str:
|
||||
return os.path.join(LOG_DIR, "llama-server.log")
|
||||
|
||||
def current_log(self) -> str:
|
||||
return self.log_path if self.owned else self.LEGACY_LOG
|
||||
|
||||
def check_files(self) -> str | None:
|
||||
for path in (self.server, self.presets):
|
||||
if not os.path.exists(path):
|
||||
return f"Not found: {path}"
|
||||
return None
|
||||
|
||||
def before_start(self) -> None:
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
try:
|
||||
if os.path.exists(self.log_path):
|
||||
os.replace(self.log_path, os.path.join(LOG_DIR, "llama-server.prev.log"))
|
||||
except OSError as e:
|
||||
log.warning("Could not rotate llama-server.log: %s", e)
|
||||
self.logparser.reset()
|
||||
|
||||
def command(self) -> tuple[list[str], str, str]:
|
||||
argv = [self.server, "--models-preset", self.presets, "--models-max", "1", "--host", "127.0.0.1",
|
||||
"--port", str(self.port), "--api-prefix", config.LLAMA_PREFIX, "--api-key", config.LLAMA_API_KEY,
|
||||
"--metrics"]
|
||||
return argv, os.path.dirname(self.presets), self.log_path
|
||||
|
||||
def _api(self, path: str, body: dict | None = None, timeout: float = 3) -> tuple[int, bytes]:
|
||||
return http("GET" if body is None else "POST", f"http://127.0.0.1:{self.port}{self.prefix}{path}", body,
|
||||
{"Authorization": f"Bearer {config.LLAMA_API_KEY}"}, timeout)
|
||||
|
||||
def _model_entry(self) -> dict:
|
||||
code, body = self._api("/models")
|
||||
if code != 200:
|
||||
raise ValueError(f"/models returned HTTP {code}")
|
||||
return next(m for m in json.loads(body)["data"] if m["id"] == self.model)
|
||||
|
||||
def poll(self) -> None:
|
||||
entry = self._model_entry()
|
||||
state = entry["status"]["value"]
|
||||
live, requests, averages = self.logparser.snapshot()
|
||||
if state == "loading" and self.load_started is None:
|
||||
self.load_started = time.time()
|
||||
elif state != "loading" and self.load_started is not None:
|
||||
if state == "loaded":
|
||||
self.last_load_seconds = round(time.time() - self.load_started, 1)
|
||||
self.load_started = None
|
||||
if state == "loaded":
|
||||
state = live["phase"] if live else "idle"
|
||||
else:
|
||||
live = None
|
||||
detail = entry["status"].get("failed_reason", "") if state == "failed" else ""
|
||||
if state == "loading" and self.load_started:
|
||||
detail = f"{time.time() - self.load_started:.0f} s"
|
||||
status = {"model": {"state": state, "detail": detail, "id": self.model, "context": 262144,
|
||||
"last_load_seconds": self.last_load_seconds},
|
||||
"live": live, "requests": requests, "averages": averages}
|
||||
with self.lock:
|
||||
self.status = status
|
||||
|
||||
def load(self) -> None:
|
||||
if self._model_entry()["status"]["value"] == "sleeping":
|
||||
# A sleeping instance only wakes on a task, so restart it to load immediately.
|
||||
self._api("/models/unload", {"model": self.model}, timeout=30)
|
||||
for _ in range(60):
|
||||
if self._model_entry()["status"]["value"] == "unloaded":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
code, body = self._api("/models/load", {"model": self.model}, timeout=30)
|
||||
log.info("llama load: HTTP %s %s", code, body[:200])
|
||||
if code != 200:
|
||||
raise RuntimeError(_error_text(body) or f"llama.cpp load failed (HTTP {code})")
|
||||
|
||||
def unload(self) -> None:
|
||||
code, body = self._api("/models/unload", {"model": self.model}, timeout=30)
|
||||
log.info("llama unload: HTTP %s %s", code, body[:200])
|
||||
if code != 200:
|
||||
raise RuntimeError(_error_text(body) or f"llama.cpp unload failed (HTTP {code})")
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Defaults for the two local LLM servers. Paths and ports can be overridden in settings.json ("ai").
|
||||
|
||||
Clients reach both through The Kurgan's web server: http://127.0.0.1:8080/strata/v1 and
|
||||
http://127.0.0.1:8080/llama/v1 (see kurgan/web/proxy.py). The ports below are where each server
|
||||
listens on 127.0.0.1 behind it; clients shouldn't use them directly.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
BACKENDS = ("strata", "llama") # also each server's path on The Kurgan's web server: /strata/, /llama/
|
||||
|
||||
# A server nobody has used for this long is stopped; the next request starts it again (0 = never).
|
||||
IDLE_STOP_MINUTES = 40
|
||||
|
||||
# Strata (github.com/Niko1221/Strata), a git clone with its own venv in terminal\.
|
||||
STRATA_ROOT = r"D:\AI\Strata"
|
||||
STRATA_PORT = 8082
|
||||
STRATA_MODELS = { # key: (label, run config in terminal\, model id it serves)
|
||||
"q5": ("OrcaRouter Qwen3.8 Flash Next Q5_K_M", "strata-orca-q5_k_m.json",
|
||||
"orcarouter-qwen3.8-flash-next-uncensored-q5_k_m"),
|
||||
"iq3": ("OrcaRouter Qwen3.8 Flash Next IQ3_XXS", "strata-orca-iq3_xxs.json",
|
||||
"orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs"),
|
||||
}
|
||||
STRATA_DEFAULT_MODEL = "q5"
|
||||
STRATA_IDLE_UNLOAD = 2000 # seconds idle before the model leaves VRAM; it reloads on the next request
|
||||
|
||||
# llama.cpp's llama-server in router mode, with the model defined in a presets file.
|
||||
LLAMA_SERVER = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "llama.cpp", "b12977",
|
||||
"llama-server.exe")
|
||||
LLAMA_PRESETS = r"D:\AI\models\qwen4-35b-a3b\service\presets.ini"
|
||||
LLAMA_MODEL = "qwen4-35b-a3b-q5"
|
||||
LLAMA_LABEL = "Qwen4 35B-A3B UD-Q5_K_XL"
|
||||
LLAMA_PORT = 8083
|
||||
LLAMA_API_KEY = "sk-local"
|
||||
LLAMA_PREFIX = "/llama" # --api-prefix: llama-server serves its API and chat page under this path
|
||||
@@ -0,0 +1,449 @@
|
||||
"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated.
|
||||
|
||||
The Kurgan needs admin rights for PawnIO (CPU sensors, top fans, RAM lighting), but the LLM
|
||||
servers never did: they ran from non-elevated tasks before. How a server is started:
|
||||
|
||||
- The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own
|
||||
token, through CreateProcessWithTokenW. The server is then exactly what Explorer would have
|
||||
started: medium integrity, not elevated, in the desktop's logon session.
|
||||
- No desktop shell yet (just after logon; see desktop_ready) or The Kurgan not elevated (tests,
|
||||
--demo): a "normal user" token from the Safer API (Administrators made deny-only, admin
|
||||
privileges removed, medium integrity). Windows still counts that token as part of the elevated
|
||||
logon session, so the shell's token is preferred.
|
||||
|
||||
Each server gets its own job object that kills everything in it when The Kurgan closes the
|
||||
job, including the model processes the server starts itself; a crashed Kurgan leaves no
|
||||
orphan holding VRAM or a port. stdout/stderr go to a log file. The Safer path passes an explicit
|
||||
handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take
|
||||
one; Python makes its handles non-inheritable, and launches are serialised, so in practice the
|
||||
same two are all the child gets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
|
||||
|
||||
SAFER_SCOPEID_USER = 2
|
||||
SAFER_LEVELID_NORMALUSER = 0x20000
|
||||
SAFER_LEVEL_OPEN = 1
|
||||
TOKEN_INTEGRITY_LEVEL = 25
|
||||
TOKEN_ELEVATION = 20
|
||||
SE_GROUP_INTEGRITY = 0x20
|
||||
MEDIUM_INTEGRITY_SID = "S-1-16-8192"
|
||||
|
||||
CREATE_SUSPENDED = 0x4
|
||||
CREATE_NEW_PROCESS_GROUP = 0x200
|
||||
CREATE_UNICODE_ENVIRONMENT = 0x400
|
||||
EXTENDED_STARTUPINFO_PRESENT = 0x80000
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES = 0x1, 0x100
|
||||
SW_HIDE = 0
|
||||
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
|
||||
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
||||
GENERIC_READ, GENERIC_WRITE = 0x80000000, 0x40000000
|
||||
FILE_APPEND_DATA = 0x4
|
||||
SYNCHRONIZE = 0x100000
|
||||
FILE_SHARE_ALL = 0x7
|
||||
OPEN_EXISTING, OPEN_ALWAYS = 3, 4
|
||||
INVALID_HANDLE = wt.HANDLE(-1).value
|
||||
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
|
||||
STILL_ACTIVE = 259
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
TOKEN_QUERY = 0x8
|
||||
TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_ADJUST_DEFAULT, TOKEN_ADJUST_SESSIONID = 0x1, 0x2, 0x80, 0x100
|
||||
SECURITY_IMPERSONATION, TOKEN_PRIMARY = 2, 1
|
||||
ERROR_INVALID_PARAMETER = 87
|
||||
|
||||
|
||||
class SecurityAttributes(ctypes.Structure):
|
||||
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", wt.LPVOID), ("bInheritHandle", wt.BOOL)]
|
||||
|
||||
|
||||
class StartupInfo(ctypes.Structure):
|
||||
_fields_ = [("cb", wt.DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR), ("lpTitle", wt.LPWSTR),
|
||||
("dwX", wt.DWORD), ("dwY", wt.DWORD), ("dwXSize", wt.DWORD), ("dwYSize", wt.DWORD),
|
||||
("dwXCountChars", wt.DWORD), ("dwYCountChars", wt.DWORD), ("dwFillAttribute", wt.DWORD),
|
||||
("dwFlags", wt.DWORD), ("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD),
|
||||
("lpReserved2", ctypes.c_void_p), ("hStdInput", wt.HANDLE), ("hStdOutput", wt.HANDLE),
|
||||
("hStdError", wt.HANDLE)]
|
||||
|
||||
|
||||
class StartupInfoEx(ctypes.Structure):
|
||||
_fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", ctypes.c_void_p)]
|
||||
|
||||
|
||||
class ProcessInformation(ctypes.Structure):
|
||||
_fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD),
|
||||
("dwThreadId", wt.DWORD)]
|
||||
|
||||
|
||||
class SidAndAttributes(ctypes.Structure):
|
||||
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
|
||||
|
||||
|
||||
class BasicLimits(ctypes.Structure):
|
||||
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", wt.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wt.DWORD),
|
||||
("Affinity", ctypes.c_size_t), ("PriorityClass", wt.DWORD), ("SchedulingClass", wt.DWORD)]
|
||||
|
||||
|
||||
class ExtendedLimits(ctypes.Structure):
|
||||
_fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", ctypes.c_uint64 * 6),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
||||
|
||||
|
||||
_adv.SaferCreateLevel.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.LPVOID]
|
||||
_adv.SaferCreateLevel.restype = wt.BOOL
|
||||
_adv.SaferComputeTokenFromLevel.argtypes = [wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.LPVOID]
|
||||
_adv.SaferComputeTokenFromLevel.restype = wt.BOOL
|
||||
_adv.SaferCloseLevel.argtypes = [wt.HANDLE]
|
||||
_adv.SaferCloseLevel.restype = wt.BOOL
|
||||
_adv.ConvertStringSidToSidW.argtypes = [wt.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]
|
||||
_adv.ConvertStringSidToSidW.restype = wt.BOOL
|
||||
_adv.GetLengthSid.argtypes = [ctypes.c_void_p]
|
||||
_adv.GetLengthSid.restype = wt.DWORD
|
||||
_adv.SetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
|
||||
_adv.SetTokenInformation.restype = wt.BOOL
|
||||
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)]
|
||||
_adv.GetTokenInformation.restype = wt.BOOL
|
||||
_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
|
||||
_adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)
|
||||
_adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD]
|
||||
_adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD)
|
||||
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
||||
_adv.OpenProcessToken.restype = wt.BOOL
|
||||
_adv.CreateProcessAsUserW.argtypes = [wt.HANDLE, wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD,
|
||||
wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
|
||||
_adv.CreateProcessAsUserW.restype = wt.BOOL
|
||||
_k32.LocalFree.argtypes = [wt.HLOCAL]
|
||||
_k32.LocalFree.restype = wt.HLOCAL
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
_k32.CloseHandle.restype = wt.BOOL
|
||||
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD,
|
||||
wt.DWORD, wt.HANDLE]
|
||||
_k32.CreateFileW.restype = wt.HANDLE
|
||||
_k32.CreateJobObjectW.argtypes = [wt.LPVOID, wt.LPCWSTR]
|
||||
_k32.CreateJobObjectW.restype = wt.HANDLE
|
||||
_k32.SetInformationJobObject.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
|
||||
_k32.SetInformationJobObject.restype = wt.BOOL
|
||||
_k32.AssignProcessToJobObject.argtypes = [wt.HANDLE, wt.HANDLE]
|
||||
_k32.AssignProcessToJobObject.restype = wt.BOOL
|
||||
_k32.TerminateJobObject.argtypes = [wt.HANDLE, wt.UINT]
|
||||
_k32.TerminateJobObject.restype = wt.BOOL
|
||||
_k32.TerminateProcess.argtypes = [wt.HANDLE, wt.UINT]
|
||||
_k32.TerminateProcess.restype = wt.BOOL
|
||||
_k32.ResumeThread.argtypes = [wt.HANDLE]
|
||||
_k32.ResumeThread.restype = wt.DWORD
|
||||
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||
_k32.WaitForSingleObject.restype = wt.DWORD
|
||||
_k32.GetExitCodeProcess.argtypes = [wt.HANDLE, ctypes.POINTER(wt.DWORD)]
|
||||
_k32.GetExitCodeProcess.restype = wt.BOOL
|
||||
_k32.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wt.DWORD, wt.DWORD, ctypes.POINTER(ctypes.c_size_t)]
|
||||
_k32.InitializeProcThreadAttributeList.restype = wt.BOOL
|
||||
_k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_size_t, wt.LPVOID, ctypes.c_size_t,
|
||||
wt.LPVOID, wt.LPVOID]
|
||||
_k32.UpdateProcThreadAttribute.restype = wt.BOOL
|
||||
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
|
||||
_k32.DeleteProcThreadAttributeList.restype = None
|
||||
_k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD]
|
||||
_k32.OpenProcess.restype = wt.HANDLE
|
||||
_k32.GetCurrentProcess.restype = wt.HANDLE
|
||||
_adv.DuplicateTokenEx.argtypes = [wt.HANDLE, wt.DWORD, wt.LPVOID, ctypes.c_int, ctypes.c_int, ctypes.POINTER(wt.HANDLE)]
|
||||
_adv.DuplicateTokenEx.restype = wt.BOOL
|
||||
_adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR,
|
||||
ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
|
||||
_adv.CreateProcessWithTokenW.restype = wt.BOOL
|
||||
_u32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
_u32.GetShellWindow.restype = wt.HWND
|
||||
_u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
|
||||
_u32.GetWindowThreadProcessId.restype = wt.DWORD
|
||||
|
||||
_launch_lock = threading.Lock()
|
||||
|
||||
|
||||
def _check(ok, what: str):
|
||||
if not ok:
|
||||
raise ctypes.WinError(ctypes.get_last_error(), f"{what} failed")
|
||||
return ok
|
||||
|
||||
|
||||
def _normal_user_token() -> wt.HANDLE:
|
||||
"""A primary token like this process's, minus admin rights, at medium integrity."""
|
||||
level, token = wt.HANDLE(), wt.HANDLE()
|
||||
_check(_adv.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN,
|
||||
ctypes.byref(level), None), "SaferCreateLevel")
|
||||
try:
|
||||
_check(_adv.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None),
|
||||
"SaferComputeTokenFromLevel")
|
||||
finally:
|
||||
_adv.SaferCloseLevel(level)
|
||||
sid = ctypes.c_void_p()
|
||||
try:
|
||||
_check(_adv.ConvertStringSidToSidW(MEDIUM_INTEGRITY_SID, ctypes.byref(sid)), "ConvertStringSidToSid")
|
||||
label = SidAndAttributes(sid, SE_GROUP_INTEGRITY)
|
||||
_check(_adv.SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label),
|
||||
ctypes.sizeof(label) + _adv.GetLengthSid(sid)), "SetTokenInformation")
|
||||
except OSError:
|
||||
_k32.CloseHandle(token)
|
||||
raise
|
||||
finally:
|
||||
if sid:
|
||||
_k32.LocalFree(sid)
|
||||
return token
|
||||
|
||||
|
||||
def _describe_token(token: wt.HANDLE) -> dict:
|
||||
size = wt.DWORD()
|
||||
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
|
||||
buf = ctypes.create_string_buffer(size.value)
|
||||
_check(_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, size, ctypes.byref(size)),
|
||||
"GetTokenInformation(IntegrityLevel)")
|
||||
sid = SidAndAttributes.from_buffer(buf).Sid
|
||||
rid = _adv.GetSidSubAuthority(sid, _adv.GetSidSubAuthorityCount(sid)[0] - 1)[0]
|
||||
elevated = wt.DWORD()
|
||||
_check(_adv.GetTokenInformation(token, TOKEN_ELEVATION, ctypes.byref(elevated), 4, ctypes.byref(size)),
|
||||
"GetTokenInformation(Elevation)")
|
||||
names = {0x1000: "low", 0x2000: "medium", 0x2100: "medium-plus", 0x3000: "high", 0x4000: "system"}
|
||||
return {"integrity": names.get(rid, hex(rid)), "elevated": bool(elevated.value)}
|
||||
|
||||
|
||||
def token_info(process_handle=None) -> dict:
|
||||
"""{"integrity": "medium"|"high"|..., "elevated": bool} for a process (default: this one)."""
|
||||
token = wt.HANDLE()
|
||||
handle = process_handle if process_handle is not None else _k32.GetCurrentProcess()
|
||||
_check(_adv.OpenProcessToken(handle, TOKEN_QUERY, ctypes.byref(token)), "OpenProcessToken")
|
||||
try:
|
||||
return _describe_token(token)
|
||||
finally:
|
||||
_k32.CloseHandle(token)
|
||||
|
||||
|
||||
_ELEVATED: bool | None = None
|
||||
|
||||
|
||||
def elevated() -> bool:
|
||||
global _ELEVATED
|
||||
if _ELEVATED is None:
|
||||
_ELEVATED = token_info()["elevated"]
|
||||
return _ELEVATED
|
||||
|
||||
|
||||
def _desktop_token() -> wt.HANDLE | None:
|
||||
"""A primary copy of the desktop shell's token, or None if there is no (non-elevated) shell."""
|
||||
hwnd = _u32.GetShellWindow()
|
||||
if not hwnd:
|
||||
return None
|
||||
pid = wt.DWORD()
|
||||
_u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
|
||||
process = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value)
|
||||
if not process:
|
||||
return None
|
||||
shell, token = wt.HANDLE(), wt.HANDLE()
|
||||
try:
|
||||
if not _adv.OpenProcessToken(process, TOKEN_DUPLICATE | TOKEN_QUERY, ctypes.byref(shell)):
|
||||
return None
|
||||
try:
|
||||
_check(_adv.DuplicateTokenEx(shell, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE
|
||||
| TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, None,
|
||||
SECURITY_IMPERSONATION, TOKEN_PRIMARY, ctypes.byref(token)),
|
||||
"DuplicateTokenEx")
|
||||
finally:
|
||||
_k32.CloseHandle(shell)
|
||||
finally:
|
||||
_k32.CloseHandle(process)
|
||||
if _describe_token(token)["elevated"]: # someone runs Explorer elevated: no better than our own
|
||||
_k32.CloseHandle(token)
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
def desktop_ready() -> bool:
|
||||
"""True once servers can be started with the desktop's own token (always true when not elevated)."""
|
||||
if not elevated():
|
||||
return True
|
||||
token = _desktop_token()
|
||||
if token is None:
|
||||
return False
|
||||
_k32.CloseHandle(token)
|
||||
return True
|
||||
|
||||
|
||||
def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE:
|
||||
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
|
||||
handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None)
|
||||
if handle == INVALID_HANDLE or not handle:
|
||||
raise ctypes.WinError(ctypes.get_last_error(), f"Opening {path} failed")
|
||||
return handle
|
||||
|
||||
|
||||
def _environment_block(env: dict[str, str]) -> ctypes.Array:
|
||||
items = sorted(env.items(), key=lambda kv: kv[0].upper())
|
||||
text = "".join(f"{k}={v}\0" for k, v in items) + "\0"
|
||||
return ctypes.create_unicode_buffer(text, len(text))
|
||||
|
||||
|
||||
def child_environment(extra: dict[str, str] | None = None) -> dict[str, str]:
|
||||
env = dict(os.environ)
|
||||
# The Kurgan pins OpenBLAS to one thread for itself (see kurgan/__init__.py); the servers get the default.
|
||||
if env.get("KURGAN_PINNED_OPENBLAS") == "1":
|
||||
env.pop("OPENBLAS_NUM_THREADS", None)
|
||||
env.pop("KURGAN_PINNED_OPENBLAS", None)
|
||||
env.update(extra or {})
|
||||
return env
|
||||
|
||||
|
||||
class ChildProcess:
|
||||
"""A launched server: poll/wait/kill like subprocess.Popen, plus the job it runs in."""
|
||||
|
||||
def __init__(self, pid: int, process: wt.HANDLE, job: wt.HANDLE, argv: list[str]):
|
||||
self.pid = pid
|
||||
self.argv = argv
|
||||
self._process = process
|
||||
self._job = job
|
||||
self.returncode: int | None = None
|
||||
try:
|
||||
self.token = token_info(process)
|
||||
except OSError as e:
|
||||
log.warning("Could not read the token of process %s: %s", pid, e)
|
||||
self.token = {"integrity": "unknown", "elevated": None}
|
||||
|
||||
def poll(self) -> int | None:
|
||||
return self.wait(0)
|
||||
|
||||
def wait(self, timeout: float | None = None) -> int | None:
|
||||
if self.returncode is not None:
|
||||
return self.returncode
|
||||
if self._process is None:
|
||||
return None
|
||||
ms = 0xFFFFFFFF if timeout is None else max(0, int(timeout * 1000))
|
||||
if _k32.WaitForSingleObject(self._process, ms) != WAIT_OBJECT_0:
|
||||
return None
|
||||
code = wt.DWORD()
|
||||
_check(_k32.GetExitCodeProcess(self._process, ctypes.byref(code)), "GetExitCodeProcess")
|
||||
self.returncode = code.value
|
||||
return self.returncode
|
||||
|
||||
def kill(self) -> None:
|
||||
"""End the server and everything it started."""
|
||||
if self._job:
|
||||
_k32.TerminateJobObject(self._job, 1)
|
||||
elif self._process:
|
||||
_k32.TerminateProcess(self._process, 1)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the handles; closing the job also kills anything still in it."""
|
||||
for name in ("_process", "_job"):
|
||||
handle = getattr(self, name)
|
||||
if handle:
|
||||
_k32.CloseHandle(handle)
|
||||
setattr(self, name, None)
|
||||
|
||||
def __del__(self):
|
||||
try:
|
||||
self.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None,
|
||||
contained: bool = True) -> ChildProcess:
|
||||
"""Start argv as a normal user, windowless, with stdout/stderr appended to log_path (None: discarded).
|
||||
|
||||
contained: put it in its own kill-on-close job (servers). Without it the process outlives
|
||||
the returned handle (used to open the browser)."""
|
||||
if log_path is not None:
|
||||
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
||||
with _launch_lock:
|
||||
desktop = _desktop_token() if elevated() else None
|
||||
token = desktop or _normal_user_token()
|
||||
job = out = nul = None
|
||||
attributes = None
|
||||
try:
|
||||
if contained:
|
||||
job = _check(_k32.CreateJobObjectW(None, None), "CreateJobObject")
|
||||
limits = ExtendedLimits()
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
_check(_k32.SetInformationJobObject(job, JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
ctypes.byref(limits), ctypes.sizeof(limits)),
|
||||
"SetInformationJobObject")
|
||||
out = (_inheritable(log_path, FILE_APPEND_DATA | SYNCHRONIZE, OPEN_ALWAYS) if log_path is not None
|
||||
else _inheritable("NUL", GENERIC_WRITE, OPEN_EXISTING))
|
||||
nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING)
|
||||
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
|
||||
block = _environment_block(env if env is not None else child_environment())
|
||||
flags = CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
|
||||
pi = ProcessInformation()
|
||||
|
||||
if desktop:
|
||||
info = StartupInfo()
|
||||
info.cb = ctypes.sizeof(StartupInfo)
|
||||
info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
|
||||
info.wShowWindow = SW_HIDE
|
||||
info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out
|
||||
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd,
|
||||
ctypes.byref(info), ctypes.byref(pi))
|
||||
if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER:
|
||||
# Not every creation flag is accepted here; SW_HIDE still hides a console window.
|
||||
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block,
|
||||
cwd, ctypes.byref(info), ctypes.byref(pi))
|
||||
_check(ok, f"Starting {argv[0]}")
|
||||
else:
|
||||
size = ctypes.c_size_t()
|
||||
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
|
||||
attributes = ctypes.create_string_buffer(size.value)
|
||||
_check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)),
|
||||
"InitializeProcThreadAttributeList")
|
||||
handles = (wt.HANDLE * 2)(out, nul)
|
||||
_check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
|
||||
ctypes.sizeof(handles), None, None),
|
||||
"UpdateProcThreadAttribute")
|
||||
info = StartupInfoEx()
|
||||
info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx)
|
||||
info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
|
||||
info.StartupInfo.wShowWindow = SW_HIDE
|
||||
info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out
|
||||
info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
|
||||
_check(_adv.CreateProcessAsUserW(token, None, command, None, None, True,
|
||||
flags | EXTENDED_STARTUPINFO_PRESENT, block, cwd,
|
||||
ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}")
|
||||
if job and not _k32.AssignProcessToJobObject(job, pi.hProcess):
|
||||
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
||||
_k32.TerminateProcess(pi.hProcess, 1)
|
||||
_k32.CloseHandle(pi.hThread)
|
||||
_k32.CloseHandle(pi.hProcess)
|
||||
raise error
|
||||
_k32.ResumeThread(pi.hThread)
|
||||
_k32.CloseHandle(pi.hThread)
|
||||
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
|
||||
job = None # owned by the child object now
|
||||
log.info("Started %s (pid %s, %s token, %s integrity%s)", os.path.basename(argv[0]), child.pid,
|
||||
"desktop" if desktop else "restricted", child.token["integrity"],
|
||||
", ELEVATED" if child.token["elevated"] else "")
|
||||
return child
|
||||
finally:
|
||||
if attributes is not None:
|
||||
_k32.DeleteProcThreadAttributeList(attributes)
|
||||
for handle in (out, nul, job, token):
|
||||
if handle:
|
||||
_k32.CloseHandle(handle)
|
||||
|
||||
|
||||
def open_url(url: str) -> None:
|
||||
"""Open a web page in the default browser as the normal user, never elevated."""
|
||||
rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe")
|
||||
child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None,
|
||||
contained=False)
|
||||
child.close()
|
||||
@@ -0,0 +1,459 @@
|
||||
"""AI service: runs one LLM server at a time and swaps between them.
|
||||
|
||||
The selected server (settings "ai.active") is started as a normal-user child process and
|
||||
restarted if it crashes (5 crashes within 5 minutes pause restarts for 5 minutes). Swapping
|
||||
stops the running server completely first, so the two never share the GPU's memory.
|
||||
|
||||
Servers are also started on demand: a request through The Kurgan's web server
|
||||
(/strata/..., /llama/...; see kurgan/web/proxy.py) selects its server and waits until it
|
||||
answers. If the other server is busy (a request in flight, a reply being generated or a model
|
||||
loading), the request waits for it to finish rather than cutting it off. A server nobody has
|
||||
used for ai.idle_stop_minutes is stopped.
|
||||
|
||||
A server already listening on a port that The Kurgan didn't start (for example Strata's or
|
||||
the Qwen4 service's own tray, before they are retired) is shown as "external": it is
|
||||
monitored but never started, stopped or duplicated.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.ai import launcher
|
||||
from kurgan.ai.backends import Backend, LlamaBackend, StrataBackend
|
||||
from kurgan.ai.config import BACKENDS
|
||||
from kurgan.settings import Settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_iphlp = ctypes.WinDLL("iphlpapi")
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_iphlp.GetExtendedTcpTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, ctypes.c_int,
|
||||
wt.ULONG]
|
||||
_iphlp.GetExtendedTcpTable.restype = wt.DWORD
|
||||
_k32.OpenProcess.argtypes, _k32.OpenProcess.restype = [wt.DWORD, wt.BOOL, wt.DWORD], wt.HANDLE
|
||||
_k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)]
|
||||
_k32.QueryFullProcessImageNameW.restype = wt.BOOL
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
|
||||
|
||||
def port_in_use(port: int) -> bool:
|
||||
with socket.socket() as probe:
|
||||
probe.settimeout(0.3)
|
||||
return probe.connect_ex(("127.0.0.1", port)) == 0
|
||||
|
||||
|
||||
def port_owner(port: int) -> tuple[int, str] | None:
|
||||
"""(pid, executable name) of the process listening on 127.0.0.1:port, if any."""
|
||||
size = wt.DWORD(0)
|
||||
_iphlp.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 3, 0) # AF_INET, TCP_TABLE_OWNER_PID_LISTENER
|
||||
buf = ctypes.create_string_buffer(size.value)
|
||||
if _iphlp.GetExtendedTcpTable(buf, ctypes.byref(size), False, 2, 3, 0) != 0:
|
||||
return None
|
||||
count = ctypes.c_uint32.from_buffer(buf).value
|
||||
row = ctypes.c_uint32 * 6 # state, local addr, local port, remote addr, remote port, pid
|
||||
for i in range(count):
|
||||
state, _addr, lport, _raddr, _rport, pid = row.from_buffer(buf, 4 + i * ctypes.sizeof(row))
|
||||
if ((lport & 0xFF) << 8 | (lport >> 8) & 0xFF) == port:
|
||||
name = "?"
|
||||
handle = _k32.OpenProcess(launcher.PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
||||
if handle:
|
||||
try:
|
||||
text, length = ctypes.create_unicode_buffer(1024), wt.DWORD(1024)
|
||||
if _k32.QueryFullProcessImageNameW(handle, 0, text, ctypes.byref(length)):
|
||||
name = os.path.basename(text.value)
|
||||
finally:
|
||||
_k32.CloseHandle(handle)
|
||||
return pid, name
|
||||
return None
|
||||
|
||||
|
||||
class Slot:
|
||||
"""One backend and the process The Kurgan runs for it."""
|
||||
|
||||
def __init__(self, backend: Backend):
|
||||
self.backend = backend
|
||||
self.child: launcher.ChildProcess | None = None
|
||||
self.variant: str | None = None
|
||||
self.started_at: float | None = None
|
||||
self.stopping = False
|
||||
self.external: tuple[int, str] | None = None
|
||||
self.crashes: collections.deque[float] = collections.deque(maxlen=5)
|
||||
self.hold_until = 0.0
|
||||
self.restarts = 0
|
||||
self.error: str | None = None
|
||||
self.reachable = False
|
||||
|
||||
|
||||
class RouteError(Exception):
|
||||
"""A request for a server that can't be served now; status is the HTTP status to answer with."""
|
||||
|
||||
def __init__(self, message: str, status: int = 503):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
BUSY_STATES = ("loading", "reading", "generating")
|
||||
CLIENT_GONE = 499 # RouteError status: the client hung up while waiting (nginx's "client closed request")
|
||||
|
||||
|
||||
class AiService:
|
||||
BUSY_WAIT = 600.0 # how long a request waits for the other server to finish before giving up
|
||||
READY_WAIT = 120.0 # how long it waits for its own server to start answering
|
||||
|
||||
def __init__(self, settings: Settings, backends: list[Backend] | None = None):
|
||||
self.settings = settings
|
||||
backends = backends or [StrataBackend(settings), LlamaBackend(settings)]
|
||||
self.slots = {b.key: Slot(b) for b in backends}
|
||||
self._wake = threading.Event()
|
||||
self._lock = threading.Lock()
|
||||
self._cv = threading.Condition() # guards inflight/last_used; notified when a request ends
|
||||
self.inflight = {key: 0 for key in self.slots}
|
||||
self.last_used = {key: time.monotonic() for key in self.slots}
|
||||
self.transition: str | None = None
|
||||
self.action: str | None = None # "Loading model..." while a load/unload request runs
|
||||
self.message: str | None = None
|
||||
self._stop: threading.Event | None = None
|
||||
self._born = time.monotonic()
|
||||
|
||||
def set_public_url(self, url: str) -> None:
|
||||
"""The Kurgan's web server, which the links in the UI point to."""
|
||||
for slot in self.slots.values():
|
||||
slot.backend.public = url.rstrip("/")
|
||||
|
||||
# -- requests from the web UI (any thread)
|
||||
|
||||
def set_active(self, key: str | None, variant: str | None = None) -> None:
|
||||
if key is not None and key not in self.slots:
|
||||
raise ValueError(f"Unknown AI backend {key!r}")
|
||||
changes: dict = {"active": key}
|
||||
if variant is not None:
|
||||
changes["strata_model"] = variant
|
||||
self.settings.update("ai", **changes) # validates the variant
|
||||
log.info("AI backend selected: %s%s", key or "none", f" ({variant})" if variant else "")
|
||||
if key is not None:
|
||||
with self._cv:
|
||||
self.last_used[key] = time.monotonic() # a full idle period before it can stop
|
||||
self._wake.set()
|
||||
|
||||
# -- requests through the web server (any thread)
|
||||
|
||||
def _busy(self, key: str) -> bool:
|
||||
"""Serving or about to serve: a request in flight here, or a reply/model load in progress."""
|
||||
if self.inflight[key]:
|
||||
return True
|
||||
status = self.slots[key].backend.status
|
||||
return bool(status.get("live")) or status["model"]["state"] in BUSY_STATES
|
||||
|
||||
def claim(self, key: str, gone=None) -> Backend:
|
||||
"""Reserve key's server for one request: select it (stopping the other once that is idle)
|
||||
and wait until it answers. Always pair with release(key). gone(), if given, says whether
|
||||
the client has hung up; then the wait ends without switching anything."""
|
||||
if key not in self.slots:
|
||||
raise RouteError(f"Unknown AI server {key!r}", 404)
|
||||
slot = self.slots[key]
|
||||
deadline = time.monotonic() + self.BUSY_WAIT
|
||||
with self._cv:
|
||||
while True:
|
||||
active = self.settings.get("ai", "active")
|
||||
if active == key or slot.external is not None:
|
||||
break
|
||||
other = self.slots[active] if active else None
|
||||
if gone is not None and gone():
|
||||
raise RouteError(f"while waiting for {other.backend.label} to finish" if other is not None
|
||||
else f"before {slot.backend.label} was started", CLIENT_GONE)
|
||||
if other is None or other.external is not None or not self._busy(active):
|
||||
try:
|
||||
self.settings.update("ai", active=key)
|
||||
except OSError as e:
|
||||
raise RouteError(f"Couldn't save the AI selection: {e}", 500) from None
|
||||
log.info("%s requested by a client%s", slot.backend.label,
|
||||
f"; stopping {other.backend.label}" if other is not None and other.child else "")
|
||||
self._wake.set()
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RouteError(f"{other.backend.label} is still busy with another request; try again later.")
|
||||
self._cv.wait(1.0)
|
||||
self.inflight[key] += 1
|
||||
self.last_used[key] = time.monotonic()
|
||||
try:
|
||||
self._wait_ready(key, slot, gone)
|
||||
except BaseException:
|
||||
self.release(key)
|
||||
raise
|
||||
return slot.backend
|
||||
|
||||
def _wait_ready(self, key: str, slot: Slot, gone=None) -> None:
|
||||
start = time.monotonic()
|
||||
while True:
|
||||
running = slot.external is not None or (slot.child is not None and not slot.stopping)
|
||||
if running and port_in_use(slot.backend.port):
|
||||
return
|
||||
if self._stop is not None and self._stop.is_set():
|
||||
raise RouteError("The Kurgan is shutting down")
|
||||
if gone is not None and gone():
|
||||
raise RouteError(f"while waiting for {slot.backend.label} to start", CLIENT_GONE)
|
||||
waited = time.monotonic() - start
|
||||
if slot.external is None and self.settings.get("ai", "active") != key and waited > 3:
|
||||
raise RouteError(f"{slot.backend.label} was switched off in The Kurgan")
|
||||
if slot.child is None and slot.error and waited > 3:
|
||||
raise RouteError(slot.error)
|
||||
if waited >= self.READY_WAIT:
|
||||
raise RouteError(f"{slot.backend.label} didn't start within {self.READY_WAIT:.0f} s")
|
||||
time.sleep(0.25)
|
||||
|
||||
def release(self, key: str) -> None:
|
||||
with self._cv:
|
||||
self.inflight[key] = max(0, self.inflight[key] - 1)
|
||||
self.last_used[key] = time.monotonic()
|
||||
self._cv.notify_all()
|
||||
|
||||
def running(self, key: str) -> bool:
|
||||
"""The server answers now (started by The Kurgan or not)."""
|
||||
slot = self.slots[key]
|
||||
return slot.reachable and (slot.external is not None or (slot.child is not None and not slot.stopping))
|
||||
|
||||
def model_action(self, action: str) -> None:
|
||||
"""Load or unload the model of the running server (in the background)."""
|
||||
key = self.settings.get("ai", "active")
|
||||
if key is None or action not in ("load", "unload"):
|
||||
raise ValueError("No AI backend is selected" if key is None else f"Unknown action {action!r}")
|
||||
slot = self.slots[key]
|
||||
if not slot.reachable:
|
||||
raise ValueError(f"{slot.backend.label} isn't running yet")
|
||||
if self.action:
|
||||
raise ValueError(f"Busy: {self.action}")
|
||||
self.action = f"{'Loading' if action == 'load' else 'Unloading'} {slot.backend.label} model"
|
||||
|
||||
def run():
|
||||
try:
|
||||
getattr(slot.backend, action)()
|
||||
self.message = None
|
||||
except Exception as e:
|
||||
log.warning("%s failed: %s", self.action, e)
|
||||
self.message = f"{self.action} failed: {e}"
|
||||
finally:
|
||||
self.action = None
|
||||
|
||||
threading.Thread(target=run, name=f"ai-{action}", daemon=True).start()
|
||||
|
||||
# -- worker threads
|
||||
|
||||
def start(self, stop: threading.Event) -> list[threading.Thread]:
|
||||
self._stop = stop
|
||||
threads = [threading.Thread(target=self.run, args=(stop,), name="ai-supervisor", daemon=True),
|
||||
threading.Thread(target=self.monitor, args=(stop,), name="ai-monitor", daemon=True)]
|
||||
llama = self.slots.get("llama")
|
||||
if llama is not None and isinstance(llama.backend, LlamaBackend):
|
||||
threads.append(threading.Thread(target=llama.backend.logparser.follow,
|
||||
args=(llama.backend.current_log, stop), name="llama-log", daemon=True))
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
return threads
|
||||
|
||||
def monitor(self, stop: threading.Event) -> None:
|
||||
while not stop.is_set():
|
||||
for slot in self.slots.values():
|
||||
running = slot.child is not None or slot.external is not None
|
||||
if not running:
|
||||
slot.reachable = False
|
||||
slot.backend.mark_offline()
|
||||
continue
|
||||
try:
|
||||
slot.backend.poll()
|
||||
slot.reachable = True
|
||||
except (OSError, ValueError, KeyError, StopIteration) as e:
|
||||
slot.reachable = False
|
||||
slot.backend.mark_offline()
|
||||
log.debug("%s poll failed: %s", slot.backend.label, e)
|
||||
stop.wait(1.5)
|
||||
|
||||
def run(self, stop: threading.Event) -> None:
|
||||
try:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
self._reconcile(stop)
|
||||
except Exception:
|
||||
log.exception("AI supervisor error")
|
||||
self._wake.wait(1.0)
|
||||
self._wake.clear()
|
||||
finally:
|
||||
for slot in self.slots.values():
|
||||
if slot.child is not None:
|
||||
self._stop_slot(slot, "The Kurgan is exiting")
|
||||
|
||||
def _idle_check(self, active: str | None) -> str | None:
|
||||
"""Stop the selected server once nobody has used it for ai.idle_stop_minutes."""
|
||||
minutes = self.settings.get("ai", "idle_stop_minutes")
|
||||
if not active or not minutes:
|
||||
return active
|
||||
slot = self.slots[active]
|
||||
if slot.child is None or slot.stopping:
|
||||
return active
|
||||
with self._cv:
|
||||
if self._busy(active):
|
||||
self.last_used[active] = time.monotonic()
|
||||
return active
|
||||
if time.monotonic() - self.last_used[active] < minutes * 60:
|
||||
return active
|
||||
try:
|
||||
self.settings.update("ai", active=None)
|
||||
except OSError as e:
|
||||
log.warning("Couldn't save the AI selection: %s", e)
|
||||
return active
|
||||
log.info("%s unused for %d minutes; stopping it until the next request", slot.backend.label, minutes)
|
||||
return None
|
||||
|
||||
def _reconcile(self, stop: threading.Event) -> None:
|
||||
active = self._idle_check(self.settings.get("ai", "active"))
|
||||
for slot in self.slots.values():
|
||||
self._check_exit(slot)
|
||||
# Stop whatever isn't selected first, so the selected server gets the GPU to itself.
|
||||
for key, slot in self.slots.items():
|
||||
if slot.child is not None and key != active:
|
||||
self._stop_slot(slot, "switching" if active else "none selected")
|
||||
for key, slot in self.slots.items():
|
||||
slot.external = None
|
||||
if slot.child is None and port_in_use(slot.backend.port):
|
||||
slot.external = port_owner(slot.backend.port) or (0, "unknown program")
|
||||
if active is None or stop.is_set():
|
||||
self.transition = None
|
||||
return
|
||||
slot = self.slots[active]
|
||||
if slot.child is not None and slot.variant != slot.backend.variant():
|
||||
self._stop_slot(slot, "changing model")
|
||||
if slot.child is not None or slot.external is not None:
|
||||
self.transition = None
|
||||
return
|
||||
if time.monotonic() < slot.hold_until:
|
||||
return
|
||||
# At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the
|
||||
# server gets the desktop's own token (see launcher.py) rather than the fallback.
|
||||
if time.monotonic() - self._born < 120 and not launcher.desktop_ready():
|
||||
self.transition = f"Waiting for the desktop to start {slot.backend.label}"
|
||||
return
|
||||
problem = slot.backend.check_files()
|
||||
if problem:
|
||||
slot.error = problem
|
||||
return
|
||||
self._start_slot(slot)
|
||||
|
||||
def _check_exit(self, slot: Slot) -> None:
|
||||
if slot.child is None or slot.stopping:
|
||||
return
|
||||
code = slot.child.poll()
|
||||
if code is None:
|
||||
return
|
||||
slot.child.close()
|
||||
slot.child = None
|
||||
slot.restarts += 1
|
||||
slot.crashes.append(time.monotonic())
|
||||
if len(slot.crashes) == slot.crashes.maxlen and slot.crashes[-1] - slot.crashes[0] < 300:
|
||||
slot.error = f"{slot.backend.label} keeps exiting (code {code}); retrying in 5 minutes. See its log."
|
||||
slot.hold_until = time.monotonic() + 300
|
||||
slot.crashes.clear()
|
||||
else:
|
||||
slot.error = f"{slot.backend.label} exited (code {code}); restarting."
|
||||
slot.hold_until = time.monotonic() + 5
|
||||
log.error(slot.error)
|
||||
|
||||
def _start_slot(self, slot: Slot) -> None:
|
||||
backend = slot.backend
|
||||
self.transition = f"Starting {backend.label}"
|
||||
backend.before_start()
|
||||
argv, cwd, log_path = backend.command()
|
||||
try:
|
||||
slot.child = launcher.launch(argv, cwd, log_path)
|
||||
except OSError as e:
|
||||
slot.error = f"Could not start {backend.label}: {e}"
|
||||
slot.hold_until = time.monotonic() + 30
|
||||
log.error(slot.error)
|
||||
self.transition = None
|
||||
return
|
||||
if isinstance(backend, LlamaBackend):
|
||||
backend.owned = True
|
||||
with self._cv:
|
||||
self.last_used[backend.key] = time.monotonic()
|
||||
slot.variant = backend.variant()
|
||||
slot.started_at = time.time()
|
||||
slot.error = None
|
||||
self.transition = None
|
||||
|
||||
def _stop_slot(self, slot: Slot, why: str) -> None:
|
||||
child, backend = slot.child, slot.backend
|
||||
if child is None:
|
||||
return
|
||||
self.transition = f"Stopping {backend.label} ({why})"
|
||||
log.info("Stopping %s (%s)", backend.label, why)
|
||||
slot.stopping = True
|
||||
try:
|
||||
backend.request_stop(child)
|
||||
if child.wait(backend.stop_timeout) is None:
|
||||
log.warning("%s didn't stop within %.0f s; ending it", backend.label, backend.stop_timeout)
|
||||
child.kill()
|
||||
child.wait(10)
|
||||
deadline = time.monotonic() + 10 # the port and VRAM are free once every process in the job is gone
|
||||
while port_in_use(backend.port) and time.monotonic() < deadline:
|
||||
time.sleep(0.25)
|
||||
finally:
|
||||
child.kill()
|
||||
child.close()
|
||||
slot.child = None
|
||||
slot.stopping = False
|
||||
slot.started_at = None
|
||||
slot.reachable = False
|
||||
if isinstance(backend, LlamaBackend):
|
||||
backend.owned = False
|
||||
backend.mark_offline()
|
||||
self.transition = None
|
||||
|
||||
# -- state for the UI
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
active = self.settings.get("ai", "active")
|
||||
minutes = self.settings.get("ai", "idle_stop_minutes")
|
||||
now = time.monotonic()
|
||||
with self._cv:
|
||||
inflight = dict(self.inflight)
|
||||
idle_in = {key: max(0, round(minutes * 60 - (now - self.last_used[key])))
|
||||
for key, slot in self.slots.items()
|
||||
if minutes and key == active and slot.child is not None and not self._busy(key)}
|
||||
backends = []
|
||||
for key, slot in self.slots.items():
|
||||
b = slot.backend
|
||||
if slot.child is not None:
|
||||
process = "stopping" if slot.stopping else ("running" if slot.reachable else "starting")
|
||||
elif slot.external is not None:
|
||||
process = "external"
|
||||
else:
|
||||
process = "stopped"
|
||||
backends.append({
|
||||
"key": key, "label": b.label, "model_label": b.model_label(), "port": b.port,
|
||||
"variants": b.variants(), "variant": b.variant(), "links": b.links(),
|
||||
"process": process, "pid": slot.child.pid if slot.child else (slot.external[0] if slot.external else None),
|
||||
"external_program": slot.external[1] if slot.external else None,
|
||||
"token": slot.child.token if slot.child else None,
|
||||
"uptime": round(time.time() - slot.started_at) if slot.started_at else None,
|
||||
"restarts": slot.restarts, "error": slot.error,
|
||||
"route": f"/{key}/", "inflight": inflight[key], "idle_stop_in": idle_in.get(key),
|
||||
**b.snapshot(),
|
||||
})
|
||||
others = [s.backend.label for k, s in self.slots.items() if k != active and s.external is not None]
|
||||
warning = None
|
||||
if others:
|
||||
names, one = " and ".join(others), len(others) == 1
|
||||
warning = (f"{names} {'is' if one else 'are'} also running outside The Kurgan, so they may share "
|
||||
"the GPU's memory." if active else
|
||||
f"{names} {'is' if one else 'are'} running outside The Kurgan, from "
|
||||
f"{'its own startup task' if one else 'their own startup tasks'}. Run setup.ps1 -RetireAIServices "
|
||||
f"to let The Kurgan manage {'it' if one else 'them'}.")
|
||||
return {"active": active, "backends_order": list(BACKENDS), "transition": self.transition,
|
||||
"action": self.action, "message": self.message, "warning": warning,
|
||||
"idle_stop_minutes": minutes, "backends": backends}
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Runs Strata's OpenAI-compatible server for The Kurgan.
|
||||
|
||||
Started by The Kurgan with Strata's own venv (terminal\\.venv\\Scripts\\pythonw.exe), not
|
||||
imported by it. Does what Strata's local-service-tray.py did, without the tray icon:
|
||||
the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop
|
||||
by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing
|
||||
or cancelling the current request within --shutdown-timeout) and ends its engine processes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import _thread
|
||||
import argparse
|
||||
import contextlib
|
||||
import ctypes
|
||||
from ctypes import wintypes as wt
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LOG = logging.getLogger("kurgan-strata")
|
||||
K32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE
|
||||
K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE
|
||||
K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE, wt.DWORD], wt.DWORD
|
||||
K32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
|
||||
|
||||
def watch_stop(event: int, stopping: threading.Event) -> None:
|
||||
while K32.WaitForSingleObject(event, 1000) != 0:
|
||||
pass
|
||||
LOG.info("The Kurgan asked Strata to stop")
|
||||
stopping.set()
|
||||
_thread.interrupt_main()
|
||||
|
||||
|
||||
def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int:
|
||||
home = root / "terminal"
|
||||
sys.path.insert(0, str(home))
|
||||
os.chdir(home)
|
||||
from serve import lifeline, server
|
||||
|
||||
config = home / config_name
|
||||
with config.open(encoding="utf-8-sig") as source:
|
||||
model_id = json.load(source)["model_name"]
|
||||
# Same name as Strata's own tray uses, so the two can never serve one port at once.
|
||||
mutex = K32.CreateMutexW(None, False, f"Local\\StrataLocalService-{port}")
|
||||
if not mutex:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
if ctypes.get_last_error() == 183:
|
||||
K32.CloseHandle(mutex)
|
||||
raise RuntimeError(f"Strata is already running for port {port}.")
|
||||
stop_event = K32.CreateEventW(None, True, False, stop_name)
|
||||
if not stop_event:
|
||||
K32.CloseHandle(mutex)
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
stopping = threading.Event()
|
||||
threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start()
|
||||
try:
|
||||
LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid())
|
||||
os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1"
|
||||
os.environ["STRATA_NO_CONSOLE"] = "1"
|
||||
return server.main([
|
||||
"--engine", "strata", "--config", str(config), "--host", "127.0.0.1",
|
||||
"--port", str(port), "--lazy", "--idle-unload", str(idle_unload), "--shutdown-timeout", "30",
|
||||
])
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
lifeline.end_children()
|
||||
K32.CloseHandle(stop_event)
|
||||
K32.CloseHandle(mutex)
|
||||
LOG.info("Strata stopped")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--config", required=True, help="run config file name in terminal\\")
|
||||
parser.add_argument("--port", type=int, required=True)
|
||||
parser.add_argument("--idle-unload", type=int, default=2000)
|
||||
parser.add_argument("--stop-event", required=True)
|
||||
args = parser.parse_args()
|
||||
logs = args.root / "logs"
|
||||
logs.mkdir(exist_ok=True)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
|
||||
logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s")
|
||||
with (logs / f"local-service-stdout-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stdout, \
|
||||
(logs / f"local-service-stderr-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stderr, \
|
||||
contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
||||
try:
|
||||
return run(args.root, args.config, args.port, args.idle_unload, args.stop_event)
|
||||
except (OSError, ValueError, KeyError, RuntimeError):
|
||||
LOG.exception("Strata startup failed")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
"""The Kurgan: one process for the LCD, fans, lighting, the local LLM servers and the web UI.
|
||||
|
||||
Run: python -m kurgan (console, Ctrl+C to stop)
|
||||
Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs, elevated)
|
||||
Preview: python -m kurgan --preview x.png (render one LCD frame from live sensors and exit)
|
||||
|
||||
Needs admin rights for PawnIO (CPU temperature/power, motherboard top fans, RAM lighting);
|
||||
without them those parts show "--" or stay idle and everything else works. The LLM servers
|
||||
are always started without admin rights (see kurgan/ai/launcher.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import ctypes
|
||||
import logging
|
||||
import logging.handlers
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan import APP_NAME, __version__, paths
|
||||
|
||||
log = logging.getLogger("kurgan")
|
||||
INSTANCE_MUTEXES = ("Local\\TheKurgan", "Local\\TTLcdDashboard") # the second keeps an old dashboard copy out
|
||||
DEMO_MUTEXES = ("Local\\TheKurganDemo",)
|
||||
|
||||
|
||||
def _setup_logging(verbose: bool) -> None:
|
||||
os.makedirs(paths.DATA_DIR, exist_ok=True)
|
||||
handlers: list[logging.Handler] = [
|
||||
logging.handlers.RotatingFileHandler(paths.LOG_PATH, maxBytes=1_000_000, backupCount=2, encoding="utf-8")
|
||||
]
|
||||
if sys.stderr is not None:
|
||||
handlers.append(logging.StreamHandler())
|
||||
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
|
||||
def _single_instance(names=INSTANCE_MUTEXES) -> list | None:
|
||||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
k32.CreateMutexW.restype = ctypes.c_void_p
|
||||
k32.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
handles = []
|
||||
for name in names:
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED
|
||||
for h in handles + ([handle] if handle else []):
|
||||
k32.CloseHandle(h)
|
||||
return None
|
||||
handles.append(handle)
|
||||
return handles
|
||||
|
||||
|
||||
def _message_box(text: str) -> None:
|
||||
try:
|
||||
ctypes.WinDLL("user32").MessageBoxW(None, text, APP_NAME, 0x10 | 0x10000)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _parse_color(text: str) -> tuple[int, int, int]:
|
||||
text = text.lstrip("#")
|
||||
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
from kurgan.cooling.control import parse_ports
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m kurgan", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--port", type=int, help="web UI port (default: settings.json web.port, 8080)")
|
||||
ap.add_argument("--no-ai", action="store_true", help="don't start or watch the LLM servers")
|
||||
ap.add_argument("--no-lcd", action="store_true", help="don't drive the LCD (sensors keep running)")
|
||||
ap.add_argument("--no-tray", action="store_true", help="don't show the notification-area icon")
|
||||
ap.add_argument("--preview", metavar="PNG", help="render one LCD frame from live sensors to a PNG and exit")
|
||||
ap.add_argument("--demo", action="store_true",
|
||||
help="simulated sensors and devices, no LCD (set KURGAN_DATA_DIR for separate settings)")
|
||||
# LCD
|
||||
ap.add_argument("--interval", type=float, default=1.0, help="seconds between sensor reads/LCD frames (max 2)")
|
||||
ap.add_argument("--brightness", type=int, default=100, help="LCD backlight 0-100")
|
||||
ap.add_argument("--rotate180", action="store_true", help="flip the image if the panel is mounted upside down")
|
||||
ap.add_argument("--accent", default="e81c2c", help="LCD title colour as hex")
|
||||
ap.add_argument("--psu-watts", type=float, default=1000.0, help="power supply rating; fills the power tank")
|
||||
ap.add_argument("--cpu-temp-max", type=float, default=100.0)
|
||||
ap.add_argument("--gpu-temp-max", type=float, default=90.0)
|
||||
ap.add_argument("--temp-warn", type=float, default=50.0, help="gauges and lighting turn yellow here")
|
||||
ap.add_argument("--temp-hot", type=float, default=80.0, help="gauges and lighting turn red above this")
|
||||
ap.add_argument("--load-warn", type=float, default=50.0)
|
||||
ap.add_argument("--load-hot", type=float, default=80.0)
|
||||
ap.add_argument("--gpu-load", choices=("windows", "nvml"), default="windows")
|
||||
ap.add_argument("--same-direction", action="store_true", help=argparse.SUPPRESS)
|
||||
# Lighting: these override the saved mode for this run only (the web UI saves it).
|
||||
fans = ap.add_mutually_exclusive_group()
|
||||
fans.add_argument("--rgb-temperature", action="store_true", help="case fan LEDs: temperature (this run)")
|
||||
fans.add_argument("--rgb-side-chase", action="store_true", help="case fan LEDs: red side chase (this run)")
|
||||
memory = ap.add_mutually_exclusive_group()
|
||||
memory.add_argument("--rgb-memory-temperature", action="store_true", help="RAM: temperature (this run)")
|
||||
memory.add_argument("--rgb-memory-side-chase", action="store_true", help="RAM: red side chase (this run)")
|
||||
memory.add_argument("--rgb-memory-off", action="store_true", help="RAM: off (this run)")
|
||||
gpu = ap.add_mutually_exclusive_group()
|
||||
gpu.add_argument("--rgb-gpu-side-chase", action="store_true", help="GPU LEDs: red side chase (this run)")
|
||||
gpu.add_argument("--rgb-gpu-off", action="store_true", help="GPU LEDs: off (this run)")
|
||||
ap.add_argument("--rgb-chase-step-ms", type=float, default=150.0, help="ms per chase LED at idle power")
|
||||
ap.add_argument("--rgb-chase-fast-ms", type=float, default=25.0, help="ms per chase LED at full power")
|
||||
ap.add_argument("--rgb-chase-idle-watts", type=float, default=150.0)
|
||||
ap.add_argument("--rgb-chase-full-watts", type=float, default=550.0)
|
||||
# Cooling
|
||||
fan_options = ap.add_mutually_exclusive_group()
|
||||
fan_options.add_argument("--gpu-fan-ports", type=parse_ports, metavar="1,2,3",
|
||||
help="override the saved GPU-side Commander PRO ports for this run")
|
||||
fan_options.add_argument("--no-gpu-fan-control", action="store_true",
|
||||
help="disable case/top fan control for this run")
|
||||
ap.add_argument("-v", "--verbose", action="store_true")
|
||||
args = ap.parse_args(argv)
|
||||
for name in ("rgb_chase_step_ms", "rgb_chase_fast_ms"):
|
||||
if not math.isfinite(getattr(args, name)) or getattr(args, name) < 20:
|
||||
ap.error(f"--{name.replace('_', '-')} must be finite and at least 20")
|
||||
if args.rgb_chase_fast_ms > args.rgb_chase_step_ms:
|
||||
ap.error("--rgb-chase-fast-ms can't be slower than --rgb-chase-step-ms")
|
||||
if not (math.isfinite(args.rgb_chase_idle_watts) and math.isfinite(args.rgb_chase_full_watts)
|
||||
and args.rgb_chase_full_watts > args.rgb_chase_idle_watts):
|
||||
ap.error("--rgb-chase-full-watts must be above --rgb-chase-idle-watts")
|
||||
if args.preview and args.gpu_fan_ports:
|
||||
ap.error("--preview cannot be combined with --gpu-fan-ports")
|
||||
args.interval = max(0.25, min(2.0, args.interval))
|
||||
return args
|
||||
|
||||
|
||||
def lighting_overrides(args: argparse.Namespace) -> dict[str, str]:
|
||||
overrides = {}
|
||||
if args.rgb_temperature or args.rgb_side_chase:
|
||||
overrides["case_fans"] = "temperature" if args.rgb_temperature else "chase"
|
||||
if args.rgb_memory_temperature or args.rgb_memory_side_chase or args.rgb_memory_off:
|
||||
overrides["memory"] = ("temperature" if args.rgb_memory_temperature else
|
||||
"chase" if args.rgb_memory_side_chase else "off")
|
||||
if args.rgb_gpu_side_chase or args.rgb_gpu_off:
|
||||
overrides["gpu"] = "chase" if args.rgb_gpu_side_chase else "off"
|
||||
return overrides
|
||||
|
||||
|
||||
class Kurgan:
|
||||
"""Owns the capabilities and answers the web UI and the tray."""
|
||||
|
||||
def __init__(self, args: argparse.Namespace, settings):
|
||||
from kurgan.cooling.control import CaseFanControl, TopFanCurve
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
from kurgan.display.renderer import DashboardRenderer
|
||||
from kurgan.display.service import DisplayService
|
||||
from kurgan.lighting.service import LightingService
|
||||
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
from kurgan.theme import Theme
|
||||
|
||||
self.args = args
|
||||
self.settings = settings
|
||||
self.started = time.time()
|
||||
self.stop = threading.Event()
|
||||
self.theme = Theme(accent=_parse_color(args.accent), cpu_temp_range=(20.0, args.cpu_temp_max),
|
||||
gpu_temp_range=(20.0, args.gpu_temp_max), psu_watts=max(100.0, args.psu_watts),
|
||||
temp_warn=args.temp_warn, temp_hot=args.temp_hot,
|
||||
load_warn=args.load_warn, load_hot=args.load_hot)
|
||||
hw = None
|
||||
if args.demo:
|
||||
from kurgan import demo
|
||||
hw = demo.hardware()
|
||||
self.system = hw["system"] if hw else SystemPower()
|
||||
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(),
|
||||
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
|
||||
self.system, args.interval)
|
||||
self.display = None if (args.no_lcd or hw) else DisplayService(
|
||||
DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness)
|
||||
|
||||
cooling = settings.section("cooling")
|
||||
self.fan_note = None
|
||||
self.fans: CaseFanControl | None = None
|
||||
gpu_ports = None if args.no_gpu_fan_control else (args.gpu_fan_ports or cooling.get("gpu_ports"))
|
||||
if gpu_ports:
|
||||
top = cooling.get("top_channels")
|
||||
top_curve = None
|
||||
if top:
|
||||
top_curve = TopFanCurve(tuple(top), board_factory=hw["board"]) if hw else TopFanCurve(tuple(top))
|
||||
self.fans = CaseFanControl(self.system.fans, tuple(gpu_ports),
|
||||
tuple(cooling.get("cpu_ports") or ()) or None, top_curve,
|
||||
profile=PROFILES[cooling["profile"]], sensors=hw["fan_sensors"] if hw else None)
|
||||
self.system.fans.controlled = True
|
||||
else:
|
||||
self.fan_note = ("Fan control is off for this run (--no-gpu-fan-control)." if args.no_gpu_fan_control
|
||||
else "Fan control isn't set up: save the Commander PRO ports first (see README).")
|
||||
|
||||
self.lighting = LightingService(
|
||||
settings, self.theme,
|
||||
(args.rgb_chase_step_ms / 1000, args.rgb_chase_fast_ms / 1000,
|
||||
args.rgb_chase_idle_watts, args.rgb_chase_full_watts),
|
||||
lighting_overrides(args), **(hw["lighting"] if hw else {}))
|
||||
self.ai = None
|
||||
if not args.no_ai:
|
||||
from kurgan.ai.service import AiService
|
||||
self.ai = AiService(settings)
|
||||
self.web = None
|
||||
self.tray = None
|
||||
self._threads: list[threading.Thread] = []
|
||||
self.fan_history: collections.deque[tuple] = collections.deque(maxlen=self.telemetry._history.maxlen)
|
||||
self.telemetry.subscribe(self._on_sample)
|
||||
|
||||
# -- lifecycle
|
||||
|
||||
def _fan_row(self, t: float) -> tuple:
|
||||
cpu, top = self.fans.cpu, self.fans.top
|
||||
return (round(t, 1), self.fans.gpu.duty, None if cpu is None else cpu.duty, None if top is None else top.duty)
|
||||
|
||||
def _on_sample(self, sample) -> None:
|
||||
p = sample.power
|
||||
self.lighting.on_telemetry(sample.cpu.temp, sample.gpu.temp, p.total)
|
||||
if self.fans is not None:
|
||||
self.fan_history.append(self._fan_row(sample.t))
|
||||
if self.tray is not None:
|
||||
fmt = lambda v: "--" if v is None else f"{v:.0f}"
|
||||
self.tray.set_tooltip(f"{APP_NAME}\nTotal {fmt(p.total)} W: CPU {fmt(p.cpu)}, "
|
||||
f"GPU {fmt(p.gpu)}, other {fmt(p.other)}")
|
||||
|
||||
def _thread(self, name: str, target, *args) -> None:
|
||||
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
|
||||
thread.start()
|
||||
self._threads.append(thread)
|
||||
|
||||
def start(self, port: int, tray: bool) -> None:
|
||||
from kurgan.web.server import WebServer
|
||||
|
||||
self._thread("telemetry", self.telemetry.run, self.stop)
|
||||
if self.fans is not None:
|
||||
self._thread("case-fans", self.fans.run, self.stop)
|
||||
self.lighting.start(self.stop)
|
||||
if self.display is not None:
|
||||
self._thread("display", self.display.run, self.stop)
|
||||
if self.ai is not None:
|
||||
self.ai.set_public_url(f"http://127.0.0.1:{port}")
|
||||
self._threads += self.ai.start(self.stop)
|
||||
try:
|
||||
self.web = WebServer(self, port)
|
||||
self.web.start()
|
||||
except OSError as e:
|
||||
log.error("Web UI unavailable on port %s: %s", port, e)
|
||||
if tray:
|
||||
self._start_tray()
|
||||
|
||||
def _start_tray(self) -> None:
|
||||
from kurgan.tray import TrayIcon, make_icon
|
||||
|
||||
try:
|
||||
icon = make_icon(os.path.join(paths.DATA_DIR, "tray.ico"),
|
||||
[self.theme.other_color, self.theme.cpu_color, self.theme.gpu_color])
|
||||
self.tray = TrayIcon(APP_NAME, icon, on_exit=self.stop.set,
|
||||
on_open=self.open_ui if self.web else None, status_lines=self.tray_lines)
|
||||
self.tray.start()
|
||||
except Exception:
|
||||
log.exception("Tray icon unavailable")
|
||||
self.tray = None
|
||||
|
||||
def open_ui(self) -> None:
|
||||
from kurgan.ai.launcher import open_url
|
||||
|
||||
try:
|
||||
open_url(self.web.url)
|
||||
except OSError:
|
||||
log.exception("Couldn't open the browser")
|
||||
|
||||
def wait(self) -> None:
|
||||
try:
|
||||
while not self.stop.wait(1):
|
||||
pass
|
||||
except KeyboardInterrupt:
|
||||
self.stop.set()
|
||||
|
||||
def close(self) -> None:
|
||||
self.stop.set()
|
||||
if self.web is not None:
|
||||
self.web.close()
|
||||
if self.tray is not None:
|
||||
self.tray.close()
|
||||
deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly
|
||||
for thread in self._threads:
|
||||
thread.join(max(0.1, deadline - time.monotonic()))
|
||||
self.lighting.join()
|
||||
self.system.fans.close()
|
||||
|
||||
# -- the web UI's API
|
||||
|
||||
def config(self) -> dict:
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
|
||||
return {"app": APP_NAME, "version": __version__,
|
||||
"profiles": [p.as_dict() for p in PROFILES.values()],
|
||||
"theme": {"temp_warn": self.theme.temp_warn, "temp_hot": self.theme.temp_hot,
|
||||
"psu_watts": self.theme.psu_watts}}
|
||||
|
||||
def state(self) -> dict:
|
||||
from kurgan.ai.launcher import token_info
|
||||
|
||||
try:
|
||||
me = token_info()
|
||||
except OSError:
|
||||
me = None
|
||||
return {
|
||||
"app": {"name": APP_NAME, "version": __version__, "uptime": round(time.time() - self.started),
|
||||
"pid": os.getpid(), "token": me},
|
||||
"telemetry": self.telemetry.snapshot(),
|
||||
"display": self.display.snapshot() if self.display else {"status": "Off (--no-lcd)", "connected": False},
|
||||
"cooling": ({**self.fans.snapshot(), "note": None, "row": self.fan_history[-1] if self.fan_history else None}
|
||||
if self.fans is not None
|
||||
else {"profile": self.settings.get("cooling", "profile"), "groups": [], "top": None,
|
||||
"note": self.fan_note, "row": None}),
|
||||
"lighting": self.lighting.snapshot(),
|
||||
"ai": self.ai.snapshot() if self.ai else None,
|
||||
}
|
||||
|
||||
def history(self) -> dict:
|
||||
return {**self.telemetry.history(),
|
||||
"fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}}
|
||||
|
||||
def set_lighting(self, zone: str, mode: str) -> None:
|
||||
self.lighting.set_mode(zone, mode)
|
||||
|
||||
def set_fan_profile(self, key: str) -> None:
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
|
||||
if key not in PROFILES:
|
||||
raise ValueError(f"Unknown fan profile {key!r}")
|
||||
self.settings.update("cooling", profile=key)
|
||||
if self.fans is not None:
|
||||
self.fans.apply_profile(PROFILES[key])
|
||||
|
||||
def set_ai(self, backend: str | None, variant: str | None) -> None:
|
||||
if self.ai is None:
|
||||
raise ValueError("AI management is off for this run (--no-ai)")
|
||||
self.ai.set_active(backend, variant)
|
||||
|
||||
def ai_model(self, action: str) -> None:
|
||||
if self.ai is None:
|
||||
raise ValueError("AI management is off for this run (--no-ai)")
|
||||
self.ai.model_action(action)
|
||||
|
||||
# -- tray
|
||||
|
||||
def tray_lines(self) -> list[str]:
|
||||
lines = []
|
||||
if self.display is not None:
|
||||
lines.append(self.display.status)
|
||||
if self.fans is not None:
|
||||
profile = self.fans.profile.name
|
||||
groups = ", ".join(f"{g.name} {g.duty}%" for g in self.fans.groups)
|
||||
top = f", top {self.fans.top.duty}%" if self.fans.top is not None else ""
|
||||
lines.append(f"Fans: {profile} ({groups}{top})")
|
||||
elif self.fan_note:
|
||||
lines.append("Fans: not controlled")
|
||||
modes = {z["key"]: z["mode"] for z in self.lighting.snapshot()["zones"]}
|
||||
lines.append(f"Lighting: case fans {modes['case_fans']}, RAM {modes['memory']}, GPU {modes['gpu']}")
|
||||
if self.ai is not None:
|
||||
ai = self.ai.snapshot()
|
||||
active = next((b for b in ai["backends"] if b["key"] == ai["active"]), None)
|
||||
if active is None:
|
||||
lines.append("AI: none selected")
|
||||
else:
|
||||
lines.append(f"AI: {active['label']} - {active['process']}, model {active['model']['state']}")
|
||||
if self.web is not None:
|
||||
lines.append(f"Web UI: {self.web.url}")
|
||||
return lines
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
_setup_logging(args.verbose)
|
||||
from kurgan.settings import Settings, SettingsError
|
||||
|
||||
if args.preview:
|
||||
from kurgan.display.renderer import DashboardRenderer
|
||||
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
|
||||
from kurgan.theme import Theme
|
||||
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower())
|
||||
telemetry.read()
|
||||
time.sleep(1.0) # let counters and the energy meter accumulate
|
||||
sample = telemetry.read()
|
||||
theme = Theme(accent=_parse_color(args.accent), psu_watts=max(100.0, args.psu_watts))
|
||||
DashboardRenderer(theme, rotate180=args.rotate180).render(sample.cpu, sample.gpu, sample.power).save(
|
||||
args.preview)
|
||||
print(f"Wrote {args.preview}")
|
||||
return 0
|
||||
|
||||
mutexes = _single_instance(DEMO_MUTEXES if args.demo else INSTANCE_MUTEXES)
|
||||
if mutexes is None:
|
||||
log.error("Another copy of The Kurgan (or the TT LCD Dashboard) is already running")
|
||||
return 1
|
||||
try:
|
||||
settings = Settings(seed={"lighting": lighting_overrides(args)})
|
||||
except (OSError, SettingsError) as e:
|
||||
log.error("Invalid settings; refusing to start: %s", e)
|
||||
_message_box(f"The Kurgan didn't start: its settings are invalid.\n\n{e}\n\nLog: {paths.LOG_PATH}")
|
||||
return 1
|
||||
port = args.port or settings.get("web", "port")
|
||||
log.info("Starting %s %s (pid %s)", APP_NAME, __version__, os.getpid())
|
||||
try:
|
||||
app = Kurgan(args, settings)
|
||||
except ValueError:
|
||||
log.exception("Invalid configuration; refusing to start")
|
||||
return 1
|
||||
app.start(port, tray=not args.no_tray)
|
||||
app.wait()
|
||||
log.info("Stopping")
|
||||
app.close()
|
||||
log.info("Stopped")
|
||||
return 0
|
||||
@@ -0,0 +1 @@
|
||||
"""Cooling: Commander PRO case fans and motherboard top fans on selectable profiles."""
|
||||
@@ -0,0 +1,276 @@
|
||||
"""MSI motherboard fan headers on the Nuvoton NCT6687D Super I/O, through PawnIO's signed LpcIO module.
|
||||
|
||||
Register layout and the fan-configuration handshake follow LibreHardwareMonitor's Nct677X.cs.
|
||||
Needs PawnIO and administrator rights. Run ``python board_fans.py --probe`` to list the headers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.hardware import PAWNIO_DIR
|
||||
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
||||
_k32.CreateFileW.restype = wt.HANDLE
|
||||
_k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD,
|
||||
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
|
||||
_k32.DeviceIoControl.restype = wt.BOOL
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
_k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR]
|
||||
_k32.CreateMutexW.restype = wt.HANDLE
|
||||
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||
_k32.WaitForSingleObject.restype = wt.DWORD
|
||||
_k32.ReleaseMutex.argtypes = [wt.HANDLE]
|
||||
|
||||
|
||||
class PawnIo:
|
||||
DEVICE = r"\\?\GLOBALROOT\Device\PawnIO"
|
||||
IOCTL_LOAD_BINARY = 0xA1B22084
|
||||
IOCTL_EXECUTE_FN = 0xA1B22104
|
||||
|
||||
def __init__(self, module: str):
|
||||
h = _k32.CreateFileW(self.DEVICE, 0xC0000000, 0x3, None, 3, 0, None)
|
||||
if h == wt.HANDLE(-1).value:
|
||||
err = ctypes.get_last_error()
|
||||
reason = "run as administrator" if err == 5 else "is PawnIO installed?"
|
||||
raise OSError(f"Cannot open PawnIO ({ctypes.FormatError(err).strip()}; {reason})")
|
||||
self.handle = h
|
||||
with open(module, "rb") as f:
|
||||
blob = f.read()
|
||||
ret = wt.DWORD()
|
||||
if not _k32.DeviceIoControl(h, self.IOCTL_LOAD_BINARY, blob, len(blob), None, 0, ctypes.byref(ret), None):
|
||||
err = ctypes.get_last_error()
|
||||
self.close()
|
||||
raise OSError(f"PawnIO refused {os.path.basename(module)}: {ctypes.FormatError(err).strip()}")
|
||||
|
||||
def execute(self, fn: str, args: tuple[int, ...] = (), out: int = 0) -> tuple[int, ...]:
|
||||
inbuf = fn.encode().ljust(32, b"\x00") + struct.pack(f"<{len(args)}q", *args)
|
||||
outbuf = ctypes.create_string_buffer(8 * out)
|
||||
ret = wt.DWORD()
|
||||
if not _k32.DeviceIoControl(self.handle, self.IOCTL_EXECUTE_FN, inbuf, len(inbuf), outbuf, 8 * out,
|
||||
ctypes.byref(ret), None):
|
||||
raise OSError(f"PawnIO {fn} failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
||||
return struct.unpack(f"<{out}Q", outbuf.raw)
|
||||
|
||||
def close(self) -> None:
|
||||
if self.handle:
|
||||
_k32.CloseHandle(self.handle)
|
||||
self.handle = None
|
||||
|
||||
|
||||
class Nct6687:
|
||||
"""NCT6687D EC: 16 RPM inputs; PWM channels 0-7 are CPU, pump, then system fans 1-6."""
|
||||
|
||||
MODULE = os.path.join(PAWNIO_DIR, "LpcIO.bin")
|
||||
ISA_MUTEX = "Global\\Access_ISABUS.HTP.Method" # shared with LibreHardwareMonitor/FanControl
|
||||
CHANNELS = 8
|
||||
PAGE, INDEX, DATA = 4, 5, 6
|
||||
RPM, PWM_OUT, MODE, REQUEST, COMMAND = 0x140, 0x160, 0xA00, 0xA01, 0xA28
|
||||
CFG_REQUEST, CFG_COMPLETE = 0x80, 0x40
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.RLock()
|
||||
self._mutex = _k32.CreateMutexW(None, False, self.ISA_MUTEX)
|
||||
if not self._mutex:
|
||||
raise OSError(f"Cannot open the ISA bus mutex: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
||||
self.io: PawnIo | None = None
|
||||
try:
|
||||
self.io = PawnIo(self.MODULE)
|
||||
with self._bus():
|
||||
self.base, self.slot = self._detect()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
if self.io is not None:
|
||||
self.io.close()
|
||||
self.io = None
|
||||
if self._mutex:
|
||||
_k32.CloseHandle(self._mutex)
|
||||
self._mutex = None
|
||||
|
||||
def _bus(self):
|
||||
nct = self
|
||||
|
||||
class _Held:
|
||||
def __enter__(self):
|
||||
nct._lock.acquire()
|
||||
if _k32.WaitForSingleObject(nct._mutex, 500) not in (0, 0x80): # WAIT_OBJECT_0, WAIT_ABANDONED
|
||||
nct._lock.release()
|
||||
raise OSError("ISA bus busy (another hardware monitor is holding it)")
|
||||
|
||||
def __exit__(self, *exc):
|
||||
_k32.ReleaseMutex(nct._mutex)
|
||||
nct._lock.release()
|
||||
|
||||
return _Held()
|
||||
|
||||
def _detect(self) -> tuple[int, int]:
|
||||
assert self.io is not None
|
||||
for slot, reg in ((0, 0x2E), (1, 0x4E)):
|
||||
self.io.execute("ioctl_select_slot", (slot,))
|
||||
self.io.execute("ioctl_pio_outb", (reg, 0x87))
|
||||
self.io.execute("ioctl_pio_outb", (reg, 0x87))
|
||||
chip = self.io.execute("ioctl_superio_inb", (0x20,), 1)[0]
|
||||
rev = self.io.execute("ioctl_superio_inb", (0x21,), 1)[0]
|
||||
if (chip, rev) != (0xD5, 0x92):
|
||||
if chip not in (0, 0xFF):
|
||||
self.io.execute("ioctl_pio_outb", (reg, 0xAA))
|
||||
continue
|
||||
self.io.execute("ioctl_find_bars")
|
||||
self.io.execute("ioctl_superio_outb", (0x07, 0x0B)) # hardware-monitor logical device
|
||||
base = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0]
|
||||
time.sleep(0.001)
|
||||
verify = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0]
|
||||
self.io.execute("ioctl_pio_outb", (reg, 0xAA))
|
||||
if base != verify or base < 0x100 or base in (0xFFFF,):
|
||||
raise OSError(f"NCT6687D at 0x{reg:X} reported an invalid base address 0x{base:X}")
|
||||
return base & 0xFFF8, slot
|
||||
raise OSError("No Nuvoton NCT6687D Super I/O found (expected on MSI 600/700-series boards)")
|
||||
|
||||
def _out(self, port: int, value: int) -> None:
|
||||
assert self.io is not None
|
||||
self.io.execute("ioctl_pio_outb", (self.base + port, value))
|
||||
|
||||
def _in(self, port: int) -> int:
|
||||
assert self.io is not None
|
||||
return self.io.execute("ioctl_pio_inb", (self.base + port,), 1)[0]
|
||||
|
||||
def _claim_page(self) -> None:
|
||||
deadline = time.monotonic() + 0.5
|
||||
while self._in(self.PAGE) != 0xFF:
|
||||
if time.monotonic() >= deadline:
|
||||
self._out(self.PAGE, 0xFF) # stale owner: force access, as LibreHardwareMonitor does
|
||||
return
|
||||
time.sleep(0.001)
|
||||
|
||||
def read(self, address: int) -> int:
|
||||
self._claim_page()
|
||||
self._out(self.PAGE, address >> 8)
|
||||
self._out(self.INDEX, address & 0xFF)
|
||||
value = self._in(self.DATA)
|
||||
self._out(self.PAGE, 0xFF)
|
||||
return value
|
||||
|
||||
def write(self, address: int, value: int) -> None:
|
||||
self._claim_page()
|
||||
self._out(self.PAGE, address >> 8)
|
||||
self._out(self.INDEX, address & 0xFF)
|
||||
self._out(self.DATA, value & 0xFF)
|
||||
self._out(self.PAGE, 0xFF)
|
||||
|
||||
def rpms(self) -> list[int]:
|
||||
"""RPM of all 16 tachometer inputs."""
|
||||
with self._bus():
|
||||
return [(self.read(self.RPM + 2 * i) << 8) | self.read(self.RPM + 2 * i + 1) for i in range(16)]
|
||||
|
||||
def duties(self) -> list[int]:
|
||||
"""Current output duty (0-100%) of PWM channels 0-7."""
|
||||
with self._bus():
|
||||
return [round(self.read(self.PWM_OUT + i) / 2.55) for i in range(self.CHANNELS)]
|
||||
|
||||
def manual_mask(self) -> int:
|
||||
with self._bus():
|
||||
return self.read(self.MODE)
|
||||
|
||||
def _check_channels(self, channels: tuple[int, ...]) -> int:
|
||||
if not channels or any(c not in range(self.CHANNELS) for c in channels):
|
||||
raise ValueError(f"PWM channels must be 0-{self.CHANNELS - 1}")
|
||||
mask = 0
|
||||
for c in channels:
|
||||
mask |= 1 << c
|
||||
return mask
|
||||
|
||||
def set_manual(self, channels: tuple[int, ...], duty: int) -> None:
|
||||
"""Override the BIOS curve with a fixed duty on these channels."""
|
||||
mask = self._check_channels(channels)
|
||||
if not 0 <= duty <= 100:
|
||||
raise ValueError("duty must be 0-100")
|
||||
with self._bus():
|
||||
self.write(self.REQUEST, self.CFG_REQUEST)
|
||||
time.sleep(0.05)
|
||||
self.write(self.MODE, self.read(self.MODE) | mask)
|
||||
for c in channels:
|
||||
self.write(self.COMMAND + c, round(duty * 2.55))
|
||||
self.write(self.REQUEST, self.CFG_COMPLETE)
|
||||
time.sleep(0.05)
|
||||
|
||||
def set_auto(self, channels: tuple[int, ...]) -> None:
|
||||
"""Hand these channels back to the BIOS Smart Fan curve."""
|
||||
mask = self._check_channels(channels)
|
||||
with self._bus():
|
||||
self.write(self.REQUEST, self.CFG_REQUEST)
|
||||
time.sleep(0.05)
|
||||
self.write(self.MODE, self.read(self.MODE) & ~mask & 0xFF)
|
||||
self.write(self.REQUEST, self.CFG_COMPLETE)
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def parse_channels(text: str) -> tuple[int, ...]:
|
||||
try:
|
||||
channels = tuple(sorted({int(c) for c in text.split(",")}))
|
||||
except ValueError as e:
|
||||
raise argparse.ArgumentTypeError("Use comma-separated PWM channels, e.g. 2,5") from e
|
||||
if not channels or any(c not in range(Nct6687.CHANNELS) for c in channels):
|
||||
raise argparse.ArgumentTypeError(f"PWM channels must be 0-{Nct6687.CHANNELS - 1}")
|
||||
return channels
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
action = ap.add_mutually_exclusive_group(required=True)
|
||||
action.add_argument("--probe", action="store_true", help="read-only listing of the fan headers")
|
||||
action.add_argument("--identify", type=parse_channels, metavar="2,5",
|
||||
help="hold these PWM channels at 100%% (until --auto) to see which fans they drive")
|
||||
action.add_argument("--auto", type=parse_channels, metavar="2,5",
|
||||
help="return these PWM channels to the BIOS Smart Fan curve")
|
||||
ap.add_argument("--out", help="also write the report to this file")
|
||||
args = ap.parse_args()
|
||||
lines: list[str] = []
|
||||
try:
|
||||
nct = Nct6687()
|
||||
try:
|
||||
if args.identify:
|
||||
nct.set_manual(args.identify, 100)
|
||||
time.sleep(5)
|
||||
lines.append(f"Channels {args.identify} held at 100% until --auto")
|
||||
elif args.auto:
|
||||
nct.set_auto(args.auto)
|
||||
time.sleep(3)
|
||||
lines.append(f"Channels {args.auto} returned to the BIOS curve")
|
||||
with nct._bus():
|
||||
regs = {a: nct.read(a) for a in (0x180, nct.MODE, nct.REQUEST)}
|
||||
commands = [nct.read(nct.COMMAND + i) for i in range(nct.CHANNELS)]
|
||||
temps = [nct.read(0x100 + 2 * i) for i in range(7)]
|
||||
rpms, duties = nct.rpms(), nct.duties()
|
||||
lines.append(f"NCT6687D slot {nct.slot}, base 0x{nct.base:X}")
|
||||
lines.append("init 0x180=0x%02X manual mask 0xA00=0x%02X request 0xA01=0x%02X" % tuple(regs.values()))
|
||||
lines.append("temps 0x100..: " + ", ".join(str(struct.unpack('b', bytes([t]))[0]) for t in temps))
|
||||
for i in range(nct.CHANNELS):
|
||||
lines.append(f"PWM ch{i}: out {duties[i]:3d}% command {commands[i]:3d} "
|
||||
f"manual {'yes' if regs[nct.MODE] >> i & 1 else 'no'}")
|
||||
for i, rpm in enumerate(rpms):
|
||||
lines.append(f"RPM reg 0x{nct.RPM + 2 * i:03X}: {rpm}")
|
||||
finally:
|
||||
nct.close()
|
||||
except Exception as e:
|
||||
lines.append(f"ERROR: {type(e).__name__}: {e}")
|
||||
report = "\n".join(lines)
|
||||
print(report)
|
||||
if args.out:
|
||||
with open(args.out, "w", encoding="utf-8") as f:
|
||||
f.write(report + "\n")
|
||||
return 1 if report.startswith("ERROR") or "\nERROR" in report else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,389 @@
|
||||
"""Opt-in temperature control of Commander PRO PWM ports: the GPU-side group follows GPU
|
||||
temperature and an optional CPU-side group follows CPU temperature. Optional motherboard
|
||||
header fans follow the hotter of the two (stopped while cool) and run at 100% while either
|
||||
group works hard."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import logging
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.cooling.board_fans import Nct6687, parse_channels
|
||||
from kurgan.cooling.profiles import BALANCED, FanProfile
|
||||
from kurgan.hardware.hid import HidError
|
||||
from kurgan.telemetry.sensors import CommanderPro, GpuSensors, IntelPackage
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
# The Balanced profile's curves (the original ones); the active profile can replace them at runtime.
|
||||
CURVE, CPU_CURVE, TOP_CURVE = BALANCED.gpu_curve, BALANCED.cpu_curve, BALANCED.top_curve
|
||||
CPU_AVERAGE = 5 # seconds of CPU package temperature averaged, so momentary spikes don't surge the fans
|
||||
BOOST_ON, BOOST_OFF = 85, 65 # case fan duty (either side) that starts / ends the top-fan boost
|
||||
TOP_START, TOP_STOP = BALANCED.top_start, BALANCED.top_stop # top fans start at / stop below (C) ...
|
||||
TOP_STOP_HOLD = 30 # ... once it has stayed below the stop temperature for this many seconds
|
||||
TOP_KICK, TOP_KICK_SECONDS = 40, 3 # spin-up duty when starting from stopped
|
||||
|
||||
|
||||
def parse_ports(text: str) -> tuple[int, ...]:
|
||||
try:
|
||||
ports = tuple(int(p.strip()) for p in text.split(","))
|
||||
except ValueError as e:
|
||||
raise argparse.ArgumentTypeError("Use three comma-separated ports, e.g. 1,2,3") from e
|
||||
if len(ports) != 3 or len(set(ports)) != 3 or any(p not in range(1, 7) for p in ports):
|
||||
raise argparse.ArgumentTypeError("Specify exactly three distinct Commander PRO ports (1-6)")
|
||||
return ports
|
||||
|
||||
|
||||
def _curve_duty(curve: tuple[tuple[int, int], ...], temp: float | None) -> int:
|
||||
if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110:
|
||||
return 100
|
||||
for (t0, d0), (t1, d1) in zip(curve, curve[1:]):
|
||||
if temp <= t1:
|
||||
return math.ceil(d0 + max(0, temp - t0) * (d1 - d0) / (t1 - t0))
|
||||
return 100
|
||||
|
||||
|
||||
def gpu_duty(temp: float | None) -> int:
|
||||
return _curve_duty(CURVE, temp)
|
||||
|
||||
|
||||
def cpu_duty(temp: float | None) -> int:
|
||||
return _curve_duty(CPU_CURVE, temp)
|
||||
|
||||
|
||||
class TopFanCurve:
|
||||
"""Motherboard header fans on their own curve from the hotter of CPU/GPU, stopped while cool.
|
||||
|
||||
They are also held at 100% while either case fan group works hard; on exit the BIOS curve
|
||||
takes over again."""
|
||||
|
||||
RETRY = 30.0
|
||||
|
||||
def __init__(self, channels: tuple[int, ...], board_factory=Nct6687, profile: FanProfile = BALANCED):
|
||||
self.channels = parse_channels(",".join(map(str, channels)))
|
||||
self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop
|
||||
self.temp: float | None = None
|
||||
self._mask = sum(1 << c for c in self.channels)
|
||||
self._factory = board_factory
|
||||
self.board: Nct6687 | None = None
|
||||
self.boosted = False
|
||||
self.running = False
|
||||
self.duty = 0
|
||||
self.status = "Starting"
|
||||
self._retry_at = 0.0
|
||||
self._written: int | None = None
|
||||
self._kick_until = 0.0
|
||||
self._cool_since: float | None = None
|
||||
self._last_rise = 0.0
|
||||
self._last_update: float | None = None
|
||||
|
||||
def apply_profile(self, profile: FanProfile) -> None:
|
||||
self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop
|
||||
|
||||
def _status(self, text: str, warning: bool = False) -> None:
|
||||
if text != self.status:
|
||||
(log.warning if warning else log.info)("Top fans: %s", text)
|
||||
self.status = text
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"channels": list(self.channels), "temp": self.temp, "duty": self.duty, "running": self.running,
|
||||
"boosted": self.boosted, "status": self.status,
|
||||
"failsafe": self.status.startswith(("FAILSAFE", "UNAVAILABLE"))}
|
||||
|
||||
def close(self) -> None:
|
||||
if self.board is not None:
|
||||
self.board.close()
|
||||
self.board = None
|
||||
self._written = None
|
||||
|
||||
def _target(self, case_duty: int, temp: float | None, now: float) -> tuple[int, str]:
|
||||
self.boosted = case_duty >= BOOST_ON or (self.boosted and case_duty > BOOST_OFF)
|
||||
if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110:
|
||||
self.running, self._cool_since = True, None
|
||||
return 100, "FAILSAFE 100%: temperature unavailable"
|
||||
if not self.running and (temp >= self.start or self.boosted):
|
||||
self.running, self._cool_since = True, None
|
||||
self._kick_until = now + TOP_KICK_SECONDS
|
||||
elif self.running and temp < self.stop and not self.boosted:
|
||||
self._cool_since = now if self._cool_since is None else self._cool_since
|
||||
if now - self._cool_since >= TOP_STOP_HOLD:
|
||||
self.running, self._cool_since = False, None
|
||||
else:
|
||||
self._cool_since = None
|
||||
if not self.running:
|
||||
return 0, f"{temp:.0f} C, stopped (start at {self.start} C)"
|
||||
target = _curve_duty(self.curve, temp)
|
||||
if self.boosted:
|
||||
target = 100
|
||||
if now < self._kick_until:
|
||||
target = max(target, TOP_KICK)
|
||||
return target, f"{temp:.0f} C, {{duty}}%" + (f" (case fans >= {BOOST_ON}%)" if self.boosted else "")
|
||||
|
||||
def update(self, case_duty: int, temp: float | None, now: float) -> None:
|
||||
self.temp = temp
|
||||
target, text = self._target(case_duty, temp, now)
|
||||
elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update))
|
||||
self._last_update = now
|
||||
if target == 0 or target >= self.duty:
|
||||
if target > self.duty:
|
||||
self._last_rise = now
|
||||
self.duty = target
|
||||
elif now - self._last_rise >= 10:
|
||||
self.duty = max(target, self.duty - int(2 * elapsed))
|
||||
if self.board is None and now < self._retry_at:
|
||||
return
|
||||
try:
|
||||
if self.board is None:
|
||||
self.board = self._factory()
|
||||
# Compared every poll, so a firmware reset (e.g. after sleep) or a crash is corrected.
|
||||
if self.duty != self._written or self.board.manual_mask() & self._mask != self._mask:
|
||||
self.board.set_manual(self.channels, self.duty)
|
||||
self._written = self.duty
|
||||
self._status(text.format(duty=self.duty), warning=text.startswith("FAILSAFE"))
|
||||
except (OSError, ValueError) as e:
|
||||
self._status(f"UNAVAILABLE ({e}); BIOS curve keeps control", warning=True)
|
||||
self.close()
|
||||
self._retry_at = now + self.RETRY
|
||||
|
||||
def release(self) -> None:
|
||||
try:
|
||||
if self.board is None:
|
||||
self.board = self._factory()
|
||||
self.board.set_auto(self.channels)
|
||||
self.boosted = self.running = False
|
||||
except (OSError, ValueError):
|
||||
log.exception("Cannot return top fans to the BIOS curve")
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
|
||||
class CaseFanGroup:
|
||||
"""Three Commander PRO ports following one temperature: immediate rises, slow falls, failsafe 100%."""
|
||||
|
||||
def __init__(self, name: str, curve, commander: CommanderPro, ports: tuple[int, ...]):
|
||||
self.name = name
|
||||
self.curve = curve
|
||||
self.ports = parse_ports(",".join(map(str, ports)))
|
||||
self.commander = commander
|
||||
self.status = "Starting"
|
||||
self.duty = 100
|
||||
self.temp: float | None = None
|
||||
self.rpms: dict[int, int] = {}
|
||||
self._last_update: float | None = None
|
||||
self._last_rise = 0.0
|
||||
self._started: float | None = None
|
||||
|
||||
def set_status(self, text: str, warning: bool = False) -> None:
|
||||
if text != self.status:
|
||||
(log.warning if warning else log.info)("%s case fans: %s", self.name, text)
|
||||
self.status = text
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"name": self.name, "ports": list(self.ports), "temp": self.temp, "duty": self.duty,
|
||||
"rpms": {str(p): self.rpms.get(p) for p in self.ports}, "status": self.status,
|
||||
"failsafe": self.status.startswith(("FAILSAFE", "CONTROL ERROR"))}
|
||||
|
||||
def update(self, temp: float | None, now: float) -> None:
|
||||
self.temp = temp
|
||||
target = _curve_duty(self.curve, temp)
|
||||
invalid = temp is None or not math.isfinite(temp) or not 0 <= temp <= 110
|
||||
if self._last_update is None or now - self._last_update > 5:
|
||||
self.duty = 100
|
||||
self._last_rise = now
|
||||
self._started = now
|
||||
elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update))
|
||||
if target >= self.duty:
|
||||
if target > self.duty or invalid:
|
||||
self._last_rise = now
|
||||
self.duty = target
|
||||
elif now - self._last_rise >= 10:
|
||||
self.duty = max(target, self.duty - int(2 * elapsed))
|
||||
self._last_update = now
|
||||
rpms = self.rpms = self.commander.set_duty(self.ports, self.duty)
|
||||
if self._started is not None and now - self._started >= 10:
|
||||
stalled = [p for p in self.ports if rpms.get(p, 0) < 200]
|
||||
if stalled:
|
||||
self.duty = 100
|
||||
self._last_rise = now
|
||||
self.commander.set_duty(self.ports, 100)
|
||||
self.set_status(f"FAILSAFE 100%: no/low RPM on ports {stalled}", warning=True)
|
||||
return
|
||||
if invalid:
|
||||
self.set_status(f"FAILSAFE 100%: {self.name} temperature unavailable", warning=True)
|
||||
else:
|
||||
self.set_status(f"{self.name} {temp:.0f} C, {self.duty}% PWM; "
|
||||
+ ", ".join(f"{p}: {rpms.get(p, 0)} rpm" for p in self.ports))
|
||||
|
||||
def failsafe(self) -> None:
|
||||
self.duty = 100
|
||||
self._last_update = None
|
||||
try:
|
||||
self.commander.set_duty(self.ports, 100)
|
||||
except (OSError, HidError):
|
||||
log.exception("Cannot set %s case fans to failsafe 100%%; controller unavailable", self.name)
|
||||
|
||||
|
||||
class CpuTemperature:
|
||||
"""CPU package temperature averaged over CPU_AVERAGE readings; None while unavailable."""
|
||||
|
||||
def __init__(self, factory=IntelPackage):
|
||||
self._factory = factory
|
||||
self.pkg: IntelPackage | None = None
|
||||
self._retry_at = 0.0
|
||||
self._recent: collections.deque[float] = collections.deque(maxlen=CPU_AVERAGE)
|
||||
|
||||
def read(self, now: float) -> float | None:
|
||||
if self.pkg is None and now >= self._retry_at:
|
||||
try:
|
||||
self.pkg = self._factory()
|
||||
except Exception as e: # PawnIO missing, not admin, ...
|
||||
log.warning("CPU temperature unavailable for fan control: %s", e)
|
||||
self._retry_at = now + 60
|
||||
temp = None
|
||||
if self.pkg is not None:
|
||||
try:
|
||||
temp = self.pkg.temperature()
|
||||
except OSError as e:
|
||||
log.warning("CPU temperature read failed, will retry: %s", e)
|
||||
self.close()
|
||||
if temp is None:
|
||||
self._recent.clear()
|
||||
return None
|
||||
self._recent.append(temp)
|
||||
return sum(self._recent) / len(self._recent)
|
||||
|
||||
def close(self) -> None:
|
||||
if self.pkg is not None:
|
||||
self.pkg.msr.close()
|
||||
self.pkg = None
|
||||
|
||||
|
||||
class CaseFanControl:
|
||||
def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...],
|
||||
cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None,
|
||||
profile: FanProfile = BALANCED, sensors=None):
|
||||
"""sensors: (GPU sensor factory, CPU temperature factory), for tests and --demo."""
|
||||
self.commander = commander
|
||||
self.profile = profile
|
||||
self._sensors = sensors or (lambda: GpuSensors(load_source="nvml"), CpuTemperature)
|
||||
self.gpu = CaseFanGroup("GPU", profile.gpu_curve, commander, gpu_ports)
|
||||
self.cpu = CaseFanGroup("CPU", profile.cpu_curve, commander, cpu_ports) if cpu_ports else None
|
||||
if self.cpu is not None and set(self.cpu.ports) & set(self.gpu.ports):
|
||||
raise ValueError("CPU-side and GPU-side ports must not overlap")
|
||||
self.groups = [g for g in (self.gpu, self.cpu) if g is not None]
|
||||
self.top = top
|
||||
if top is not None:
|
||||
top.apply_profile(profile)
|
||||
|
||||
def apply_profile(self, profile: FanProfile) -> None:
|
||||
"""Switch curves; rises take effect on the next poll, falls follow the usual slow ramp-down."""
|
||||
self.gpu.curve = profile.gpu_curve
|
||||
if self.cpu is not None:
|
||||
self.cpu.curve = profile.cpu_curve
|
||||
if self.top is not None:
|
||||
self.top.apply_profile(profile)
|
||||
self.profile = profile
|
||||
log.info("Fan profile: %s", profile.name)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"profile": self.profile.key, "groups": [g.snapshot() for g in self.groups],
|
||||
"top": None if self.top is None else self.top.snapshot()}
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
return self.gpu.status
|
||||
|
||||
def update(self, gpu_temp: float | None, now: float, cpu_temp: float | None = None) -> None:
|
||||
self.gpu.update(gpu_temp, now)
|
||||
if self.cpu is not None:
|
||||
self.cpu.update(cpu_temp, now)
|
||||
if self.top is not None:
|
||||
temps = [gpu_temp] + ([cpu_temp] if self.cpu is not None else [])
|
||||
valid = all(t is not None and math.isfinite(t) and 0 <= t <= 110 for t in temps)
|
||||
self.top.update(max(g.duty for g in self.groups), max(temps) if valid else None, now)
|
||||
|
||||
def failsafe(self) -> None:
|
||||
for g in self.groups:
|
||||
g.failsafe()
|
||||
|
||||
def _error(self, text: str) -> None:
|
||||
for g in self.groups:
|
||||
g.set_status(text, warning=True)
|
||||
|
||||
def run(self, stop: threading.Event) -> None:
|
||||
gpu_factory, cpu_factory = self._sensors
|
||||
cpu_temp = cpu_factory() if self.cpu is not None else None
|
||||
try:
|
||||
gpu = gpu_factory()
|
||||
while not stop.is_set():
|
||||
now = time.monotonic()
|
||||
try:
|
||||
self.update(gpu.read().temp, now, cpu_temp.read(now) if cpu_temp else None)
|
||||
except (OSError, HidError) as e:
|
||||
self._error(f"CONTROL ERROR: {e}")
|
||||
self.failsafe()
|
||||
self.commander.close()
|
||||
if self.top is not None:
|
||||
self.top.update(100, None, time.monotonic())
|
||||
stop.wait(1)
|
||||
except Exception:
|
||||
log.exception("Case fan worker failed")
|
||||
self._error("CONTROL ERROR: fan worker stopped; check dashboard.log")
|
||||
finally:
|
||||
self.failsafe()
|
||||
self.commander.close()
|
||||
if self.top is not None:
|
||||
self.top.release()
|
||||
if cpu_temp is not None:
|
||||
cpu_temp.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
action = ap.add_mutually_exclusive_group(required=True)
|
||||
action.add_argument("--identify", type=parse_ports, metavar="1,2,3",
|
||||
help="raise these three ports to 100%% to identify their physical side")
|
||||
action.add_argument("--save-ports", type=parse_ports, metavar="4,5,6",
|
||||
help="save identified GPU-side ports for dashboard startup")
|
||||
action.add_argument("--save-cpu-ports", type=parse_ports, metavar="1,2,3",
|
||||
help="save identified CPU-side ports (follow CPU temperature)")
|
||||
action.add_argument("--save-top-channels", type=parse_channels, metavar="2,5",
|
||||
help="save motherboard PWM channels (see board_fans.py) for the top-fan curve")
|
||||
args = ap.parse_args()
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
if args.save_ports or args.save_cpu_ports or args.save_top_channels:
|
||||
from kurgan.settings import Settings, SettingsError
|
||||
|
||||
try:
|
||||
settings = Settings()
|
||||
if args.save_ports:
|
||||
settings.update("cooling", gpu_ports=list(args.save_ports))
|
||||
elif args.save_cpu_ports:
|
||||
settings.update("cooling", cpu_ports=list(args.save_cpu_ports))
|
||||
else:
|
||||
settings.update("cooling", top_channels=list(args.save_top_channels))
|
||||
except (OSError, SettingsError):
|
||||
log.exception("Cannot save fan configuration")
|
||||
return 1
|
||||
print(f"Saved {settings.section('cooling')} to {settings.path}. Restart The Kurgan to apply it.")
|
||||
return 0
|
||||
commander = CommanderPro()
|
||||
try:
|
||||
rpms = commander.set_duty(args.identify, 100)
|
||||
print(f"Ports {args.identify} set to 100%. They will stay at 100% after this test.")
|
||||
time.sleep(5)
|
||||
rpms = commander.set_duty(args.identify, 100)
|
||||
print("RPMs: " + ", ".join(f"{p}: {rpm}" for p, rpm in rpms.items()))
|
||||
return 0
|
||||
except (OSError, HidError) as e:
|
||||
log.error("Identification failed: %s", e)
|
||||
return 1
|
||||
finally:
|
||||
commander.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Selectable fan profiles: one set of temperature -> PWM duty curves for each fan group.
|
||||
|
||||
Every profile keeps the fail-safes in control.py (100% when a temperature is missing, a fan
|
||||
stalls or the controller fails), the slow ramp-down, and the top-fan boost while either
|
||||
case-fan group runs at 85% or more. Only the curves and the top fans' start/stop
|
||||
temperatures differ.
|
||||
|
||||
Curves are (temperature C, duty %) points: below the first point the duty is the first
|
||||
point's, between points it is interpolated, and at or above the last point it is 100%.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
Curve = tuple[tuple[int, int], ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FanProfile:
|
||||
key: str
|
||||
name: str
|
||||
description: str
|
||||
gpu_curve: Curve # GPU-side Commander PRO fans, from GPU temperature
|
||||
cpu_curve: Curve # CPU-side Commander PRO fans, from 5-second-averaged CPU package temperature
|
||||
top_curve: Curve # motherboard top fans while running, from the hotter of CPU/GPU
|
||||
top_start: int # top fans start at this temperature ...
|
||||
top_stop: int # ... and stop after 30 s below this one
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {"key": self.key, "name": self.name, "description": self.description,
|
||||
"gpu_curve": self.gpu_curve, "cpu_curve": self.cpu_curve, "top_curve": self.top_curve,
|
||||
"top_start": self.top_start, "top_stop": self.top_stop}
|
||||
|
||||
|
||||
def validate_curve(curve: Curve) -> None:
|
||||
if len(curve) < 2:
|
||||
raise ValueError("a curve needs at least two points")
|
||||
temps = [t for t, _ in curve]
|
||||
duties = [d for _, d in curve]
|
||||
if any(b <= a for a, b in zip(temps, temps[1:])):
|
||||
raise ValueError("curve temperatures must rise")
|
||||
if any(b < a for a, b in zip(duties, duties[1:])):
|
||||
raise ValueError("curve duties must not fall as temperature rises")
|
||||
if not all(0 <= t <= 110 for t in temps) or not all(0 <= d <= 100 for d in duties):
|
||||
raise ValueError("curve points must be 0-110 C and 0-100%")
|
||||
if duties[-1] != 100:
|
||||
raise ValueError("every curve must reach 100%")
|
||||
|
||||
|
||||
QUIET = FanProfile(
|
||||
"quiet", "Quiet",
|
||||
"Lower fan speeds; each group reaches 100% about 5 C later than Balanced.",
|
||||
gpu_curve=((45, 35), (55, 45), (65, 65), (75, 100)),
|
||||
cpu_curve=((55, 35), (65, 45), (75, 65), (85, 100)),
|
||||
top_curve=((55, 30), (65, 60), (75, 100)),
|
||||
top_start=55, top_stop=50,
|
||||
)
|
||||
BALANCED = FanProfile(
|
||||
"balanced", "Balanced",
|
||||
"The original curves: GPU-side fans reach 100% at 70 C, CPU-side fans at 80 C.",
|
||||
gpu_curve=((40, 40), (50, 50), (60, 65), (70, 100)),
|
||||
cpu_curve=((50, 40), (60, 50), (70, 65), (80, 100)),
|
||||
top_curve=((50, 30), (60, 60), (70, 100)),
|
||||
top_start=50, top_stop=45,
|
||||
)
|
||||
PERFORMANCE = FanProfile(
|
||||
"performance", "Performance",
|
||||
"Higher speeds for long AI or gaming loads; each group reaches 100% 5 C earlier than Balanced.",
|
||||
gpu_curve=((35, 50), (45, 60), (55, 80), (65, 100)),
|
||||
cpu_curve=((45, 50), (55, 60), (65, 80), (75, 100)),
|
||||
top_curve=((45, 40), (55, 70), (65, 100)),
|
||||
top_start=45, top_stop=40,
|
||||
)
|
||||
FULL = FanProfile(
|
||||
"full", "Full speed",
|
||||
"Every controlled fan at 100%, including the top fans.",
|
||||
gpu_curve=((0, 100), (110, 100)),
|
||||
cpu_curve=((0, 100), (110, 100)),
|
||||
top_curve=((0, 100), (110, 100)),
|
||||
top_start=0, top_stop=0,
|
||||
)
|
||||
|
||||
PROFILES: dict[str, FanProfile] = {p.key: p for p in (QUIET, BALANCED, PERFORMANCE, FULL)}
|
||||
DEFAULT_PROFILE = BALANCED.key
|
||||
|
||||
for _profile in PROFILES.values():
|
||||
for _curve in (_profile.gpu_curve, _profile.cpu_curve, _profile.top_curve):
|
||||
validate_curve(_curve)
|
||||
assert _profile.top_stop <= _profile.top_start
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
"""Simulated sensors and devices for `python -m kurgan --demo`.
|
||||
|
||||
Lets the web UI and the AI swapping be worked on while the real Kurgan owns the hardware:
|
||||
nothing here touches USB, PawnIO, the SMBus or NVAPI. Run it with its own data folder and
|
||||
web port, e.g.
|
||||
|
||||
$env:KURGAN_DATA_DIR = "$env:TEMP\\kurgan-demo"; python -m kurgan --demo --port 18080 --no-tray
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
|
||||
_T0 = time.monotonic()
|
||||
|
||||
|
||||
def _wave(period: float, phase: float = 0.0) -> float:
|
||||
"""0..1, slowly rising and falling."""
|
||||
return 0.5 + 0.5 * math.sin((time.monotonic() - _T0) * 2 * math.pi / period + phase)
|
||||
|
||||
|
||||
class FakeCpu:
|
||||
status = "simulated"
|
||||
|
||||
def read(self) -> Readings:
|
||||
load = 5 + 70 * _wave(150) ** 3
|
||||
return Readings(temp=38 + 0.5 * load, load=load, clock=1200 + 40 * load, power=15 + 1.6 * load)
|
||||
|
||||
|
||||
class FakeGpu:
|
||||
def read(self) -> Readings:
|
||||
load = 2 + 95 * _wave(90, 1.0) ** 4
|
||||
return Readings(temp=34 + 0.42 * load, load=load, clock=210 + 26 * load, power=18 + 4.2 * load)
|
||||
|
||||
def memory(self) -> tuple[int, int]:
|
||||
return int((1.4 + 18 * _wave(300, 2.0)) * 2**30), 24 * 2**30
|
||||
|
||||
|
||||
class FakeCommander:
|
||||
controlled = False
|
||||
|
||||
def __init__(self):
|
||||
self.duty = {p: 100 for p in range(1, 7)}
|
||||
|
||||
def _rpm(self, port: int) -> int:
|
||||
return int(525 + 9.75 * self.duty[port])
|
||||
|
||||
def read(self) -> list[int]:
|
||||
return [self._rpm(p) for p in range(1, 7)]
|
||||
|
||||
def set_duty(self, ports, duty: int) -> dict[int, int]:
|
||||
for p in ports:
|
||||
self.duty[p] = duty
|
||||
return {p: self._rpm(p) for p in ports}
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeSystem:
|
||||
def __init__(self):
|
||||
self.fans = FakeCommander()
|
||||
|
||||
def read(self, cpu: Readings, gpu: Readings) -> PowerReadings:
|
||||
parts = {"Motherboard & chipset": 15.0, "Memory (4 modules)": 10 + 0.1 * (cpu.load or 0),
|
||||
"Case fans (6, Commander PRO)": sum(2 * (r / 1500) ** 2.5 for r in self.fans.read()),
|
||||
"USB devices & RGB lighting (fixed)": 12.0}
|
||||
return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=sum(parts.values()), parts=parts)
|
||||
|
||||
|
||||
class FakeBoard:
|
||||
def __init__(self):
|
||||
self.mask = 0
|
||||
|
||||
def manual_mask(self) -> int:
|
||||
return self.mask
|
||||
|
||||
def set_manual(self, channels, duty: int) -> None:
|
||||
self.mask |= sum(1 << c for c in channels)
|
||||
|
||||
def set_auto(self, channels) -> None:
|
||||
self.mask &= ~sum(1 << c for c in channels)
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeCpuTemperature:
|
||||
def read(self, now: float) -> float:
|
||||
return FakeCpu().read().temp
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeLights:
|
||||
"""Stands in for a lighting worker: reports which pattern it would be running."""
|
||||
|
||||
def __init__(self, device: str):
|
||||
self.device = device
|
||||
self.status = "off"
|
||||
|
||||
def set_temperature(self, cpu_temp, gpu_temp=None) -> None:
|
||||
pass
|
||||
|
||||
def set_power(self, total_watts) -> None:
|
||||
pass
|
||||
|
||||
def run(self, stop: threading.Event, *events: threading.Event) -> None:
|
||||
names = ("temperature", "chase") if len(events) == 2 else ("chase",)
|
||||
while not stop.is_set():
|
||||
active = [n for n, e in zip(names, events) if e.is_set()]
|
||||
self.status = f"{active[0].capitalize()} on the {self.device} (simulated)" if active else "off"
|
||||
stop.wait(0.2)
|
||||
|
||||
|
||||
def hardware() -> dict:
|
||||
return {
|
||||
"cpu": FakeCpu(), "gpu": FakeGpu(), "system": FakeSystem(), "board": FakeBoard,
|
||||
"fan_sensors": (FakeGpu, FakeCpuTemperature),
|
||||
"lighting": {"rgb": FakeLights("case fans"), "memory": FakeLights("RAM"), "gpu": FakeLights("GPU")},
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Display: the GPU | CPU dashboard on the Thermaltake 3.9\" bar LCD."""
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 428 KiB |
@@ -0,0 +1,614 @@
|
||||
"""Renders the GPU | CPU dashboard for the Thermaltake 3.9" bar LCD (480x128).
|
||||
|
||||
Left half is the GPU; the right half is the same layout mirrored horizontally
|
||||
for the CPU, with all gauges filling clockwise. The centre column shows the whole PC's power draw
|
||||
against the power supply's rating, stacked as other (bottom), CPU, GPU (top).
|
||||
The supplied red-panel background sits behind the procedural instruments.
|
||||
Everything is rendered at SS x resolution and then downsampled,
|
||||
which gives clean anti-aliasing on the small panel.
|
||||
|
||||
[GPU]---------------------[ TOTAL W ]---------------------[CPU]
|
||||
temp gauge load gauge | tank | load gauge temp gauge
|
||||
[ MHz ]-------[# GPU W] [# other W] [# CPU W]-------[ MHz ]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import numpy as np
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
from kurgan.theme import Theme
|
||||
|
||||
W, H = 480, 128
|
||||
SS = 4 # supersampling factor
|
||||
|
||||
FONT_FILE = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", "bahnschrift.ttf")
|
||||
FALLBACK_FONT = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", "segoeuib.ttf")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- layout
|
||||
# All coordinates are in panel pixels for the GPU (left) half. The CPU half is
|
||||
# produced by mirroring x around the centre line.
|
||||
|
||||
R_GAUGE = 48.0
|
||||
R_FACE = 41.0
|
||||
ARC_R_OUT = 38.5
|
||||
ARC_W = 6.0
|
||||
ARC_START = 150.0 # degrees, 0 = 3 o'clock, clockwise
|
||||
ARC_SWEEP = 240.0
|
||||
G_TEMP = (52.0, 66.0)
|
||||
G_LOAD = (152.0, 66.0)
|
||||
DIGIT_CY = 62.0
|
||||
UNIT_CY = 88.0
|
||||
|
||||
TITLE_BOX = (80.0, 2.0, 124.0, 16.0)
|
||||
MHZ_BOX = (74.0, 112.0, 130.0, 126.0)
|
||||
PART_BOX = (170.0, 112.0, 212.0, 126.0) # this half's watts (CPU or GPU)
|
||||
|
||||
# Centre column (drawn once, not mirrored)
|
||||
TOTAL_BOX = (206.0, 2.0, 274.0, 16.0)
|
||||
OTHER_BOX = (218.0, 112.0, 262.0, 126.0)
|
||||
TANK_X0, TANK_X1 = 222.0, 258.0
|
||||
CAP_TOP = (17.0, 24.0)
|
||||
CAP_BOT = (97.0, 108.0)
|
||||
GLASS_X0, GLASS_X1 = TANK_X0 + 3.0, TANK_X1 - 3.0
|
||||
GLASS_Y0, GLASS_Y1 = CAP_TOP[1], CAP_BOT[0]
|
||||
|
||||
PIPE_T = 6.0
|
||||
_GY = math.sqrt(R_GAUGE ** 2 - 24.0 ** 2) # where x = cx - 24 meets the bezel
|
||||
PIPES = [
|
||||
[(28.0, G_TEMP[1] + _GY), (28.0, 119.0), (MHZ_BOX[0], 119.0)], # temp gauge -> MHz box
|
||||
[(MHZ_BOX[2], 119.0), (PART_BOX[0], 119.0)], # MHz box -> watt box
|
||||
[(28.0, G_TEMP[1] - _GY), (28.0, 9.0), (TITLE_BOX[0], 9.0)], # temp gauge -> title
|
||||
[(TITLE_BOX[2], 9.0), (TOTAL_BOX[0], 9.0)], # title -> total box
|
||||
]
|
||||
TANK_PIPE = [(W / 2, CAP_BOT[1]), (W / 2, OTHER_BOX[1])] # tank -> other box
|
||||
JUNCTION_PIPE = [(G_TEMP[0] + R_GAUGE - 4, 66.0), (G_LOAD[0] - R_GAUGE + 4, 66.0)]
|
||||
RIVETS = [(6.0, 6.0), (6.0, 122.0)]
|
||||
|
||||
COPPER = [
|
||||
(1.00, (64, 30, 16)),
|
||||
(0.84, (112, 56, 30)),
|
||||
(0.66, (156, 82, 48)),
|
||||
(0.46, (196, 116, 72)),
|
||||
(0.26, (228, 156, 110)),
|
||||
(0.09, (252, 212, 178)),
|
||||
]
|
||||
|
||||
# 5x7 dot-matrix glyphs
|
||||
GLYPHS = {
|
||||
"0": [".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###."],
|
||||
"1": ["..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."],
|
||||
"2": [".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"],
|
||||
"3": ["#####", "...#.", "..#..", "...#.", "....#", "#...#", ".###."],
|
||||
"4": ["...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."],
|
||||
"5": ["#####", "#....", "####.", "....#", "....#", "#...#", ".###."],
|
||||
"6": ["..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."],
|
||||
"7": ["#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."],
|
||||
"8": [".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."],
|
||||
"9": [".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."],
|
||||
"-": [".....", ".....", ".....", ".###.", ".....", ".....", "....."],
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- helpers
|
||||
|
||||
def _s(v: float) -> float:
|
||||
return v * SS
|
||||
|
||||
|
||||
def _font(size_px: float, style: str = "Bold") -> ImageFont.FreeTypeFont:
|
||||
try:
|
||||
f = ImageFont.truetype(FONT_FILE, round(size_px * SS))
|
||||
f.set_variation_by_name(style)
|
||||
return f
|
||||
except Exception:
|
||||
return ImageFont.truetype(FALLBACK_FONT, round(size_px * SS))
|
||||
|
||||
|
||||
def _grid(x0: float, y0: float, x1: float, y1: float):
|
||||
ix0 = max(0, int(math.floor(x0 * SS)))
|
||||
iy0 = max(0, int(math.floor(y0 * SS)))
|
||||
ix1 = min(W * SS, int(math.ceil(x1 * SS)))
|
||||
iy1 = min(H * SS, int(math.ceil(y1 * SS)))
|
||||
xs = (np.arange(ix0, ix1) + 0.5) / SS
|
||||
ys = (np.arange(iy0, iy1) + 0.5) / SS
|
||||
X, Y = np.meshgrid(xs, ys)
|
||||
return ix0, iy0, X, Y
|
||||
|
||||
|
||||
def _paste(canvas: Image.Image, ix0: int, iy0: int, rgb: np.ndarray, alpha: np.ndarray) -> None:
|
||||
arr = np.dstack([np.clip(rgb, 0, 255), np.clip(alpha, 0, 1) * 255]).astype(np.uint8)
|
||||
canvas.alpha_composite(Image.fromarray(arr, "RGBA"), (ix0, iy0))
|
||||
|
||||
|
||||
def _rrect_mask(X, Y, x0, y0, x1, y1, r):
|
||||
cx = np.clip(X, x0 + r, x1 - r)
|
||||
cy = np.clip(Y, y0 + r, y1 - r)
|
||||
return ((X - cx) ** 2 + (Y - cy) ** 2 <= r * r) & (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1)
|
||||
|
||||
|
||||
def _mix(lo, hi, t):
|
||||
lo = np.asarray(lo, dtype=float)
|
||||
hi = np.asarray(hi, dtype=float)
|
||||
return lo + (hi - lo) * np.asarray(t)[..., None]
|
||||
|
||||
|
||||
def _cyl_shade(u, hl=0.33, width=0.2, ambient=0.18):
|
||||
"""Cylinder lighting profile across a tube, u in 0..1."""
|
||||
u = np.clip(u, 0, 1)
|
||||
body = np.sin(np.pi * u) ** 0.6
|
||||
spec = np.exp(-((u - hl) / width) ** 2)
|
||||
return np.clip(ambient + 0.55 * body + 0.45 * spec, 0, 1)
|
||||
|
||||
|
||||
def cyl_rect(canvas, x0, y0, x1, y1, across, lo, hi, radius=0.0, hl=0.33, width=0.2, ambient=0.18):
|
||||
ix0, iy0, X, Y = _grid(x0, y0, x1, y1)
|
||||
u = (X - x0) / (x1 - x0) if across == "x" else (Y - y0) / (y1 - y0)
|
||||
rgb = _mix(lo, hi, _cyl_shade(u, hl, width, ambient))
|
||||
mask = _rrect_mask(X, Y, x0, y0, x1, y1, radius) if radius else (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1)
|
||||
_paste(canvas, ix0, iy0, rgb, mask.astype(float))
|
||||
|
||||
|
||||
def dome(canvas, cx, cy, rad, tint=(205, 205, 212)):
|
||||
ix0, iy0, X, Y = _grid(cx - rad - 1, cy - rad - 1, cx + rad + 1, cy + rad + 1)
|
||||
d = np.hypot(X - cx, Y - cy) / rad
|
||||
hl = np.exp(-(((X - cx + rad * 0.35) ** 2 + (Y - cy + rad * 0.35) ** 2) / (rad * 0.45) ** 2))
|
||||
v = 0.18 + 0.30 * np.sqrt(np.clip(1 - d ** 2, 0, 1)) + 0.65 * hl
|
||||
rgb = _mix((0, 0, 0), tint, np.clip(v, 0, 1.2))
|
||||
ring = np.clip((d - 0.82) / 0.18, 0, 1)
|
||||
rgb = rgb * (1 - 0.55 * ring[..., None])
|
||||
_paste(canvas, ix0, iy0, rgb, (d <= 1).astype(float))
|
||||
|
||||
|
||||
def _fillet(points, radius=5.0, steps=10):
|
||||
"""Round the corners of a polyline with quadratic Bezier curves."""
|
||||
pts = [np.array(p, dtype=float) for p in points]
|
||||
if len(pts) < 3:
|
||||
return [tuple(p) for p in pts]
|
||||
out = [tuple(pts[0])]
|
||||
for i in range(1, len(pts) - 1):
|
||||
p0, p1, p2 = pts[i - 1], pts[i], pts[i + 1]
|
||||
d1, d2 = np.linalg.norm(p0 - p1), np.linalg.norm(p2 - p1)
|
||||
r = min(radius, d1 / 2, d2 / 2)
|
||||
a = p1 + (p0 - p1) / d1 * r
|
||||
b = p1 + (p2 - p1) / d2 * r
|
||||
for t in np.linspace(0, 1, steps):
|
||||
q = (1 - t) ** 2 * a + 2 * (1 - t) * t * p1 + t ** 2 * b
|
||||
out.append(tuple(q))
|
||||
out.append(tuple(pts[-1]))
|
||||
return out
|
||||
|
||||
|
||||
def _extend(points, amount=2.0):
|
||||
"""Push both ends of a polyline outward so pipes tuck under their fittings."""
|
||||
pts = [np.array(p, dtype=float) for p in points]
|
||||
for end, nxt in ((0, 1), (-1, -2)):
|
||||
v = pts[end] - pts[nxt]
|
||||
n = np.linalg.norm(v)
|
||||
if n:
|
||||
pts[end] = pts[end] + v / n * amount
|
||||
return [tuple(p) for p in pts]
|
||||
|
||||
|
||||
class _Half:
|
||||
"""Coordinate mapping for one half; mirror=True maps the layout onto the right."""
|
||||
|
||||
def __init__(self, mirror: bool):
|
||||
self.mirror = mirror
|
||||
|
||||
def x(self, x: float) -> float:
|
||||
return W - x if self.mirror else x
|
||||
|
||||
def pt(self, p):
|
||||
return (self.x(p[0]), p[1])
|
||||
|
||||
def box(self, b):
|
||||
xa, xb = sorted((self.x(b[0]), self.x(b[2])))
|
||||
return (xa, b[1], xb, b[3])
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- renderer
|
||||
|
||||
class DashboardRenderer:
|
||||
def __init__(self, theme: Theme | None = None, rotate180: bool = False):
|
||||
self.theme = theme or Theme()
|
||||
self.rotate180 = rotate180
|
||||
self.halves = (_Half(False), _Half(True))
|
||||
self.f_title = _font(11, "Bold")
|
||||
self.f_unit = _font(9, "SemiBold")
|
||||
self.f_value = _font(10.5, "Bold SemiCondensed")
|
||||
self.f_small = _font(7, "SemiBold SemiCondensed")
|
||||
self._static = self._build_static()
|
||||
self._glass = self._build_glass_overlay()
|
||||
self._dome_light, self._dome_shade = self._build_dome_overlay()
|
||||
|
||||
# ------------------------------------------------------------------ static art
|
||||
|
||||
def _build_static(self) -> Image.Image:
|
||||
canvas = self._plate()
|
||||
self._shadows(canvas)
|
||||
for half in self.halves:
|
||||
for pipe in PIPES:
|
||||
self._pipe(canvas, [half.pt(p) for p in pipe])
|
||||
self._pipe(canvas, [half.pt(p) for p in JUNCTION_PIPE])
|
||||
self._pipe(canvas, TANK_PIPE)
|
||||
|
||||
for half in self.halves:
|
||||
for g in (G_TEMP, G_LOAD):
|
||||
self._gauge(canvas, half.x(g[0]), g[1])
|
||||
for b in (MHZ_BOX, PART_BOX, TITLE_BOX):
|
||||
self._box(canvas, half.box(b))
|
||||
self._tank(canvas)
|
||||
self._box(canvas, TOTAL_BOX)
|
||||
self._box(canvas, OTHER_BOX)
|
||||
|
||||
for half in self.halves:
|
||||
for pipe in PIPES:
|
||||
pts = [half.pt(p) for p in pipe]
|
||||
self._coupler(canvas, pts[0], pts[1])
|
||||
self._coupler(canvas, pts[-1], pts[-2])
|
||||
self._nut(canvas, half.x((JUNCTION_PIPE[0][0] + JUNCTION_PIPE[1][0]) / 2), 66.0)
|
||||
self._coupler(canvas, TANK_PIPE[0], TANK_PIPE[1])
|
||||
self._coupler(canvas, TANK_PIPE[1], TANK_PIPE[0])
|
||||
for x, y in RIVETS:
|
||||
for half in self.halves:
|
||||
dome(canvas, half.x(x), y, 2.3)
|
||||
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
glow = Image.new("RGB", canvas.size, (0, 0, 0))
|
||||
gdraw = ImageDraw.Draw(glow)
|
||||
for i, half in enumerate(self.halves):
|
||||
b = half.box(TITLE_BOX)
|
||||
c = (_s((b[0] + b[2]) / 2), _s((b[1] + b[3]) / 2 + 0.4))
|
||||
gdraw.text(c, self.theme.titles[i], font=self.f_title, fill=self.theme.accent, anchor="mm")
|
||||
for g, unit in ((G_TEMP, "\u00b0C"), (G_LOAD, "%")):
|
||||
draw.text((_s(half.x(g[0])), _s(UNIT_CY)), unit, font=self.f_unit,
|
||||
fill=(196, 196, 200), anchor="mm")
|
||||
glow = glow.filter(ImageFilter.GaussianBlur(_s(2.2)))
|
||||
rgb = ImageChops.screen(canvas.convert("RGB"), glow)
|
||||
canvas = rgb.convert("RGBA")
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
for i, half in enumerate(self.halves):
|
||||
b = half.box(TITLE_BOX)
|
||||
c = (_s((b[0] + b[2]) / 2), _s((b[1] + b[3]) / 2 + 0.4))
|
||||
draw.text(c, self.theme.titles[i], font=self.f_title, fill=self.theme.accent, anchor="mm")
|
||||
return canvas
|
||||
|
||||
def _plate(self) -> Image.Image:
|
||||
path = os.path.join(os.path.dirname(__file__), "background.png")
|
||||
with Image.open(path) as background:
|
||||
return background.convert("RGBA").resize((W * SS, H * SS), Image.Resampling.LANCZOS)
|
||||
|
||||
def _shadows(self, canvas: Image.Image) -> None:
|
||||
mask = Image.new("L", canvas.size, 0)
|
||||
d = ImageDraw.Draw(mask)
|
||||
for half in self.halves:
|
||||
for g in (G_TEMP, G_LOAD):
|
||||
cx, cy = half.x(g[0]), g[1]
|
||||
d.ellipse([_s(cx - R_GAUGE), _s(cy - R_GAUGE), _s(cx + R_GAUGE), _s(cy + R_GAUGE)], fill=255)
|
||||
for b in (MHZ_BOX, PART_BOX, TITLE_BOX):
|
||||
d.rectangle([_s(v) for v in half.box(b)], fill=255)
|
||||
for pipe in PIPES:
|
||||
d.line([(_s(x), _s(y)) for x, y in _fillet([half.pt(p) for p in pipe])],
|
||||
fill=255, width=round(_s(PIPE_T)), joint="curve")
|
||||
for b in (TOTAL_BOX, OTHER_BOX, (TANK_X0, CAP_TOP[0], TANK_X1, CAP_BOT[1])):
|
||||
d.rectangle([_s(v) for v in b], fill=255)
|
||||
d.line([(_s(x), _s(y)) for x, y in TANK_PIPE], fill=255, width=round(_s(PIPE_T)))
|
||||
mask = mask.filter(ImageFilter.GaussianBlur(_s(2.4)))
|
||||
shifted = Image.new("L", canvas.size, 0)
|
||||
shifted.paste(mask, (round(_s(1.4)), round(_s(2.0))))
|
||||
shade = np.asarray(shifted, dtype=float)[..., None] / 255
|
||||
arr = np.asarray(canvas, dtype=float).copy()
|
||||
arr[..., :3] *= 1 - 0.75 * shade
|
||||
canvas.paste(Image.fromarray(arr.astype(np.uint8), "RGBA"))
|
||||
|
||||
def _pipe(self, canvas, points) -> None:
|
||||
pts = _fillet(_extend(points, 2.5))
|
||||
d = ImageDraw.Draw(canvas)
|
||||
for frac, col in COPPER:
|
||||
off = -0.13 * PIPE_T * (1 - frac) if frac < 0.9 else 0.0
|
||||
d.line([(_s(x + off), _s(y + off)) for x, y in pts], fill=col,
|
||||
width=max(1, round(_s(PIPE_T * frac))), joint="curve")
|
||||
|
||||
def _coupler(self, canvas, end, toward) -> None:
|
||||
horizontal = abs(end[0] - toward[0]) > abs(end[1] - toward[1])
|
||||
x, y = end
|
||||
half_len, half_w = 1.7, PIPE_T / 2 + 1.0
|
||||
if horizontal:
|
||||
cyl_rect(canvas, x - half_len, y - half_w, x + half_len, y + half_w, "y",
|
||||
(10, 10, 12), (170, 170, 176), radius=0.6)
|
||||
else:
|
||||
cyl_rect(canvas, x - half_w, y - half_len, x + half_w, y + half_len, "x",
|
||||
(10, 10, 12), (170, 170, 176), radius=0.6)
|
||||
|
||||
def _nut(self, canvas, x, y) -> None:
|
||||
hw, hh = 3.4, PIPE_T / 2 + 2.2
|
||||
cyl_rect(canvas, x - hw, y - hh, x + hw, y + hh, "y", (12, 12, 14), (190, 190, 196), radius=0.8)
|
||||
d = ImageDraw.Draw(canvas)
|
||||
for fx in (-1.15, 1.15):
|
||||
d.line([(_s(x + fx), _s(y - hh + 0.4)), (_s(x + fx), _s(y + hh - 0.4))],
|
||||
fill=(20, 20, 22), width=round(_s(0.45)))
|
||||
|
||||
def _gauge(self, canvas, cx, cy) -> None:
|
||||
ix0, iy0, X, Y = _grid(cx - R_GAUGE - 1, cy - R_GAUGE - 1, cx + R_GAUGE + 1, cy + R_GAUGE + 1)
|
||||
dx, dy = X - cx, Y - cy
|
||||
r = np.hypot(dx, dy)
|
||||
phi = np.arctan2(dy, dx)
|
||||
light = np.cos(phi - math.radians(225))
|
||||
t = np.clip((r - R_FACE) / (R_GAUGE - R_FACE), 0, 1)
|
||||
prof = np.sin(t * np.pi)
|
||||
v = 0.17 + 0.16 * prof + 0.20 * light * (0.35 + 0.65 * prof)
|
||||
v += 0.30 * np.exp(-((R_GAUGE - 0.7 - r) / 0.45) ** 2) * (0.45 + 0.55 * light)
|
||||
v -= 0.12 * np.exp(-((r - R_FACE - 0.5) / 0.6) ** 2)
|
||||
v += 0.018 * np.sin(r * SS * 2.2)
|
||||
face = 0.03 + 0.05 * (1 - r / R_FACE) ** 2
|
||||
face = face * (0.45 + 0.55 * np.clip((R_FACE - r) / 3.5, 0, 1))
|
||||
val = np.where(r < R_FACE, face, v)
|
||||
rgb = _mix((0, 0, 0), (238, 240, 246), np.clip(val, 0, 1))
|
||||
_paste(canvas, ix0, iy0, rgb, (r <= R_GAUGE).astype(float))
|
||||
|
||||
d = ImageDraw.Draw(canvas)
|
||||
# arc groove
|
||||
for rad, width, col in ((ARC_R_OUT + 0.8, ARC_W + 1.6, (54, 54, 58)), (ARC_R_OUT, ARC_W, (20, 20, 22))):
|
||||
bb = [_s(cx - rad), _s(cy - rad), _s(cx + rad), _s(cy + rad)]
|
||||
d.arc(bb, ARC_START, ARC_START + ARC_SWEEP, fill=col, width=round(_s(width)))
|
||||
# bolts on the bezel
|
||||
for a in (45, 135, 225, 315):
|
||||
ar = math.radians(a)
|
||||
dome(canvas, cx + 44.5 * math.cos(ar), cy + 44.5 * math.sin(ar), 1.7, tint=(170, 170, 178))
|
||||
|
||||
def _tank(self, canvas) -> None:
|
||||
x0, x1 = TANK_X0, TANK_X1
|
||||
chrome = ((22, 22, 25), (236, 236, 242))
|
||||
# glass background
|
||||
cyl_rect(canvas, GLASS_X0, GLASS_Y0 - 1, GLASS_X1, GLASS_Y1 + 1, "x", (6, 6, 8), (40, 40, 46),
|
||||
hl=0.3, width=0.25)
|
||||
# end caps with grooves
|
||||
for y0, y1 in (CAP_TOP, CAP_BOT):
|
||||
cyl_rect(canvas, x0, y0, x1, y1, "x", *chrome, radius=1.4)
|
||||
d = ImageDraw.Draw(canvas)
|
||||
for gy in (CAP_TOP[0] + 2.4, 100.5, 105.0):
|
||||
d.line([(_s(x0 + 0.6), _s(gy)), (_s(x1 - 0.6), _s(gy))], fill=(30, 30, 34, 200), width=round(_s(0.6)))
|
||||
for y0, y1 in ((CAP_TOP[1] - 2.2, CAP_TOP[1]), (CAP_BOT[0], CAP_BOT[0] + 2.2)):
|
||||
cyl_rect(canvas, x0 + 1, y0, x1 - 1, y1, "x", (10, 10, 12), (110, 110, 116))
|
||||
|
||||
def _build_glass_overlay(self) -> Image.Image:
|
||||
layer = Image.new("RGBA", (W * SS, H * SS), (0, 0, 0, 0))
|
||||
gx0, gx1 = GLASS_X0, GLASS_X1
|
||||
ix0, iy0, X, Y = _grid(gx0, GLASS_Y0, gx1, GLASS_Y1)
|
||||
u = (X - gx0) / (gx1 - gx0)
|
||||
a = 0.38 * np.exp(-((u - 0.24) / 0.04) ** 2) + 0.12 * np.exp(-((u - 0.80) / 0.04) ** 2)
|
||||
edge = np.exp(-(u / 0.05) ** 2) + np.exp(-((1 - u) / 0.05) ** 2)
|
||||
top_shadow = np.clip(1 - (Y - GLASS_Y0) / 3.0, 0, 1)
|
||||
rgb = np.where((edge > 0.3)[..., None], 0.0, 255.0) * np.ones(3)
|
||||
alpha = np.maximum(a, np.maximum(0.55 * edge, 0.65 * top_shadow))
|
||||
rgb = np.where((top_shadow * 0.65 > a)[..., None], 0.0, rgb)
|
||||
_paste(layer, ix0, iy0, rgb, alpha)
|
||||
# scale: a tick every 10% of the power supply's rating, a longer one at 50%
|
||||
d = ImageDraw.Draw(layer)
|
||||
span = GLASS_Y1 - GLASS_Y0
|
||||
for i in range(1, 10):
|
||||
y = GLASS_Y1 - span * i / 10
|
||||
length = 3.5 if i == 5 else 2.0
|
||||
for xa, xb in ((gx0 + 1.5, gx0 + 1.5 + length), (gx1 - 1.5 - length, gx1 - 1.5)):
|
||||
d.line([(_s(xa), _s(y)), (_s(xb), _s(y))], fill=(230, 230, 235, 130), width=round(_s(0.5)))
|
||||
return layer
|
||||
|
||||
def _build_dome_overlay(self) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Reflections of a glass dome over each gauge face, lit from the top left.
|
||||
|
||||
Returns panel-sized (H, W, 1) maps: `light` is screened over the finished
|
||||
frame (so it also sits over the glowing arcs and digits) and `shade` multiplies it.
|
||||
"""
|
||||
light = np.zeros((H * SS, W * SS))
|
||||
shade = np.ones((H * SS, W * SS))
|
||||
rad = R_FACE - 0.2
|
||||
for half in self.halves:
|
||||
for g in (G_TEMP, G_LOAD):
|
||||
cx, cy = half.x(g[0]), g[1]
|
||||
ix0, iy0, X, Y = _grid(cx - rad - 1, cy - rad - 1, cx + rad + 1, cy + rad + 1)
|
||||
u, v = (X - cx) / rad, (Y - cy) / rad
|
||||
r = np.hypot(u, v)
|
||||
inside = np.clip((1 - r) * rad * 1.5, 0, 1)
|
||||
# broad crescent sheen: inside the dome but outside a circle offset to the lower right
|
||||
inner = np.hypot(u - 0.10, v - 0.20) / 0.93
|
||||
crescent = np.clip((inner - 1) * 9, 0, 1) * np.clip((0.98 - r) * 25, 0, 1)
|
||||
towards = np.clip(0.55 - 0.75 * (u * 0.55 + v * 0.83), 0, 1)
|
||||
sheen = 0.42 * crescent * towards
|
||||
# window highlight up and to the left
|
||||
a, b = (u + v + 0.95) / 1.414, (v - u + 0.18) / 1.414
|
||||
spot = 0.75 * np.exp(-(a / 0.07) ** 2 - (b / 0.30) ** 2) + 0.12 * np.exp(-(a / 0.22) ** 2 - (b / 0.45) ** 2)
|
||||
# faint bounce along the lower-right rim
|
||||
ang = np.arctan2(v, u)
|
||||
bounce = 0.13 * np.exp(-((r - 0.93) / 0.035) ** 2) * np.clip(np.cos(ang - math.radians(60)), 0, 1) ** 2
|
||||
haze = 0.04 * (1 - r ** 2).clip(0, 1)
|
||||
hi = (np.maximum(sheen, spot) + bounce + haze) * inside
|
||||
dark = 1 - 0.30 * np.clip((r - 0.80) / 0.20, 0, 1) ** 2 * inside
|
||||
sl = (slice(iy0, iy0 + hi.shape[0]), slice(ix0, ix0 + hi.shape[1]))
|
||||
light[sl] = np.maximum(light[sl], hi)
|
||||
shade[sl] = np.minimum(shade[sl], dark)
|
||||
|
||||
def small(m: np.ndarray) -> np.ndarray:
|
||||
img = Image.fromarray(np.clip(m * 255, 0, 255).astype(np.uint8), "L")
|
||||
return np.asarray(img.resize((W, H), Image.Resampling.BOX), dtype=float)[..., None] / 255
|
||||
|
||||
return small(light), small(shade)
|
||||
|
||||
def _box(self, canvas, b) -> None:
|
||||
x0, y0, x1, y1 = b
|
||||
ix0, iy0, X, Y = _grid(x0, y0, x1, y1)
|
||||
t = (Y - y0) / (y1 - y0)
|
||||
frame = _mix((40, 40, 44), (215, 215, 222), np.clip(1.05 - 1.1 * t, 0, 1))
|
||||
_paste(canvas, ix0, iy0, frame, _rrect_mask(X, Y, x0, y0, x1, y1, 2.2).astype(float))
|
||||
i = 1.4
|
||||
inner = _mix((4, 4, 5), (20, 20, 23), t)
|
||||
inner_shadow = np.clip((Y - (y0 + i)) / 2.0, 0, 1)
|
||||
inner = inner * (0.4 + 0.6 * inner_shadow)[..., None]
|
||||
_paste(canvas, ix0, iy0, inner, _rrect_mask(X, Y, x0 + i, y0 + i, x1 - i, y1 - i, 1.2).astype(float))
|
||||
|
||||
# ------------------------------------------------------------------ dynamic
|
||||
|
||||
def render(self, cpu: Readings, gpu: Readings, power: PowerReadings | None = None) -> Image.Image:
|
||||
if power is None:
|
||||
power = PowerReadings(cpu=cpu.power, gpu=gpu.power)
|
||||
canvas = self._static.copy()
|
||||
glow = Image.new("RGB", canvas.size, (0, 0, 0))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
gdraw = ImageDraw.Draw(glow)
|
||||
th = self.theme
|
||||
|
||||
for half, rd, temp_range in ((self.halves[0], gpu, th.gpu_temp_range),
|
||||
(self.halves[1], cpu, th.cpu_temp_range)):
|
||||
reverse = half.mirror and th.mirror_gauge_direction
|
||||
# gauges
|
||||
gauges = (
|
||||
(G_TEMP, rd.temp, *temp_range, th.temp_warn, th.temp_hot),
|
||||
(G_LOAD, rd.load, 0.0, 100.0, th.load_warn, th.load_hot),
|
||||
)
|
||||
for g, value, lo, hi, warn, hot in gauges:
|
||||
cx, cy = half.x(g[0]), g[1]
|
||||
frac = None if value is None else min(1.0, max(0.0, (value - lo) / (hi - lo)))
|
||||
if frac:
|
||||
self._arc_fill(draw, gdraw, cx, cy, frac, reverse, th.level_color(value, warn, hot))
|
||||
self._digits(draw, gdraw, cx, DIGIT_CY, value)
|
||||
self._readout(draw, half.box(MHZ_BOX), rd.clock, "MHz")
|
||||
|
||||
# power column: stacked tank, its parts along the bottom, the sum on top
|
||||
self._liquid(canvas, power)
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
self._readout(draw, self.halves[0].box(PART_BOX), power.gpu, "W", swatch=th.gpu_color)
|
||||
self._readout(draw, self.halves[1].box(PART_BOX), power.cpu, "W", swatch=th.cpu_color)
|
||||
self._readout(draw, OTHER_BOX, power.other, "W", swatch=th.other_color)
|
||||
self._readout(draw, TOTAL_BOX, power.total, "W", prefix="TOTAL")
|
||||
|
||||
small = canvas.convert("RGB").resize((W, H), Image.LANCZOS)
|
||||
g_small = glow.resize((W, H), Image.BOX).filter(ImageFilter.GaussianBlur(2.0))
|
||||
g_small = Image.eval(g_small, lambda v: min(255, int(v * 0.85)))
|
||||
out = ImageChops.screen(small, g_small)
|
||||
arr = np.asarray(out, dtype=float) * self._dome_shade
|
||||
arr += (255 - arr) * self._dome_light
|
||||
out = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), "RGB")
|
||||
if self.rotate180:
|
||||
out = out.transpose(Image.ROTATE_180)
|
||||
return out
|
||||
|
||||
def _arc_fill(self, draw, gdraw, cx, cy, frac, reverse, acc) -> None:
|
||||
sweep = ARC_SWEEP * frac
|
||||
if reverse:
|
||||
end = ARC_START + ARC_SWEEP
|
||||
start = end - sweep
|
||||
else:
|
||||
start, end = ARC_START, ARC_START + sweep
|
||||
dark = tuple(int(c * 0.55) for c in acc)
|
||||
light = tuple(min(255, int(c + (255 - c) * 0.45)) for c in acc)
|
||||
layers = (
|
||||
(ARC_R_OUT - 0.3, ARC_W - 0.6, dark),
|
||||
(ARC_R_OUT - 0.9, ARC_W - 1.8, acc),
|
||||
(ARC_R_OUT - 1.9, 1.1, light),
|
||||
)
|
||||
for rad, width, col in layers:
|
||||
bb = [_s(cx - rad), _s(cy - rad), _s(cx + rad), _s(cy + rad)]
|
||||
draw.arc(bb, start, end, fill=col, width=round(_s(width)))
|
||||
bb = [_s(cx - ARC_R_OUT), _s(cy - ARC_R_OUT), _s(cx + ARC_R_OUT), _s(cy + ARC_R_OUT)]
|
||||
gdraw.arc(bb, start, end, fill=acc, width=round(_s(ARC_W)))
|
||||
|
||||
def _digits(self, draw, gdraw, cx, cy, value) -> None:
|
||||
text = "--" if value is None else str(int(round(value)))
|
||||
pitch = 4.0 if len(text) <= 2 else 3.2 # 3 digits ("100") need a finer grid to fit
|
||||
gap = pitch
|
||||
total = len(text) * 5 * pitch + (len(text) - 1) * gap
|
||||
left = cx - total / 2
|
||||
top = cy - 7 * pitch / 2
|
||||
rad = pitch * 0.40
|
||||
for i, ch in enumerate(text):
|
||||
glyph = GLYPHS.get(ch, GLYPHS["-"])
|
||||
for row in range(7):
|
||||
for col in range(5):
|
||||
x = left + i * (5 * pitch + gap) + col * pitch + pitch / 2
|
||||
y = top + row * pitch + pitch / 2
|
||||
bb = [_s(x - rad), _s(y - rad), _s(x + rad), _s(y + rad)]
|
||||
if glyph[row][col] == "#":
|
||||
draw.ellipse(bb, fill=(248, 248, 250))
|
||||
gdraw.ellipse(bb, fill=(150, 150, 155))
|
||||
else:
|
||||
draw.ellipse(bb, fill=(30, 30, 33))
|
||||
|
||||
def _liquid(self, canvas, power: PowerReadings) -> None:
|
||||
"""Stack other / CPU / GPU from the bottom of the glass, scaled to the PSU rating."""
|
||||
th = self.theme
|
||||
gx0, gx1 = GLASS_X0, GLASS_X1
|
||||
span = GLASS_Y1 - GLASS_Y0
|
||||
layers = ((power.other, th.other_color), (power.cpu, th.cpu_color), (power.gpu, th.gpu_color))
|
||||
base = GLASS_Y1
|
||||
tops: list[tuple[float, tuple[int, int, int]]] = []
|
||||
for watts, acc in layers:
|
||||
if not watts or watts <= 0 or base <= GLASS_Y0:
|
||||
continue
|
||||
top = max(GLASS_Y0, base - span * watts / th.psu_watts)
|
||||
lo = tuple(int(c * 0.22) for c in acc)
|
||||
hi = tuple(min(255, int(c + (255 - c) * 0.12)) for c in acc)
|
||||
cyl_rect(canvas, gx0, top, gx1, base, "x", lo, hi, hl=0.32, width=0.24, ambient=0.12)
|
||||
tops.append((top, acc))
|
||||
base = top
|
||||
d = ImageDraw.Draw(canvas)
|
||||
# a dark gap between layers, then a bright meniscus on the top one
|
||||
for top, _ in tops[:-1]:
|
||||
d.line([(_s(gx0), _s(top)), (_s(gx1), _s(top))], fill=(6, 6, 8), width=round(_s(0.5)))
|
||||
if tops:
|
||||
top, acc = tops[-1]
|
||||
d.line([(_s(gx0 + 0.5), _s(top + 0.3)), (_s(gx1 - 0.5), _s(top + 0.3))],
|
||||
fill=tuple(min(255, int(c + (255 - c) * 0.5)) for c in acc), width=round(_s(0.7)))
|
||||
# glass reflections and scale on top of the liquid
|
||||
ix0 = int(math.floor(gx0 * SS))
|
||||
iy0 = int(math.floor(GLASS_Y0 * SS))
|
||||
box = (ix0, iy0, int(math.ceil(gx1 * SS)), int(math.ceil(GLASS_Y1 * SS)))
|
||||
canvas.alpha_composite(self._glass.crop(box), (ix0, iy0))
|
||||
|
||||
def _readout(self, draw, b, value, unit, swatch=None, prefix=None) -> None:
|
||||
"""Value + unit centred in a box, optionally led by a colour swatch or a small label."""
|
||||
x0, y0, x1, y1 = b
|
||||
text = "--" if value is None else f"{value:.0f}"
|
||||
gap = 1.2
|
||||
wv = self.f_value.getlength(text) / SS
|
||||
wu = self.f_small.getlength(unit) / SS
|
||||
lead = 0.0
|
||||
if swatch is not None:
|
||||
lead = 4.0 + 2.6
|
||||
elif prefix:
|
||||
lead = self.f_small.getlength(prefix) / SS + 2.6
|
||||
start = (x0 + x1) / 2 - (lead + wv + gap + wu) / 2
|
||||
cy = (y0 + y1) / 2 + 0.3
|
||||
if swatch is not None:
|
||||
draw.rounded_rectangle([_s(start), _s(cy - 3.6), _s(start + 4.0), _s(cy + 3.4)],
|
||||
radius=_s(1.0), fill=swatch)
|
||||
elif prefix:
|
||||
draw.text((_s(start), _s(cy + 1.0)), prefix, font=self.f_small, fill=(170, 170, 176), anchor="lm")
|
||||
start += lead
|
||||
draw.text((_s(start), _s(cy)), text, font=self.f_value, fill=(245, 245, 248), anchor="lm")
|
||||
draw.text((_s(start + wv + gap), _s(cy + 1.0)), unit, font=self.f_small, fill=(170, 170, 176), anchor="lm")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
import time
|
||||
|
||||
ap = argparse.ArgumentParser(description="Render a preview of the dashboard to PNG")
|
||||
ap.add_argument("out", nargs="?", default="preview.png")
|
||||
ap.add_argument("--zoom", type=int, default=3)
|
||||
args = ap.parse_args()
|
||||
|
||||
t0 = time.perf_counter()
|
||||
r = DashboardRenderer()
|
||||
t1 = time.perf_counter()
|
||||
img = r.render(Readings(49, 11, 3114, 36.2), Readings(76, 88, 2700, 313),
|
||||
PowerReadings(cpu=36.2, gpu=313, other=78))
|
||||
t2 = time.perf_counter()
|
||||
print(f"static build {1000 * (t1 - t0):.0f} ms, frame {1000 * (t2 - t1):.0f} ms")
|
||||
img.save(args.out)
|
||||
if args.zoom > 1:
|
||||
root, ext = os.path.splitext(args.out)
|
||||
img.resize((W * args.zoom, H * args.zoom), Image.NEAREST).save(f"{root}_x{args.zoom}{ext}")
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Display service: keeps the Thermaltake 3.9" LCD showing the latest telemetry.
|
||||
|
||||
Reconnects after sleep, unplugging or a firmware hang. The panel falls back to its own
|
||||
screen if it gets no frame for a few seconds, so a frame goes out at least every 1.5 s even
|
||||
if telemetry stalls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.display.renderer import DashboardRenderer
|
||||
from kurgan.display.tt_lcd import LcdError, LcdNotFound, ThermaltakeLcd, encode_jpeg
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DisplayService:
|
||||
def __init__(self, renderer: DashboardRenderer, telemetry: Telemetry, brightness: int = 100):
|
||||
self.renderer = renderer
|
||||
self.telemetry = telemetry
|
||||
self.brightness = brightness
|
||||
self.status = "Starting"
|
||||
self.connected = False
|
||||
self.frames = 0
|
||||
|
||||
def _set_status(self, text: str, connected: bool) -> None:
|
||||
self.status, self.connected = text, connected
|
||||
|
||||
def render(self, sample=None):
|
||||
if sample is None:
|
||||
return self.renderer.render(Readings(), Readings(), PowerReadings())
|
||||
return self.renderer.render(sample.cpu, sample.gpu, sample.power)
|
||||
|
||||
def run(self, stop: threading.Event) -> None:
|
||||
lcd: ThermaltakeLcd | None = None
|
||||
last_heartbeat = 0.0
|
||||
missed_acks = 0
|
||||
waiting_logged = False
|
||||
seq = 0
|
||||
while not stop.is_set():
|
||||
try:
|
||||
if lcd is None:
|
||||
lcd = ThermaltakeLcd(brightness=self.brightness)
|
||||
lcd.open()
|
||||
log.info("LCD connected")
|
||||
self._set_status("LCD connected", True)
|
||||
waiting_logged = False
|
||||
missed_acks = 0
|
||||
sample = self.telemetry.wait_newer(seq, timeout=1.5)
|
||||
if stop.is_set():
|
||||
break
|
||||
seq = sample.seq if sample is not None else seq
|
||||
t0 = time.monotonic()
|
||||
if lcd.send_jpeg(encode_jpeg(self.render(sample))):
|
||||
missed_acks = 0
|
||||
self.frames += 1
|
||||
else:
|
||||
missed_acks += 1
|
||||
if missed_acks >= 5:
|
||||
raise LcdError("LCD stopped acknowledging frames")
|
||||
if t0 - last_heartbeat >= 2.0:
|
||||
lcd.heartbeat()
|
||||
last_heartbeat = t0
|
||||
except LcdNotFound:
|
||||
if not waiting_logged:
|
||||
log.info("Waiting for the LCD to appear...")
|
||||
self._set_status("Waiting for the LCD...", False)
|
||||
waiting_logged = True
|
||||
lcd = None
|
||||
stop.wait(3)
|
||||
except (LcdError, OSError) as e:
|
||||
log.warning("LCD error, reconnecting: %s", e)
|
||||
self._set_status("LCD error, reconnecting...", False)
|
||||
if lcd is not None:
|
||||
lcd.close()
|
||||
lcd = None
|
||||
stop.wait(3)
|
||||
except Exception:
|
||||
log.exception("Unexpected LCD error; retrying")
|
||||
if lcd is not None:
|
||||
lcd.close()
|
||||
lcd = None
|
||||
stop.wait(5)
|
||||
if lcd is not None:
|
||||
lcd.close()
|
||||
self._set_status("Stopped", False)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"status": self.status, "connected": self.connected, "frames": self.frames}
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Driver for the Thermaltake 3.9" bar LCD (USB 264A:233D, 480x128) on Windows.
|
||||
|
||||
Talks to the panel through the stock Windows HID driver using only ctypes.
|
||||
|
||||
Protocol (as documented by the ttlcd, thermaltaked and Tower-500-LCD-Controller
|
||||
projects):
|
||||
* Interface 0 (MI_00) is the command channel: 440-byte reports.
|
||||
handshake : 85, 87, 85, 87, 84, 81 each as [op, 01, 00, 80], each acknowledged
|
||||
brightness : [12, 01, 00, 80, percent]
|
||||
heartbeat : [82, 01, 00, 80] (every ~2 s)
|
||||
* Interface 1 (MI_01) is the frame channel: 1024-byte reports carrying a
|
||||
baseline JPEG split into 1020-byte chunks.
|
||||
first packet : [08, packet_count, 00, 80] + data
|
||||
next packets : [08, index, 00, 00] + data
|
||||
One acknowledgement arrives after the whole frame.
|
||||
* No report IDs are used, so every write is prefixed with a 0x00 byte.
|
||||
* If no frame arrives for a few seconds the panel goes back to its own screen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import threading
|
||||
|
||||
from kurgan.hardware.hid import HidChannel, HidError, hid_device_paths
|
||||
|
||||
VENDOR_ID = 0x264A
|
||||
PRODUCT_ID = 0x233D
|
||||
WIDTH = 480
|
||||
HEIGHT = 128
|
||||
|
||||
COMMAND_SIZE = 440
|
||||
FRAME_PACKET_SIZE = 1024
|
||||
FRAME_DATA_SIZE = FRAME_PACKET_SIZE - 4
|
||||
MAX_FRAME_PACKETS = 255
|
||||
|
||||
HANDSHAKE_OPCODES = (0x85, 0x87, 0x85, 0x87, 0x84, 0x81)
|
||||
OP_HEARTBEAT = 0x82
|
||||
OP_BRIGHTNESS = 0x12
|
||||
OP_FRAME = 0x08
|
||||
|
||||
REPLY_TIMEOUT_MS = 2000
|
||||
|
||||
|
||||
# The panel's own errors share the HID layer's exception, so callers catch one type.
|
||||
LcdError = HidError
|
||||
|
||||
|
||||
class LcdNotFound(LcdError):
|
||||
pass
|
||||
|
||||
|
||||
def find_interfaces() -> dict[int, str]:
|
||||
"""Return {interface_number: device_path} for the panel's HID interfaces."""
|
||||
found: dict[int, str] = {}
|
||||
for path in hid_device_paths(VENDOR_ID, PRODUCT_ID):
|
||||
low = path.lower()
|
||||
if "&mi_00" in low:
|
||||
found[0] = path
|
||||
elif "&mi_01" in low:
|
||||
found[1] = path
|
||||
return found
|
||||
|
||||
|
||||
def _command(*prefix: int) -> bytes:
|
||||
return bytes(prefix).ljust(COMMAND_SIZE, b"\x00")
|
||||
|
||||
|
||||
def frame_packets(jpeg: bytes) -> list[bytes]:
|
||||
if not (jpeg[:2] == b"\xff\xd8" and jpeg[-2:] == b"\xff\xd9"):
|
||||
raise LcdError("Frame is not a complete JPEG")
|
||||
count = math.ceil(len(jpeg) / FRAME_DATA_SIZE)
|
||||
if not 1 <= count <= MAX_FRAME_PACKETS:
|
||||
raise LcdError(f"JPEG too large ({len(jpeg)} bytes)")
|
||||
packets = []
|
||||
for index in range(count):
|
||||
chunk = jpeg[index * FRAME_DATA_SIZE:(index + 1) * FRAME_DATA_SIZE]
|
||||
header = bytes((OP_FRAME, count, 0x00, 0x80)) if index == 0 else bytes((OP_FRAME, index, 0x00, 0x00))
|
||||
packets.append((header + chunk).ljust(FRAME_PACKET_SIZE, b"\x00"))
|
||||
return packets
|
||||
|
||||
|
||||
class ThermaltakeLcd:
|
||||
"""Open with `with ThermaltakeLcd() as lcd:` then call send_jpeg() at least every 2 s."""
|
||||
|
||||
def __init__(self, brightness: int = 100):
|
||||
self.brightness = max(0, min(100, int(brightness)))
|
||||
self.command: HidChannel | None = None
|
||||
self.frame: HidChannel | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def open(self) -> None:
|
||||
paths = find_interfaces()
|
||||
if 0 not in paths or 1 not in paths:
|
||||
raise LcdNotFound("Thermaltake 3.9\" LCD (264A:233D) not found")
|
||||
self.command = HidChannel(paths[0], COMMAND_SIZE)
|
||||
try:
|
||||
self.frame = HidChannel(paths[1], FRAME_PACKET_SIZE)
|
||||
self._handshake()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
for ch in (self.frame, self.command):
|
||||
if ch is not None:
|
||||
ch.close()
|
||||
self.frame = self.command = None
|
||||
|
||||
def __enter__(self) -> "ThermaltakeLcd":
|
||||
self.open()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def _handshake(self) -> None:
|
||||
assert self.command and self.frame
|
||||
self.frame.drain()
|
||||
self.command.drain()
|
||||
with self._lock:
|
||||
for op in HANDSHAKE_OPCODES:
|
||||
self.command.send(_command(op, 0x01, 0x00, 0x80))
|
||||
if self.command.read(REPLY_TIMEOUT_MS) is None:
|
||||
raise LcdError(f"No reply to handshake opcode 0x{op:02X}")
|
||||
self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness))
|
||||
|
||||
def set_brightness(self, percent: int) -> None:
|
||||
self.brightness = max(0, min(100, int(percent)))
|
||||
with self._lock:
|
||||
self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness))
|
||||
|
||||
def heartbeat(self) -> None:
|
||||
with self._lock:
|
||||
self.command.drain()
|
||||
self.command.send(_command(OP_HEARTBEAT, 0x01, 0x00, 0x80))
|
||||
|
||||
def send_jpeg(self, jpeg: bytes) -> bool:
|
||||
"""Send one JPEG frame. Returns True if the panel acknowledged it."""
|
||||
packets = frame_packets(jpeg)
|
||||
self.frame.drain()
|
||||
for packet in packets:
|
||||
self.frame.send(packet)
|
||||
return self.frame.read(REPLY_TIMEOUT_MS) is not None
|
||||
|
||||
|
||||
def encode_jpeg(image, quality: int = 90) -> bytes:
|
||||
"""Encode a 480x128 PIL image as a baseline JPEG the panel accepts."""
|
||||
import io
|
||||
|
||||
if image.size != (WIDTH, HEIGHT):
|
||||
raise ValueError(f"Frame must be {WIDTH}x{HEIGHT}, got {image.size}")
|
||||
out = io.BytesIO()
|
||||
image.convert("RGB").save(out, format="JPEG", quality=quality, optimize=True,
|
||||
progressive=False, subsampling=0)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Quick hardware test: draws a test card for a few seconds.
|
||||
import time
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
print("Interfaces:", find_interfaces())
|
||||
with ThermaltakeLcd() as lcd:
|
||||
print(f"Handshake OK. Report lengths: cmd out={lcd.command.output_len} in={lcd.command.input_len}, "
|
||||
f"frame out={lcd.frame.output_len} in={lcd.frame.input_len}")
|
||||
for i in range(8):
|
||||
img = Image.new("RGB", (WIDTH, HEIGHT), (10, 10, 14))
|
||||
d = ImageDraw.Draw(img)
|
||||
for x, col in enumerate([(220, 30, 40), (40, 200, 60), (40, 90, 230), (240, 240, 240)]):
|
||||
d.rectangle([x * 120, 0, x * 120 + 119, 30], fill=col)
|
||||
d.rectangle([0, 0, WIDTH - 1, HEIGHT - 1], outline=(255, 255, 0))
|
||||
d.text((10, 50), f"LEFT test frame {i + 1}/8", fill=(255, 255, 255), font_size=24)
|
||||
d.text((400, 100), "RIGHT", fill=(255, 255, 255), font_size=16)
|
||||
ack = lcd.send_jpeg(encode_jpeg(img))
|
||||
print(f"frame {i + 1}: ack={ack}")
|
||||
lcd.heartbeat()
|
||||
time.sleep(1)
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Low-level device access shared by the capabilities: Win32 HID and the PawnIO modules."""
|
||||
|
||||
import os
|
||||
|
||||
# PawnIO's signed kernel modules (PawnIO.Modules 0.2.12, LGPL-2.1): Intel MSR, Super I/O, SMBus.
|
||||
PAWNIO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pawnio")
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Overlapped Win32 HID access shared by every USB device The Kurgan drives
|
||||
(the Thermaltake LCD, the Corsair Commander PRO and the Lighting Node CORE).
|
||||
|
||||
Uses only ctypes and the stock Windows HID driver.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
|
||||
|
||||
class HidError(Exception):
|
||||
"""A HID device could not be opened, written or read."""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- Win32
|
||||
|
||||
_setupapi = ctypes.WinDLL("setupapi", use_last_error=True)
|
||||
_hid = ctypes.WinDLL("hid", use_last_error=True)
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
_INVALID_HANDLE = wt.HANDLE(-1).value
|
||||
_DIGCF_PRESENT = 0x02
|
||||
_DIGCF_DEVICEINTERFACE = 0x10
|
||||
_GENERIC_READ = 0x80000000
|
||||
_GENERIC_WRITE = 0x40000000
|
||||
_FILE_SHARE_READ = 0x01
|
||||
_FILE_SHARE_WRITE = 0x02
|
||||
_OPEN_EXISTING = 3
|
||||
_FILE_FLAG_OVERLAPPED = 0x40000000
|
||||
_ERROR_IO_PENDING = 997
|
||||
_ERROR_NO_MORE_ITEMS = 259
|
||||
_WAIT_OBJECT_0 = 0
|
||||
_WAIT_TIMEOUT = 0x102
|
||||
|
||||
|
||||
class _GUID(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Data1", wt.DWORD),
|
||||
("Data2", wt.WORD),
|
||||
("Data3", wt.WORD),
|
||||
("Data4", ctypes.c_ubyte * 8),
|
||||
]
|
||||
|
||||
|
||||
class _SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("cbSize", wt.DWORD),
|
||||
("InterfaceClassGuid", _GUID),
|
||||
("Flags", wt.DWORD),
|
||||
("Reserved", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
|
||||
class _HIDP_CAPS(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Usage", wt.USHORT),
|
||||
("UsagePage", wt.USHORT),
|
||||
("InputReportByteLength", wt.USHORT),
|
||||
("OutputReportByteLength", wt.USHORT),
|
||||
("FeatureReportByteLength", wt.USHORT),
|
||||
("Reserved", wt.USHORT * 17),
|
||||
("Counts", wt.USHORT * 10),
|
||||
]
|
||||
|
||||
|
||||
class _OVERLAPPED(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Internal", ctypes.c_size_t),
|
||||
("InternalHigh", ctypes.c_size_t),
|
||||
("Offset", wt.DWORD),
|
||||
("OffsetHigh", wt.DWORD),
|
||||
("hEvent", wt.HANDLE),
|
||||
]
|
||||
|
||||
|
||||
_hid.HidD_GetHidGuid.argtypes = [ctypes.POINTER(_GUID)]
|
||||
_hid.HidD_GetHidGuid.restype = None
|
||||
_hid.HidD_GetPreparsedData.argtypes = [wt.HANDLE, ctypes.POINTER(ctypes.c_void_p)]
|
||||
_hid.HidD_GetPreparsedData.restype = wt.BOOLEAN
|
||||
_hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p]
|
||||
_hid.HidD_FreePreparsedData.restype = wt.BOOLEAN
|
||||
_hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_HIDP_CAPS)]
|
||||
_hid.HidP_GetCaps.restype = ctypes.c_long
|
||||
_hid.HidD_FlushQueue.argtypes = [wt.HANDLE]
|
||||
_hid.HidD_FlushQueue.restype = wt.BOOLEAN
|
||||
|
||||
_setupapi.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), wt.LPCWSTR, wt.HWND, wt.DWORD]
|
||||
_setupapi.SetupDiGetClassDevsW.restype = wt.HANDLE
|
||||
_setupapi.SetupDiEnumDeviceInterfaces.argtypes = [
|
||||
wt.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), wt.DWORD,
|
||||
ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA),
|
||||
]
|
||||
_setupapi.SetupDiEnumDeviceInterfaces.restype = wt.BOOL
|
||||
_setupapi.SetupDiGetDeviceInterfaceDetailW.argtypes = [
|
||||
wt.HANDLE, ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), ctypes.c_void_p, wt.DWORD,
|
||||
ctypes.POINTER(wt.DWORD), ctypes.c_void_p,
|
||||
]
|
||||
_setupapi.SetupDiGetDeviceInterfaceDetailW.restype = wt.BOOL
|
||||
_setupapi.SetupDiDestroyDeviceInfoList.argtypes = [wt.HANDLE]
|
||||
_setupapi.SetupDiDestroyDeviceInfoList.restype = wt.BOOL
|
||||
|
||||
_k32.CreateFileW.argtypes = [
|
||||
wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE,
|
||||
]
|
||||
_k32.CreateFileW.restype = wt.HANDLE
|
||||
_k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR]
|
||||
_k32.CreateEventW.restype = wt.HANDLE
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
_k32.CloseHandle.restype = wt.BOOL
|
||||
_k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)]
|
||||
_k32.WriteFile.restype = wt.BOOL
|
||||
_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)]
|
||||
_k32.ReadFile.restype = wt.BOOL
|
||||
_k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED), ctypes.POINTER(wt.DWORD), wt.BOOL]
|
||||
_k32.GetOverlappedResult.restype = wt.BOOL
|
||||
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||
_k32.WaitForSingleObject.restype = wt.DWORD
|
||||
_k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED)]
|
||||
_k32.CancelIoEx.restype = wt.BOOL
|
||||
_k32.ResetEvent.argtypes = [wt.HANDLE]
|
||||
_k32.ResetEvent.restype = wt.BOOL
|
||||
|
||||
|
||||
def _winerr(what: str) -> HidError:
|
||||
code = ctypes.get_last_error()
|
||||
return HidError(f"{what} failed: [{code}] {ctypes.FormatError(code).strip()}")
|
||||
|
||||
|
||||
def hid_device_paths(vendor_id: int, product_id: int) -> list[str]:
|
||||
"""Device paths of every present HID interface with this USB vendor/product ID."""
|
||||
guid = _GUID()
|
||||
_hid.HidD_GetHidGuid(ctypes.byref(guid))
|
||||
hdev = _setupapi.SetupDiGetClassDevsW(
|
||||
ctypes.byref(guid), None, None, _DIGCF_PRESENT | _DIGCF_DEVICEINTERFACE
|
||||
)
|
||||
if hdev == _INVALID_HANDLE:
|
||||
raise _winerr("SetupDiGetClassDevs")
|
||||
found: list[str] = []
|
||||
needle = f"vid_{vendor_id:04x}&pid_{product_id:04x}"
|
||||
try:
|
||||
index = 0
|
||||
while True:
|
||||
ifdata = _SP_DEVICE_INTERFACE_DATA()
|
||||
ifdata.cbSize = ctypes.sizeof(ifdata)
|
||||
if not _setupapi.SetupDiEnumDeviceInterfaces(hdev, None, ctypes.byref(guid), index, ctypes.byref(ifdata)):
|
||||
if ctypes.get_last_error() == _ERROR_NO_MORE_ITEMS:
|
||||
break
|
||||
raise _winerr("SetupDiEnumDeviceInterfaces")
|
||||
index += 1
|
||||
required = wt.DWORD(0)
|
||||
_setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), None, 0, ctypes.byref(required), None)
|
||||
buf = ctypes.create_string_buffer(required.value + 2)
|
||||
# SP_DEVICE_INTERFACE_DETAIL_DATA_W.cbSize: 8 on 64-bit, 6 on 32-bit
|
||||
ctypes.c_uint32.from_buffer(buf).value = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
|
||||
if not _setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), buf, required, None, None):
|
||||
continue
|
||||
path = ctypes.wstring_at(ctypes.addressof(buf) + 4)
|
||||
if needle in path.lower():
|
||||
found.append(path)
|
||||
finally:
|
||||
_setupapi.SetupDiDestroyDeviceInfoList(hdev)
|
||||
return found
|
||||
|
||||
|
||||
class HidChannel:
|
||||
"""One HID interface opened for overlapped I/O."""
|
||||
|
||||
def __init__(self, path: str, payload_size: int):
|
||||
self.path = path
|
||||
self.handle = _k32.CreateFileW(
|
||||
path, _GENERIC_READ | _GENERIC_WRITE, _FILE_SHARE_READ | _FILE_SHARE_WRITE,
|
||||
None, _OPEN_EXISTING, _FILE_FLAG_OVERLAPPED, None,
|
||||
)
|
||||
if self.handle == _INVALID_HANDLE:
|
||||
raise _winerr(f"Opening {path}")
|
||||
try:
|
||||
caps = _HIDP_CAPS()
|
||||
pp = ctypes.c_void_p()
|
||||
if not _hid.HidD_GetPreparsedData(self.handle, ctypes.byref(pp)):
|
||||
raise _winerr("HidD_GetPreparsedData")
|
||||
try:
|
||||
_hid.HidP_GetCaps(pp, ctypes.byref(caps))
|
||||
finally:
|
||||
_hid.HidD_FreePreparsedData(pp)
|
||||
self.output_len = caps.OutputReportByteLength
|
||||
self.input_len = caps.InputReportByteLength
|
||||
if self.output_len != payload_size + 1:
|
||||
raise HidError(
|
||||
f"Unexpected output report length {self.output_len} on {path} "
|
||||
f"(expected {payload_size + 1}); is this the right device?"
|
||||
)
|
||||
self._wevent = _k32.CreateEventW(None, True, False, None)
|
||||
self._revent = _k32.CreateEventW(None, True, False, None)
|
||||
except Exception:
|
||||
_k32.CloseHandle(self.handle)
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
for h in (getattr(self, "_wevent", None), getattr(self, "_revent", None), self.handle):
|
||||
if h:
|
||||
_k32.CloseHandle(h)
|
||||
self.handle = None
|
||||
|
||||
def send(self, payload: bytes, timeout_ms: int = 1000) -> None:
|
||||
data = bytes(1) + payload
|
||||
if len(data) < self.output_len:
|
||||
data += bytes(self.output_len - len(data))
|
||||
buf = ctypes.create_string_buffer(data, self.output_len)
|
||||
ov = _OVERLAPPED()
|
||||
ov.hEvent = self._wevent
|
||||
_k32.ResetEvent(self._wevent)
|
||||
written = wt.DWORD(0)
|
||||
if not _k32.WriteFile(self.handle, buf, self.output_len, None, ctypes.byref(ov)):
|
||||
if ctypes.get_last_error() != _ERROR_IO_PENDING:
|
||||
raise _winerr("WriteFile")
|
||||
if _k32.WaitForSingleObject(self._wevent, timeout_ms) != _WAIT_OBJECT_0:
|
||||
_k32.CancelIoEx(self.handle, ctypes.byref(ov))
|
||||
_k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True)
|
||||
raise HidError(f"HID write timed out on {self.path}")
|
||||
if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True):
|
||||
raise _winerr("WriteFile (completion)")
|
||||
|
||||
def read(self, timeout_ms: int) -> bytes | None:
|
||||
"""Read one input report, or None on timeout."""
|
||||
buf = ctypes.create_string_buffer(self.input_len)
|
||||
ov = _OVERLAPPED()
|
||||
ov.hEvent = self._revent
|
||||
_k32.ResetEvent(self._revent)
|
||||
got = wt.DWORD(0)
|
||||
if not _k32.ReadFile(self.handle, buf, self.input_len, None, ctypes.byref(ov)):
|
||||
if ctypes.get_last_error() != _ERROR_IO_PENDING:
|
||||
raise _winerr("ReadFile")
|
||||
if _k32.WaitForSingleObject(self._revent, timeout_ms) == _WAIT_TIMEOUT:
|
||||
_k32.CancelIoEx(self.handle, ctypes.byref(ov))
|
||||
ok = _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True)
|
||||
return buf.raw[: got.value] if ok and got.value else None
|
||||
if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True):
|
||||
raise _winerr("ReadFile (completion)")
|
||||
return buf.raw[: got.value]
|
||||
|
||||
def drain(self) -> None:
|
||||
_hid.HidD_FlushQueue(self.handle)
|
||||
@@ -0,0 +1,502 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
#include <pawnio.inc>
|
||||
|
||||
const SleepMode: {
|
||||
SleepMode_AlwaysBusy = 0,
|
||||
SleepMode_ShortBusy = 1,
|
||||
SleepMode_AlwaysSleep = 2,
|
||||
|
||||
SleepMode_Max,
|
||||
};
|
||||
|
||||
static SleepMode:g_sleep_mode = SleepMode_AlwaysBusy;
|
||||
|
||||
/// Set sleep mode.
|
||||
/// @param mode Sleep mode to set
|
||||
stock Void:set_sleep_mode(SleepMode:mode) {
|
||||
g_sleep_mode = mode;
|
||||
}
|
||||
|
||||
/// Short sleep for a given number of microseconds.
|
||||
/// @param us Microseconds to sleep
|
||||
stock Void:microsleep_short(us) {
|
||||
switch (g_sleep_mode) {
|
||||
case SleepMode_AlwaysBusy, SleepMode_ShortBusy:
|
||||
microsleep2(us);
|
||||
case SleepMode_AlwaysSleep:
|
||||
microsleep(us);
|
||||
}
|
||||
}
|
||||
|
||||
/// Long sleep for a given number of microseconds.
|
||||
/// @param us Microseconds to sleep
|
||||
stock Void:microsleep_long(us) {
|
||||
switch (g_sleep_mode) {
|
||||
case SleepMode_AlwaysBusy:
|
||||
microsleep2(us);
|
||||
case SleepMode_ShortBusy, SleepMode_AlwaysSleep:
|
||||
microsleep(us);
|
||||
}
|
||||
}
|
||||
|
||||
#if !defined(NO_SLEEPMODE_IOCTL)
|
||||
|
||||
DEFINE_IOCTL_SIZED(ioctl_set_sleep_mode, 1, 0) {
|
||||
new SleepMode:mode = SleepMode:in[0];
|
||||
if (mode < SleepMode_AlwaysBusy || mode >= SleepMode_Max) {
|
||||
return STATUS_INVALID_PARAMETER;
|
||||
}
|
||||
set_sleep_mode(mode);
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1 @@
|
||||
"""Lighting: Lighting Node CORE fan LEDs, Dominator DDR5 RAM and ASUS GPU LEDs."""
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Opt-in temperature lighting and calibrated QL120 side chase on the Lighting Node CORE.
|
||||
|
||||
Header 1 of the CORE holds the six QL120 case fans (34 LEDs each, 204 in total); header 2 is
|
||||
left alone. The node is driven directly over HID (see lighting_node.py), so no OpenRGB is needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.lighting_node import MAX_LEDS, LightingNodeBusy, LightingNodeCore
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_RETRY_SECONDS = 10.0
|
||||
_FAN_TOP_RIGHT = (17, 17, 17, 20, 11, 20)
|
||||
_CHASE_EASE_SECONDS = 1.0
|
||||
# The CORE shares a USB 2.0 hub with the LCD; flooding it hung the LCD firmware, so cap
|
||||
# frames at ~22/s and let a fast chase advance more than one LED per frame instead.
|
||||
MIN_CHASE_FRAME_SECONDS = 0.045
|
||||
CHASE_POLL_SECONDS = 0.02
|
||||
|
||||
|
||||
def _side_chase_route(cpu_side: bool) -> tuple[int, ...]:
|
||||
fans = (4, 5, 3) if cpu_side else (0, 1, 2) # bottom, middle, top; zero-based chain
|
||||
# Clock positions 0 and 11 flank 12; 5 and 6 flank 6.
|
||||
segments = (
|
||||
(0, range(12)),
|
||||
(1, range(5, -1, -1)),
|
||||
(2, range(6, 18)),
|
||||
(1, range(11, 5, -1)),
|
||||
)
|
||||
route = []
|
||||
for position, clock_positions in segments:
|
||||
for clock in clock_positions:
|
||||
if not cpu_side:
|
||||
clock = 11 - clock
|
||||
led = 10 + (_FAN_TOP_RIGHT[fans[position]] - 10 + clock) % 12
|
||||
route.append(fans[position] * 34 + led)
|
||||
return tuple(route)
|
||||
|
||||
|
||||
_SIDE_CHASE_ROUTES = (_side_chase_route(True), _side_chase_route(False))
|
||||
SIDE_CHASE_CYCLE_STEPS = len(_SIDE_CHASE_ROUTES[0])
|
||||
# Bottom fan at 6 o'clock; the top fan reaches 12 o'clock half a cycle later.
|
||||
SIDE_CHASE_BOTTOM_STEP = 6
|
||||
_LEDS_PER_SIDE = 3 * 34 # chain fans 0-2 are the GPU side, 3-5 the CPU side
|
||||
|
||||
|
||||
def side_chase_color(strength: float) -> tuple[int, int, int]:
|
||||
"""Blend the dark-red ring base into the warm-orange chase head (strength 0-1)."""
|
||||
return (round(24 + 231 * strength), round(48 * strength), 0)
|
||||
|
||||
|
||||
def side_chase_frame(step: int) -> list[tuple[int, int, int]]:
|
||||
"""Render mirrored sides, with each inner ring reflected left-to-right."""
|
||||
colors = [(48, 0, 0) if index % 34 < 10 else (24, 0, 0) for index in range(204)]
|
||||
for route in _SIDE_CHASE_ROUTES:
|
||||
for age in range(5):
|
||||
strength = (5 - age) / 5
|
||||
color = side_chase_color(strength)
|
||||
outer = route[(step - age) % len(route)]
|
||||
fan, local = divmod(outer, 34)
|
||||
right_of_top = _FAN_TOP_RIGHT[fan]
|
||||
clock = (local - right_of_top) % 12
|
||||
inner = fan * 34 + 22 + (right_of_top - 10 + 11 - clock) % 12
|
||||
colors[outer] = colors[inner] = color
|
||||
return colors
|
||||
|
||||
|
||||
class ChaseTiming:
|
||||
"""Elapsed-time chase phase with power-dependent speed and gradual acceleration."""
|
||||
|
||||
def __init__(self, step_seconds: float = 0.15, fast_step_seconds: float = 0.025,
|
||||
watts: tuple[float, float] = (150.0, 550.0)):
|
||||
for step in (step_seconds, fast_step_seconds):
|
||||
if not math.isfinite(step) or step < 0.02:
|
||||
raise ValueError("Chase step must be finite and at least 0.02 seconds")
|
||||
if fast_step_seconds > step_seconds:
|
||||
raise ValueError("Fast chase step can't be slower than the idle step")
|
||||
if not all(math.isfinite(w) for w in watts) or watts[1] <= watts[0]:
|
||||
raise ValueError("Chase power range must be finite and increasing")
|
||||
self.step_seconds = step_seconds
|
||||
self.fast_step_seconds = fast_step_seconds
|
||||
self.watts = watts
|
||||
self._lock = threading.Lock()
|
||||
self._power: float | None = None
|
||||
self.reset()
|
||||
|
||||
def reset(self, phase: float = 0.0) -> None:
|
||||
with self._lock:
|
||||
self.last_time: float | None = None
|
||||
self.phase = phase
|
||||
self.rate = 0.0
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
with self._lock:
|
||||
self._power = total_watts
|
||||
|
||||
def rate_for(self, total_watts: float | None) -> float:
|
||||
slow, fast = 1 / self.step_seconds, 1 / self.fast_step_seconds
|
||||
if total_watts is None or not math.isfinite(total_watts):
|
||||
return slow
|
||||
lo, hi = self.watts
|
||||
t = min(1.0, max(0.0, (total_watts - lo) / (hi - lo)))
|
||||
return slow + t * (fast - slow)
|
||||
|
||||
def sample(self, now: float) -> tuple[float, float]:
|
||||
with self._lock:
|
||||
target = self.rate_for(self._power)
|
||||
if self.last_time is None:
|
||||
self.last_time, self.rate = now, target
|
||||
dt = max(0.0, now - self.last_time)
|
||||
self.last_time = max(now, self.last_time)
|
||||
self.rate += (target - self.rate) * min(1.0, dt / _CHASE_EASE_SECONDS)
|
||||
self.phase += self.rate * dt
|
||||
return self.phase, self.rate
|
||||
|
||||
def step(self, now: float) -> int:
|
||||
return int(self.sample(now)[0])
|
||||
|
||||
|
||||
class RGBLighting:
|
||||
"""Run a selected pattern on the Lighting Node CORE; hand it back to its hardware effect when off."""
|
||||
|
||||
def __init__(self, theme: Theme, chase_step_seconds: float = 0.15, chase_fast_step_seconds: float = 0.025,
|
||||
chase_watts: tuple[float, float] = (150.0, 550.0),
|
||||
node_factory: Callable[[], LightingNodeCore] = LightingNodeCore, *,
|
||||
chase_timing: ChaseTiming | None = None):
|
||||
"""The side chase runs at `chase_step_seconds` per LED at or below the first
|
||||
`chase_watts` total system power, speeding up to `chase_fast_step_seconds` at the second."""
|
||||
self._owns_chase_timing = chase_timing is None
|
||||
self._chase_timing = (chase_timing if chase_timing is not None
|
||||
else ChaseTiming(chase_step_seconds, chase_fast_step_seconds, chase_watts))
|
||||
self.theme = theme
|
||||
self.chase_step_seconds = chase_step_seconds
|
||||
self.chase_fast_step_seconds = chase_fast_step_seconds
|
||||
self.chase_watts = chase_watts
|
||||
self.node: LightingNodeCore | None = None
|
||||
self.status = "off"
|
||||
self._node_factory = node_factory
|
||||
self._retry_at = 0.0
|
||||
self._last_error: str | None = None
|
||||
self._pattern: str | None = None
|
||||
self._last_chase_step: int | None = None
|
||||
self._last_frame_time = -math.inf
|
||||
self._cpu_temp: float | None = None
|
||||
self._gpu_temp: float | None = None
|
||||
self._power: float | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
with self._lock:
|
||||
self._cpu_temp = cpu_temp
|
||||
self._gpu_temp = gpu_temp
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
with self._lock:
|
||||
self._power = total_watts
|
||||
self._chase_timing.set_power(total_watts)
|
||||
|
||||
def chase_rate(self, total_watts: float | None) -> float:
|
||||
"""LEDs per second for a given total system power (idle pace when unknown)."""
|
||||
return self._chase_timing.rate_for(total_watts)
|
||||
|
||||
def run(self, stop: threading.Event, temperature_enabled: threading.Event,
|
||||
side_chase_enabled: threading.Event) -> None:
|
||||
"""Own all Lighting Node access on one worker, independent of LCD and sensor timing."""
|
||||
try:
|
||||
while not stop.is_set():
|
||||
with self._lock:
|
||||
cpu_temp, gpu_temp = self._cpu_temp, self._gpu_temp
|
||||
self.update(cpu_temp, temperature_enabled.is_set(), side_chase=side_chase_enabled.is_set(),
|
||||
gpu_temp=gpu_temp)
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def update(self, cpu_temp: float | None, enabled: bool, *, side_chase: bool = False,
|
||||
gpu_temp: float | None = None) -> None:
|
||||
pattern = "side-chase" if side_chase else "temperature" if enabled else None
|
||||
if pattern != self._pattern:
|
||||
self._pattern = pattern
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset()
|
||||
self._last_chase_step = None
|
||||
if pattern is None:
|
||||
self.close()
|
||||
if pattern is None:
|
||||
return
|
||||
if self.node is None:
|
||||
if time.monotonic() < self._retry_at:
|
||||
return
|
||||
try:
|
||||
node = self._node_factory()
|
||||
node.open()
|
||||
except LightingNodeBusy as e:
|
||||
self._fail(e, str(e))
|
||||
return
|
||||
except Exception as e:
|
||||
self._fail(e, "Lighting Node CORE unavailable")
|
||||
return
|
||||
self.node = node
|
||||
self._last_error = None
|
||||
log.info("Lighting Node CORE opened (firmware %s)", node.firmware)
|
||||
try:
|
||||
if pattern == "side-chase":
|
||||
self._apply_side_chase()
|
||||
else:
|
||||
self._apply_temperature(cpu_temp, gpu_temp)
|
||||
self.node.keepalive()
|
||||
except Exception as e:
|
||||
self._fail(e, "Lighting Node CORE connection lost")
|
||||
|
||||
def close(self) -> None:
|
||||
"""Hand the fans back to the node's own effect."""
|
||||
node, self.node = self.node, None
|
||||
self._last_chase_step = None
|
||||
if node is not None:
|
||||
try:
|
||||
node.close()
|
||||
except Exception:
|
||||
log.exception("Couldn't release the Lighting Node CORE")
|
||||
self._set_status("off")
|
||||
|
||||
def _apply_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
"""Colour each side's three fans by its own part's temperature, like the LCD gauges."""
|
||||
assert self.node is not None
|
||||
if cpu_temp is None and gpu_temp is None:
|
||||
self._set_status("Temperature lighting waiting for temperatures")
|
||||
return
|
||||
# A side whose sensor is unavailable borrows the other side's reading.
|
||||
cpu = cpu_temp if cpu_temp is not None else gpu_temp
|
||||
gpu = gpu_temp if gpu_temp is not None else cpu_temp
|
||||
th = self.theme
|
||||
gpu_color = th.level_color(gpu, th.temp_warn, th.temp_hot)
|
||||
cpu_color = th.level_color(cpu, th.temp_warn, th.temp_hot)
|
||||
self.node.show(0, [gpu_color] * _LEDS_PER_SIDE + [cpu_color] * (MAX_LEDS - _LEDS_PER_SIDE))
|
||||
self._set_status(f"Temperature lighting active (GPU {gpu:.0f} \u00b0C, CPU {cpu:.0f} \u00b0C)")
|
||||
|
||||
def _apply_side_chase(self) -> None:
|
||||
assert self.node is not None
|
||||
with self._lock:
|
||||
power = self._power
|
||||
now = time.monotonic()
|
||||
step = self._chase_timing.step(now)
|
||||
if step != self._last_chase_step and now - self._last_frame_time >= MIN_CHASE_FRAME_SECONDS:
|
||||
self.node.show(0, side_chase_frame(step))
|
||||
self._last_chase_step = step
|
||||
self._last_frame_time = now
|
||||
watts = "" if power is None else f" at {power:.0f} W"
|
||||
self._set_status(f"Red side chase active ({1000 / self._chase_timing.rate:.0f} ms/LED{watts})")
|
||||
|
||||
def _fail(self, error: Exception, status: str) -> None:
|
||||
node, self.node = self.node, None
|
||||
if node is not None:
|
||||
try:
|
||||
node.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._last_chase_step = None
|
||||
self._retry_at = time.monotonic() + _RETRY_SECONDS
|
||||
self._set_status(status)
|
||||
message = str(error) or type(error).__name__
|
||||
if message != self._last_error:
|
||||
log.warning("RGB lighting unavailable: %s", message, exc_info=not isinstance(error, LightingNodeBusy))
|
||||
self._last_error = message
|
||||
|
||||
def _set_status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
self.status = status
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Direct ASUS RTX 4090 lighting through NVIDIA's I2C API (no USB traffic)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable, Protocol
|
||||
|
||||
from kurgan.lighting.case_fans import (
|
||||
CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming,
|
||||
SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color,
|
||||
)
|
||||
from kurgan.telemetry.sensors import _process_names, corsair_software_running
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
Rgb = tuple[int, int, int]
|
||||
_U8, _U32 = ctypes.c_uint8, ctypes.c_uint32
|
||||
_GPU_DEVICE = 0x268410DE
|
||||
_GPU_SUBSYSTEM = 0x89321043
|
||||
_CONTROLLER_ADDRESS = 0x67
|
||||
_FIRMWARE = ("AUMA0-E6K5-0107", "AUMA0-E6K5-1110", "AUMA0-E6K5-1111")
|
||||
|
||||
|
||||
class _I2cInfo(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("version", _U32), ("display_mask", _U32),
|
||||
("ddc", _U8), ("address", _U8),
|
||||
("register", ctypes.POINTER(_U8)), ("register_size", _U32),
|
||||
("data", ctypes.POINTER(_U8)), ("size", _U32),
|
||||
("speed", _U32), ("speed_khz", _U32),
|
||||
("port", _U8), ("port_set", _U32),
|
||||
]
|
||||
|
||||
|
||||
class NvidiaI2c:
|
||||
def __init__(self) -> None:
|
||||
name = "nvapi64.dll" if ctypes.sizeof(ctypes.c_void_p) == 8 else "nvapi.dll"
|
||||
self._dll = ctypes.CDLL(os.path.join(os.environ["SystemRoot"], "System32", name))
|
||||
self._query = self._dll.nvapi_QueryInterface
|
||||
self._query.argtypes = [_U32]
|
||||
self._query.restype = ctypes.c_void_p
|
||||
self._check(self._function(0x0150E828)(), "Initialize")
|
||||
enum = self._function(0xE5AC921F, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_int32))
|
||||
identity = self._function(0x2DDFB66E, ctypes.c_void_p, *([ctypes.POINTER(_U32)] * 4))
|
||||
handles = (ctypes.c_void_p * 64)()
|
||||
count = ctypes.c_int32()
|
||||
self._check(enum(handles, ctypes.byref(count)), "EnumPhysicalGPUs")
|
||||
matches = []
|
||||
for handle in handles[:count.value]:
|
||||
device, subsystem, revision, extended = (_U32() for _ in range(4))
|
||||
self._check(identity(handle, ctypes.byref(device), ctypes.byref(subsystem),
|
||||
ctypes.byref(revision), ctypes.byref(extended)), "GetPCIIdentifiers")
|
||||
if device.value == _GPU_DEVICE and subsystem.value == _GPU_SUBSYSTEM:
|
||||
matches.append(handle)
|
||||
if len(matches) != 1:
|
||||
raise OSError(f"Expected one ASUS RTX 4090 (2684:8932), found {len(matches)}")
|
||||
self._handle = matches[0]
|
||||
arguments = (ctypes.c_void_p, ctypes.POINTER(_I2cInfo), ctypes.POINTER(_U32))
|
||||
self._read = self._function(0x4D7B0709, *arguments)
|
||||
self._write = self._function(0x283AC65A, *arguments)
|
||||
|
||||
def _function(self, identifier: int, *arguments):
|
||||
address = self._query(identifier)
|
||||
if not address:
|
||||
raise OSError(f"NVIDIA API function 0x{identifier:08X} unavailable")
|
||||
return ctypes.CFUNCTYPE(ctypes.c_int32, *arguments)(address)
|
||||
|
||||
@staticmethod
|
||||
def _check(status: int, operation: str) -> None:
|
||||
if status != 0:
|
||||
raise OSError(f"NVIDIA {operation} failed (status {status})")
|
||||
|
||||
def transfer(self, command: int, data: bytes, *, read: bool = False) -> bytes:
|
||||
register = (_U8 * 1)(command)
|
||||
buffer = (_U8 * len(data)).from_buffer_copy(data)
|
||||
info = _I2cInfo()
|
||||
info.version = ctypes.sizeof(_I2cInfo) | (3 << 16)
|
||||
info.address = _CONTROLLER_ADDRESS << 1
|
||||
info.register, info.register_size = register, 1
|
||||
info.data, info.size = buffer, len(data)
|
||||
info.speed = 0xFFFF
|
||||
info.port, info.port_set = 1, 1
|
||||
unknown = _U32()
|
||||
operation = self._read if read else self._write
|
||||
self._check(operation(self._handle, ctypes.byref(info), ctypes.byref(unknown)), "I2C transfer")
|
||||
if info.size != len(data):
|
||||
raise OSError(f"NVIDIA I2C transferred {info.size} bytes; expected {len(data)}")
|
||||
return bytes(buffer)
|
||||
|
||||
|
||||
class AsusGpuLeds:
|
||||
def __init__(self, bus_factory: Callable[[], NvidiaI2c] = NvidiaI2c) -> None:
|
||||
self._factory = bus_factory
|
||||
self._bus: NvidiaI2c | None = None
|
||||
self.led_count = 0
|
||||
self._original_direct = 0
|
||||
self._original_colors: tuple[Rgb, ...] = ()
|
||||
self._shown: tuple[Rgb, ...] | None = None
|
||||
self._claimed = False
|
||||
|
||||
def _select(self, register: int) -> None:
|
||||
assert self._bus is not None
|
||||
self._bus.transfer(0, register.to_bytes(2, "big"))
|
||||
|
||||
def _read_register(self, register: int) -> int:
|
||||
self._select(register)
|
||||
assert self._bus is not None
|
||||
return self._bus.transfer(0x81, bytes(1), read=True)[0]
|
||||
|
||||
def _write_register(self, register: int, value: int) -> None:
|
||||
self._select(register)
|
||||
assert self._bus is not None
|
||||
self._bus.transfer(1, bytes((value,)))
|
||||
|
||||
def open(self) -> None:
|
||||
if any("lightingservice" in name or "armoury" in name or "aura" in name
|
||||
for name in _process_names()):
|
||||
raise OSError("GPU lighting busy: exit ASUS lighting software")
|
||||
if corsair_software_running("ASUS ROG STRIX GeForce RTX 4090 Gaming OC", fan_tools=False):
|
||||
raise OSError("GPU lighting busy: exit other RGB software")
|
||||
self._bus = self._factory()
|
||||
version = bytes(self._read_register(0x1000 + i) for i in range(16)).split(b"\0", 1)[0]
|
||||
if version.decode("ascii", errors="replace") not in _FIRMWARE:
|
||||
raise OSError(f"Unsupported GPU LED firmware: {version!r}")
|
||||
self.led_count = self._read_register(0x1C03)
|
||||
if not 1 <= self.led_count <= 32:
|
||||
raise OSError(f"Unexpected GPU LED count: {self.led_count}")
|
||||
self._original_direct = self._read_register(0x8020)
|
||||
if self._original_direct not in (0, 1):
|
||||
raise OSError(f"Unexpected GPU direct-mode state: {self._original_direct}")
|
||||
raw = [self._read_register(0x8100 + i) for i in range(self.led_count * 3)]
|
||||
self._original_colors = tuple((raw[i], raw[i + 2], raw[i + 1])
|
||||
for i in range(0, len(raw), 3))
|
||||
log.info("GPU lighting identified: %s, %d LEDs", version.decode("ascii"), self.led_count)
|
||||
|
||||
def _write_colors(self, colors: tuple[Rgb, ...], previous: tuple[Rgb, ...] | None) -> None:
|
||||
assert self._bus is not None
|
||||
for led, (red, green, blue) in enumerate(colors):
|
||||
if previous is not None and colors[led] == previous[led]:
|
||||
continue
|
||||
self._select(0x8100 + led * 3)
|
||||
self._bus.transfer(3, bytes((3, red, blue, green)))
|
||||
|
||||
def show_frame(self, colors: tuple[Rgb, ...]) -> None:
|
||||
if len(colors) != self.led_count or any(
|
||||
len(color) != 3 or any(type(value) is not int or not 0 <= value <= 255 for value in color)
|
||||
for color in colors):
|
||||
raise ValueError("GPU frame must contain one valid RGB triplet per LED")
|
||||
self._claimed = True
|
||||
self._write_colors(colors, self._shown)
|
||||
if self._shown is None:
|
||||
self._write_register(0x8020, 1)
|
||||
self._write_register(0x80A0, 1)
|
||||
self._shown = colors
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
if self._claimed:
|
||||
try:
|
||||
self._write_colors(self._original_colors, None)
|
||||
finally:
|
||||
self._write_register(0x8020, self._original_direct)
|
||||
self._write_register(0x80A0, 1)
|
||||
finally:
|
||||
self._bus = None
|
||||
self._shown = None
|
||||
self._claimed = False
|
||||
|
||||
|
||||
def gpu_chase_frame(phase: float, led_count: int) -> tuple[Rgb, ...]:
|
||||
if led_count < 1:
|
||||
raise ValueError("GPU must have at least one LED")
|
||||
if led_count == 1:
|
||||
return (side_chase_color(1),)
|
||||
route = tuple(range(led_count - 1, -1, -1)) + tuple(range(1, led_count - 1))
|
||||
step = math.floor((phase - SIDE_CHASE_BOTTOM_STEP) * len(route) / SIDE_CHASE_CYCLE_STEPS)
|
||||
colors = [side_chase_color(0)] * led_count
|
||||
for age in range(min(4, led_count - 1), -1, -1):
|
||||
colors[route[(step - age) % len(route)]] = side_chase_color((5 - age) / 5)
|
||||
return tuple(colors)
|
||||
|
||||
|
||||
class _GpuDriver(Protocol):
|
||||
led_count: int
|
||||
def open(self) -> None: ...
|
||||
def show_frame(self, colors: tuple[Rgb, ...]) -> None: ...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
class GpuLighting:
|
||||
def __init__(self, chase_timing: ChaseTiming,
|
||||
driver_factory: Callable[[], _GpuDriver] = AsusGpuLeds) -> None:
|
||||
self.status = "off"
|
||||
self._clock = chase_timing
|
||||
self._factory = driver_factory
|
||||
self._driver: _GpuDriver | None = None
|
||||
self._retry_at = 0.0
|
||||
self._last_frame_at = -math.inf
|
||||
self._last_frame: tuple[Rgb, ...] | None = None
|
||||
|
||||
def _status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
log.info("GPU lighting: %s", status)
|
||||
self.status = status
|
||||
|
||||
def close(self) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
self._last_frame = None
|
||||
self._last_frame_at = -math.inf
|
||||
if driver is not None:
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't restore GPU lighting state")
|
||||
|
||||
def update(self, enabled: bool) -> None:
|
||||
if not enabled:
|
||||
self.close()
|
||||
self._status("off")
|
||||
return
|
||||
now = time.monotonic()
|
||||
if self._driver is None and now < self._retry_at:
|
||||
return
|
||||
try:
|
||||
if self._driver is None:
|
||||
self._driver = self._factory()
|
||||
self._driver.open()
|
||||
phase, _ = self._clock.sample(now)
|
||||
frame = gpu_chase_frame(phase, self._driver.led_count)
|
||||
if frame != self._last_frame and now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS:
|
||||
self._driver.show_frame(frame)
|
||||
self._last_frame, self._last_frame_at = frame, now
|
||||
self._status(f"Red chase active ({self._driver.led_count} LEDs)")
|
||||
except OSError as error:
|
||||
log.warning("GPU lighting unavailable: %s", error)
|
||||
self.close()
|
||||
self._retry_at = now + 10
|
||||
self._status(f"unavailable: {error}")
|
||||
|
||||
def run(self, stop: threading.Event, enabled: threading.Event) -> None:
|
||||
try:
|
||||
while not stop.is_set():
|
||||
self.update(enabled.is_set())
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
except Exception:
|
||||
log.exception("GPU lighting worker failed")
|
||||
self._status("worker stopped; check dashboard.log")
|
||||
finally:
|
||||
self.close()
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Corsair Lighting Node CORE (1B1C:0C1A) driven directly over Windows HID.
|
||||
|
||||
Each command is a 64-byte output report answered by a 16-byte input report whose first
|
||||
byte is 0 on success. LED colours go 50 at a time, one packet per colour channel, and only
|
||||
appear after a commit. The node returns to its stored hardware effect if it hears nothing
|
||||
for about 20 s in software mode, so `keepalive()` re-commits every few seconds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import time
|
||||
|
||||
from kurgan.telemetry.sensors import corsair_software_running
|
||||
from kurgan.hardware.hid import HidChannel, hid_device_paths
|
||||
|
||||
VID, PID = 0x1B1C, 0x0C1A
|
||||
OP_FIRMWARE, OP_DIRECT, OP_COMMIT, OP_PORT_STATE = 0x02, 0x32, 0x33, 0x38
|
||||
PORT_HARDWARE, PORT_SOFTWARE = 0x01, 0x02
|
||||
LEDS_PER_PACKET = 50
|
||||
MAX_LEDS = 204
|
||||
KEEPALIVE_SECONDS = 5.0
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_k32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
|
||||
_k32.CreateMutexW.restype = ctypes.c_void_p
|
||||
_k32.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
_ERROR_ALREADY_EXISTS = 183
|
||||
|
||||
|
||||
class LightingNodeBusy(OSError):
|
||||
pass
|
||||
|
||||
|
||||
def direct_packets(channel: int, colors: list[tuple[int, int, int]],
|
||||
previous: list[tuple[int, int, int]] | None = None) -> list[bytes]:
|
||||
"""Direct-colour packets for `colors`, skipping chunks whose colour channel is unchanged."""
|
||||
packets = []
|
||||
for start in range(0, len(colors), LEDS_PER_PACKET):
|
||||
chunk = colors[start:start + LEDS_PER_PACKET]
|
||||
old = None if previous is None else previous[start:start + LEDS_PER_PACKET]
|
||||
for component in range(3):
|
||||
values = bytes(color[component] for color in chunk)
|
||||
if old is not None and values == bytes(color[component] for color in old):
|
||||
continue
|
||||
packets.append(bytes((OP_DIRECT, channel, start, len(chunk), component)) + values)
|
||||
return packets
|
||||
|
||||
|
||||
class LightingNodeCore:
|
||||
"""Open with `with LightingNodeCore() as node:` and call `show()` or `keepalive()` regularly."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ch: HidChannel | None = None
|
||||
self.firmware = ""
|
||||
self._mutex: int | None = None
|
||||
self._software: set[int] = set()
|
||||
self._shown: dict[int, list[tuple[int, int, int]]] = {}
|
||||
self._last_commit = 0.0
|
||||
|
||||
def __enter__(self) -> "LightingNodeCore":
|
||||
self.open()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def open(self) -> None:
|
||||
if self.ch is not None:
|
||||
return
|
||||
if corsair_software_running("Corsair Lighting Node Core", fan_tools=False):
|
||||
raise LightingNodeBusy("Lighting Node CORE busy: exit iCUE, or disable OpenRGB's "
|
||||
"Corsair Lighting Node Core detector")
|
||||
ctypes.set_last_error(0)
|
||||
mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdLightingNode")
|
||||
if not mutex or ctypes.get_last_error() == _ERROR_ALREADY_EXISTS:
|
||||
if mutex:
|
||||
_k32.CloseHandle(mutex)
|
||||
raise LightingNodeBusy("Lighting Node CORE is in use by another dashboard process")
|
||||
self._mutex = mutex
|
||||
try:
|
||||
paths = hid_device_paths(VID, PID)
|
||||
if len(paths) != 1:
|
||||
raise OSError(f"Expected one Lighting Node CORE, found {len(paths)}")
|
||||
self.ch = HidChannel(paths[0], 64)
|
||||
reply = self._cmd(OP_FIRMWARE)
|
||||
self.firmware = ".".join(str(b) for b in reply[2:5])
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
if self.ch is not None:
|
||||
try:
|
||||
self.release()
|
||||
except OSError:
|
||||
pass
|
||||
self.ch.close()
|
||||
self.ch = None
|
||||
if self._mutex is not None:
|
||||
_k32.CloseHandle(self._mutex)
|
||||
self._mutex = None
|
||||
|
||||
def show(self, channel: int, colors: list[tuple[int, int, int]]) -> None:
|
||||
"""Display `colors` on header `channel` (0 or 1), sending only what changed."""
|
||||
if channel not in (0, 1) or not 0 < len(colors) <= MAX_LEDS:
|
||||
raise ValueError("Channel must be 0 or 1 with 1-204 LEDs")
|
||||
if channel not in self._software:
|
||||
self._cmd(OP_PORT_STATE, channel, PORT_SOFTWARE)
|
||||
self._software.add(channel)
|
||||
self._shown.pop(channel, None)
|
||||
previous = self._shown.get(channel)
|
||||
if previous is not None and len(previous) != len(colors):
|
||||
previous = None
|
||||
packets = direct_packets(channel, colors, previous)
|
||||
for packet in packets:
|
||||
self._cmd(*packet)
|
||||
if packets:
|
||||
self._commit()
|
||||
self._shown[channel] = list(colors)
|
||||
|
||||
def keepalive(self) -> None:
|
||||
if self._software and time.monotonic() - self._last_commit >= KEEPALIVE_SECONDS:
|
||||
self._commit()
|
||||
|
||||
def release(self) -> None:
|
||||
"""Hand every header back to the node's stored hardware effect."""
|
||||
for channel in sorted(self._software):
|
||||
self._cmd(OP_PORT_STATE, channel, PORT_HARDWARE)
|
||||
self._software.clear()
|
||||
self._shown.clear()
|
||||
|
||||
def _commit(self) -> None:
|
||||
self._cmd(OP_COMMIT, 0xFF)
|
||||
self._last_commit = time.monotonic()
|
||||
|
||||
def _cmd(self, *payload: int) -> bytes:
|
||||
ch = self.ch
|
||||
if ch is None:
|
||||
raise OSError("Lighting Node CORE is not open")
|
||||
ch.drain()
|
||||
ch.send(bytes(payload))
|
||||
reply = ch.read(300)
|
||||
if not reply or len(reply) < 2 or reply[1] != 0: # [report id, status, ...]
|
||||
raise OSError(f"Lighting Node CORE didn't accept command 0x{payload[0]:02X}")
|
||||
return reply
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Direct, temporary RGB control for Corsair Dominator Platinum DDR5 memory."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from typing import Callable, Generator, Protocol, Sequence
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.case_fans import (
|
||||
CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming,
|
||||
SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color,
|
||||
)
|
||||
from kurgan.telemetry.sensors import corsair_software_running
|
||||
|
||||
from kurgan.hardware import PAWNIO_DIR
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_PAWNIO_DLL = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "PawnIO", "PawnIOLib.dll")
|
||||
_SMBUS_MODULE = os.path.join(PAWNIO_DIR, "SmbusI801.bin")
|
||||
_ADDRESSES = (0x18, 0x19, 0x1A, 0x1B)
|
||||
_LED_COUNT = 12
|
||||
_KEEPALIVE_SECONDS = 5.0
|
||||
_RETRY_SECONDS = 10.0
|
||||
_BLACK = (0, 0, 0)
|
||||
_CELL = ctypes.c_uint64
|
||||
_STATUS_ACCESS_DENIED = 0xC0000022
|
||||
_STATUS_NO_SUCH_DEVICE = 0xC000000E
|
||||
_WAIT_OBJECT_0 = 0
|
||||
_WAIT_ABANDONED = 0x80
|
||||
Rgb = tuple[int, int, int]
|
||||
MemoryFrame = tuple[tuple[Rgb, ...], ...]
|
||||
|
||||
# Identification colours confirmed physical sticks 1-4 as addresses 0x18-0x1B.
|
||||
_CHASE_ROUTE = tuple((stick, led)
|
||||
for stick, inward in ((3, True), (2, False), (1, True),
|
||||
(0, False), (1, True), (2, False))
|
||||
for led in (range(6) if inward else range(5, -1, -1)))
|
||||
_CHASE_BOTTOM_STEP = 5
|
||||
|
||||
|
||||
def _solid_frame(color: Rgb) -> MemoryFrame:
|
||||
return ((color,) * _LED_COUNT,) * len(_ADDRESSES)
|
||||
|
||||
|
||||
def memory_chase_frame(step: int) -> MemoryFrame:
|
||||
"""Two mirrored heads travel up and down without repeating either end stick."""
|
||||
colors = [[side_chase_color(0)] * _LED_COUNT for _ in _ADDRESSES]
|
||||
for age in range(4, -1, -1):
|
||||
stick, led = _CHASE_ROUTE[(step - age) % len(_CHASE_ROUTE)]
|
||||
colors[stick][led] = colors[stick][_LED_COUNT - 1 - led] = side_chase_color((5 - age) / 5)
|
||||
return tuple(tuple(stick) for stick in colors)
|
||||
|
||||
|
||||
def memory_chase_step(fan_phase: float) -> int:
|
||||
return math.floor(_CHASE_BOTTOM_STEP
|
||||
+ (fan_phase - SIDE_CHASE_BOTTOM_STEP) * len(_CHASE_ROUTE) / SIDE_CHASE_CYCLE_STEPS)
|
||||
|
||||
|
||||
class MemoryLightingBusy(OSError):
|
||||
"""Raised when another RGB application owns Corsair memory lighting."""
|
||||
|
||||
|
||||
class _MemoryLightingDriver(Protocol):
|
||||
def open(self) -> None: ...
|
||||
|
||||
def show(self, color: tuple[int, int, int]) -> None: ...
|
||||
|
||||
def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
def _crc8(data: bytes) -> int:
|
||||
crc = 0
|
||||
for byte in data:
|
||||
crc ^= byte
|
||||
for _ in range(8):
|
||||
crc = ((crc << 1) ^ (0x07 if crc & 0x80 else 0)) & 0xFF
|
||||
return crc
|
||||
|
||||
|
||||
def _rgb_bytes(color: Sequence[object]) -> bytes:
|
||||
channels = [channel for channel in color if isinstance(channel, int) and not isinstance(channel, bool)]
|
||||
if (len(color) != 3 or len(channels) != 3
|
||||
or any(not 0 <= channel <= 255 for channel in channels)):
|
||||
raise ValueError("RGB channels must be integers from 0 to 255")
|
||||
return bytes(channels)
|
||||
|
||||
|
||||
def _led_packet(colors: Sequence[Sequence[object]]) -> bytes:
|
||||
if len(colors) != _LED_COUNT:
|
||||
raise ValueError("Each RAM stick requires exactly 12 LED colours")
|
||||
payload = bytes((_LED_COUNT,)) + b"".join(_rgb_bytes(color) for color in colors)
|
||||
return payload + bytes((_crc8(payload),))
|
||||
|
||||
|
||||
def _check_ntstatus(operation: str, status: int) -> None:
|
||||
if status < 0:
|
||||
value = status & 0xFFFFFFFF
|
||||
if value == _STATUS_ACCESS_DENIED:
|
||||
raise OSError(f"{operation}: PawnIO access denied; run the dashboard as administrator")
|
||||
if value == _STATUS_NO_SUCH_DEVICE:
|
||||
raise OSError(f"{operation}: no response from the RAM lighting controller")
|
||||
raise OSError(f"{operation}: NTSTATUS 0x{value:08X}")
|
||||
|
||||
|
||||
class PawnIoSmbus:
|
||||
"""Minimal, synchronized access to the four supported Corsair DDR5 RGB controllers."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._dll = None
|
||||
self._handle = wt.HANDLE()
|
||||
self._mutex = None
|
||||
self._kernel32 = None
|
||||
self._last_packets: dict[int, bytes] = {}
|
||||
|
||||
def open(self) -> None:
|
||||
if self._handle.value:
|
||||
return
|
||||
if not hasattr(ctypes, "WinDLL"):
|
||||
raise OSError("Corsair RAM lighting requires Windows and PawnIO")
|
||||
if corsair_software_running("Corsair DRAM", fan_tools=False):
|
||||
raise MemoryLightingBusy("RAM lighting busy: exit iCUE or disable OpenRGB's Corsair DRAM detector")
|
||||
|
||||
try:
|
||||
dll = ctypes.WinDLL(_PAWNIO_DLL, use_last_error=True)
|
||||
dll.pawnio_open_nt.argtypes = [ctypes.POINTER(wt.HANDLE)]
|
||||
dll.pawnio_load_nt.argtypes = [wt.HANDLE, ctypes.c_char_p, ctypes.c_size_t]
|
||||
dll.pawnio_execute_nt.argtypes = [
|
||||
wt.HANDLE, ctypes.c_char_p, ctypes.POINTER(_CELL), ctypes.c_size_t,
|
||||
ctypes.POINTER(_CELL), ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t),
|
||||
]
|
||||
dll.pawnio_execute_nt.restype = ctypes.c_int32
|
||||
dll.pawnio_close_nt.argtypes = [wt.HANDLE]
|
||||
|
||||
handle = wt.HANDLE()
|
||||
_check_ntstatus("Opening PawnIO", dll.pawnio_open_nt(ctypes.byref(handle)))
|
||||
self._dll, self._handle = dll, handle
|
||||
with open(_SMBUS_MODULE, "rb") as module_file:
|
||||
module = module_file.read()
|
||||
_check_ntstatus("Loading the PawnIO I801 SMBus module",
|
||||
dll.pawnio_load_nt(handle, module, len(module)))
|
||||
|
||||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR]
|
||||
k32.CreateMutexW.restype = wt.HANDLE
|
||||
k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||
k32.WaitForSingleObject.restype = wt.DWORD
|
||||
k32.ReleaseMutex.argtypes = [wt.HANDLE]
|
||||
k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
self._kernel32 = k32
|
||||
self._mutex = k32.CreateMutexW(None, False, r"Global\Access_SMBUS.HTP.Method")
|
||||
if not self._mutex:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
with self._bus():
|
||||
_, _, pci_ids = self._execute(b"ioctl_identity", count=3)
|
||||
if pci_ids & 0xFFFF != 0x8086:
|
||||
raise OSError(f"Expected an Intel SMBus controller, found PCI IDs 0x{pci_ids:016X}")
|
||||
self._verify_controllers()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
self._last_packets.clear()
|
||||
if self._mutex is not None:
|
||||
if self._kernel32 is None:
|
||||
raise OSError("Cannot close SMBus mutex: kernel32 was not initialized")
|
||||
if not self._kernel32.CloseHandle(self._mutex):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
self._mutex = None
|
||||
if self._handle.value and self._dll is not None:
|
||||
handle, self._handle = self._handle, wt.HANDLE()
|
||||
dll, self._dll = self._dll, None
|
||||
_check_ntstatus("Closing PawnIO", dll.pawnio_close_nt(handle))
|
||||
|
||||
def show(self, color: tuple[int, int, int]) -> None:
|
||||
self.show_frame(_solid_frame(color), force=True)
|
||||
|
||||
def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None:
|
||||
if len(colors) != len(_ADDRESSES):
|
||||
raise ValueError("RAM frames require exactly four sticks in physical top-to-bottom order")
|
||||
packets = tuple(_led_packet(stick) for stick in colors)
|
||||
with self._bus():
|
||||
for address, packet in zip(_ADDRESSES, packets):
|
||||
if not force and self._last_packets.get(address) == packet:
|
||||
continue
|
||||
self._write_block(address, 0x31, packet[:32])
|
||||
time.sleep(0.001)
|
||||
self._write_block(address, 0x32, packet[32:])
|
||||
self._last_packets[address] = packet
|
||||
|
||||
@contextmanager
|
||||
def _bus(self) -> Generator[None, None, None]:
|
||||
if self._mutex is None or self._kernel32 is None:
|
||||
raise OSError("PawnIO SMBus is not open")
|
||||
result = self._kernel32.WaitForSingleObject(self._mutex, 500)
|
||||
if result == _WAIT_ABANDONED:
|
||||
self._kernel32.ReleaseMutex(self._mutex)
|
||||
raise OSError("The previous SMBus owner exited without releasing the bus")
|
||||
if result != _WAIT_OBJECT_0:
|
||||
raise OSError(f"Could not acquire the SMBus mutex (wait result 0x{result:08X})")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not self._kernel32.ReleaseMutex(self._mutex):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
|
||||
def _execute(self, operation: bytes, args: tuple[int, ...] = (), count: int = 0) -> tuple[int, ...]:
|
||||
if self._dll is None or not self._handle.value:
|
||||
raise OSError("PawnIO SMBus is not open")
|
||||
in_buffer = (_CELL * len(args))(*args)
|
||||
out_buffer = (_CELL * count)()
|
||||
written = ctypes.c_size_t()
|
||||
status = self._dll.pawnio_execute_nt(
|
||||
self._handle, operation, in_buffer, len(in_buffer), out_buffer, len(out_buffer),
|
||||
ctypes.byref(written),
|
||||
)
|
||||
_check_ntstatus(operation.decode(), status)
|
||||
if written.value != count:
|
||||
raise OSError(f"{operation.decode()}: expected {count} output cells, got {written.value}")
|
||||
return tuple(out_buffer)
|
||||
|
||||
def _read_byte(self, address: int, register: int) -> int:
|
||||
return self._execute(b"ioctl_smbus_xfer", (address, 1, register, 2), 1)[0]
|
||||
|
||||
def _write_byte(self, address: int, register: int, value: int) -> None:
|
||||
self._execute(b"ioctl_smbus_xfer", (address, 0, register, 2, value))
|
||||
|
||||
def _write_block(self, address: int, register: int, data: bytes) -> None:
|
||||
if not 0 < len(data) <= 32:
|
||||
raise ValueError("SMBus block data must contain 1 to 32 bytes")
|
||||
packed = (bytes((len(data),)) + data).ljust(40, b"\x00")
|
||||
self._execute(b"ioctl_smbus_xfer",
|
||||
(address, 0, register, 5, *struct.unpack("<5Q", packed)))
|
||||
|
||||
def _read_buffer(self, address: int, selector: int, index: int, length: int) -> bytes:
|
||||
self._write_byte(address, selector, index)
|
||||
self._write_byte(address, 0x21, 0)
|
||||
data = bytes(self._read_byte(address, 0x40) for _ in range(length))
|
||||
actual = self._read_byte(address, 0x42)
|
||||
expected = _crc8(data)
|
||||
if actual != expected:
|
||||
raise OSError(f"RAM controller 0x{address:02X} buffer CRC mismatch "
|
||||
f"(0x{actual:02X} != 0x{expected:02X})")
|
||||
return data
|
||||
|
||||
def _verify_controllers(self) -> None:
|
||||
for address in _ADDRESSES:
|
||||
signature = self._read_byte(address, 0x43)
|
||||
revision = self._read_byte(address, 0x44)
|
||||
if signature not in (0x1A, 0x1B, 0x1C) or revision not in (1, 3, 4):
|
||||
raise OSError(f"Unrecognized RAM lighting controller at 0x{address:02X}")
|
||||
info = self._read_buffer(address, 0x61, 0, 32)
|
||||
vendor = int.from_bytes(info[0:2], "little")
|
||||
product = int.from_bytes(info[2:4], "little")
|
||||
protocol = info[28]
|
||||
if (vendor, product, protocol) != (0x1B1C, 0x0601, 4):
|
||||
raise OSError(f"Unsupported RAM at 0x{address:02X}: "
|
||||
f"{vendor:04X}:{product:04X}, RGB protocol {protocol}")
|
||||
log.info("Corsair Dominator Platinum DDR5 detected at SMBus address 0x%02X", address)
|
||||
|
||||
|
||||
class MemoryLighting:
|
||||
"""Run temperature colours or the mirrored RAM chase; disabled mode holds black."""
|
||||
|
||||
def __init__(self, theme: Theme, driver_factory: Callable[[], _MemoryLightingDriver] = PawnIoSmbus,
|
||||
chase_timing: ChaseTiming | None = None):
|
||||
if not (math.isfinite(theme.temp_warn) and math.isfinite(theme.temp_hot)
|
||||
and theme.temp_hot > theme.temp_warn):
|
||||
raise ValueError("RAM temperature range must be finite and increasing")
|
||||
self.theme = theme
|
||||
self.status = "off"
|
||||
self._driver_factory = driver_factory
|
||||
self._driver: _MemoryLightingDriver | None = None
|
||||
self._retry_at = 0.0
|
||||
self._last_error: str | None = None
|
||||
self._last_frame: MemoryFrame | None = None
|
||||
self._last_frame_at = -math.inf
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._touched = False
|
||||
self._temperatures: tuple[float | None, float | None] = (None, None)
|
||||
self._power: float | None = None
|
||||
self._pattern: str | None = None
|
||||
self._owns_chase_timing = chase_timing is None
|
||||
self._chase_timing = chase_timing if chase_timing is not None else ChaseTiming()
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
|
||||
def run(self, stop: threading.Event, enabled: threading.Event,
|
||||
side_chase: threading.Event | None = None) -> None:
|
||||
try:
|
||||
while not stop.is_set():
|
||||
cpu_temp, gpu_temp = self._temperatures
|
||||
self.update(cpu_temp, enabled.is_set(), gpu_temp=gpu_temp,
|
||||
side_chase=side_chase.is_set() if side_chase is not None else False)
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
except Exception:
|
||||
log.exception("RAM lighting worker failed")
|
||||
self._set_status("RAM lighting worker stopped; check dashboard.log")
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
self._temperatures = (cpu_temp, gpu_temp)
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
self._power = total_watts
|
||||
self._chase_timing.set_power(total_watts)
|
||||
|
||||
def update(self, cpu_temp: float | None, enabled: bool, *, gpu_temp: float | None = None,
|
||||
side_chase: bool = False) -> None:
|
||||
now = time.monotonic()
|
||||
pattern = "chase" if side_chase else "temperature" if enabled else None
|
||||
if pattern != self._pattern:
|
||||
self._pattern = pattern
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
self._last_frame_at = -math.inf
|
||||
readings = [(temp, source) for temp, source in ((cpu_temp, "CPU"), (gpu_temp, "GPU"))
|
||||
if temp is not None and math.isfinite(temp)]
|
||||
reading = max(readings, key=lambda item: item[0]) if readings else None
|
||||
color = None
|
||||
if reading is not None:
|
||||
strength = min(1.0, max(0.0, (reading[0] - self.theme.temp_warn)
|
||||
/ (self.theme.temp_hot - self.theme.temp_warn)))
|
||||
color = side_chase_color(strength)
|
||||
|
||||
if side_chase:
|
||||
phase, rate = self._chase_timing.sample(now)
|
||||
target = memory_chase_frame(memory_chase_step(phase))
|
||||
elif enabled and color is None:
|
||||
if self._driver is None and not self._touched:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
return
|
||||
target = self._last_frame
|
||||
if target is None:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
return
|
||||
elif enabled:
|
||||
assert color is not None
|
||||
target = _solid_frame(color)
|
||||
else:
|
||||
target = _solid_frame(_BLACK)
|
||||
|
||||
if self._driver is None:
|
||||
if now < self._retry_at:
|
||||
return
|
||||
try:
|
||||
driver = self._driver_factory()
|
||||
driver.open()
|
||||
except OSError as error:
|
||||
self._fail(error)
|
||||
return
|
||||
self._driver = driver
|
||||
self._last_error = None
|
||||
log.info("RAM lighting SMBus opened")
|
||||
|
||||
assert target is not None
|
||||
keepalive = now - self._last_keepalive_at >= _KEEPALIVE_SECONDS
|
||||
if ((target != self._last_frame or keepalive)
|
||||
and (not side_chase or now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS)):
|
||||
try:
|
||||
self._driver.show_frame(target, force=keepalive)
|
||||
except OSError as error:
|
||||
self._fail(error)
|
||||
return
|
||||
self._last_frame = target
|
||||
self._last_frame_at = now
|
||||
if keepalive:
|
||||
self._last_keepalive_at = now
|
||||
self._touched = True
|
||||
|
||||
if side_chase:
|
||||
watts = "" if self._power is None else f" at {self._power:.0f} W"
|
||||
self._set_status(f"RAM red side chase active ({SIDE_CHASE_CYCLE_STEPS / rate:.1f} s/cycle{watts})")
|
||||
elif enabled and color is None:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
elif enabled:
|
||||
assert reading is not None
|
||||
self._set_status(f"RAM temperature lighting active ({reading[1]} {reading[0]:.0f} \u00b0C)")
|
||||
else:
|
||||
self._set_status("RAM lighting off")
|
||||
|
||||
def close(self) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
if driver is not None:
|
||||
if self._touched:
|
||||
try:
|
||||
driver.show(_BLACK)
|
||||
except OSError:
|
||||
log.exception("Couldn't leave RAM lighting dark")
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't release the RAM lighting SMBus")
|
||||
self._last_frame = None
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._set_status("off")
|
||||
|
||||
def _fail(self, error: OSError) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
if driver is not None:
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't close the failed RAM lighting SMBus")
|
||||
self._last_frame = None
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._retry_at = time.monotonic() + _RETRY_SECONDS
|
||||
message = str(error) or type(error).__name__
|
||||
self._set_status(message)
|
||||
if message != self._last_error:
|
||||
log.warning("RAM lighting unavailable: %s", message, exc_info=not isinstance(error, MemoryLightingBusy))
|
||||
self._last_error = message
|
||||
|
||||
def _set_status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
self.status = status
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Lighting service: one worker per device, one mode per zone, saved in settings.json.
|
||||
|
||||
Zones and their modes (see kurgan.settings.LIGHTING_MODES):
|
||||
case_fans Lighting Node CORE QL120 LEDs: off (hardware effect), temperature, chase
|
||||
memory Dominator DDR5: off (held dark while running), temperature, chase
|
||||
gpu ASUS RTX 4090 LED row: off (its own effect), chase
|
||||
|
||||
The three chases share one power-paced clock, so they stay in step.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting
|
||||
from kurgan.lighting.gpu import GpuLighting
|
||||
from kurgan.lighting.memory import MemoryLighting
|
||||
from kurgan.settings import LIGHTING_MODES, Settings
|
||||
from kurgan.theme import Theme
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
ZONE_LABELS = {"case_fans": "Case fan LEDs", "memory": "RAM", "gpu": "GPU"}
|
||||
MODE_LABELS = {"off": "Off", "temperature": "Temperature", "chase": "Red side chase"}
|
||||
|
||||
|
||||
class LightingService:
|
||||
def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float],
|
||||
overrides: dict[str, str] | None = None, *, rgb=None, memory=None, gpu=None):
|
||||
"""chase: (idle s/LED, full-power s/LED, idle watts, full watts).
|
||||
overrides: modes for this run only (CLI flags), not saved."""
|
||||
self._settings = settings
|
||||
self._lock = threading.Lock()
|
||||
self._events = {zone: {mode: threading.Event() for mode in modes if mode != "off"}
|
||||
for zone, modes in LIGHTING_MODES.items()}
|
||||
self._overridden = set(overrides or ())
|
||||
modes = settings.section("lighting")
|
||||
modes.update(overrides or {})
|
||||
self._modes: dict[str, str] = {}
|
||||
for zone, mode in modes.items():
|
||||
self._apply(zone, mode)
|
||||
step, fast, idle_w, full_w = chase
|
||||
self.timing = ChaseTiming(step, fast, (idle_w, full_w))
|
||||
self.timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
self.rgb = rgb or RGBLighting(theme, step, fast, (idle_w, full_w), chase_timing=self.timing)
|
||||
self.memory = memory or MemoryLighting(theme, chase_timing=self.timing)
|
||||
self.gpu = gpu or GpuLighting(self.timing)
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._power: float | None = None
|
||||
|
||||
def _apply(self, zone: str, mode: str) -> None:
|
||||
events = self._events[zone]
|
||||
# Clear the old pattern before setting the new one, as the tray always did.
|
||||
for name, event in events.items():
|
||||
if name != mode:
|
||||
event.clear()
|
||||
if mode != "off":
|
||||
events[mode].set()
|
||||
self._modes[zone] = mode
|
||||
|
||||
def start(self, stop: threading.Event) -> None:
|
||||
e = self._events
|
||||
for name, target, args in (
|
||||
("case-fan-lighting", self.rgb.run, (stop, e["case_fans"]["temperature"], e["case_fans"]["chase"])),
|
||||
("memory-lighting", self.memory.run, (stop, e["memory"]["temperature"], e["memory"]["chase"])),
|
||||
("gpu-lighting", self.gpu.run, (stop, e["gpu"]["chase"]))):
|
||||
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
|
||||
thread.start()
|
||||
self._threads.append(thread)
|
||||
|
||||
def join(self) -> None:
|
||||
for thread in self._threads:
|
||||
thread.join()
|
||||
|
||||
def on_telemetry(self, cpu_temp: float | None, gpu_temp: float | None, total_watts: float | None) -> None:
|
||||
self._power = total_watts
|
||||
self.rgb.set_temperature(cpu_temp, gpu_temp)
|
||||
self.rgb.set_power(total_watts)
|
||||
self.memory.set_temperature(cpu_temp, gpu_temp)
|
||||
self.memory.set_power(total_watts)
|
||||
|
||||
def mode(self, zone: str) -> str:
|
||||
return self._modes[zone]
|
||||
|
||||
def set_mode(self, zone: str, mode: str) -> None:
|
||||
"""Save first, then switch, so a failed save leaves the lighting as it was."""
|
||||
if zone not in LIGHTING_MODES or mode not in LIGHTING_MODES[zone]:
|
||||
raise ValueError(f"Unknown lighting {zone!r} mode {mode!r}")
|
||||
with self._lock:
|
||||
self._settings.update("lighting", **{zone: mode})
|
||||
self._overridden.discard(zone)
|
||||
self._apply(zone, mode)
|
||||
log.info("%s lighting: %s", ZONE_LABELS[zone], mode)
|
||||
|
||||
def statuses(self) -> dict[str, str]:
|
||||
return {"case_fans": self.rgb.status, "memory": self.memory.status, "gpu": self.gpu.status}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
statuses = self.statuses()
|
||||
# The eased rate once a chase is running; the target rate for the current power until then.
|
||||
rate = self.timing.rate or self.timing.rate_for(self._power)
|
||||
chasing = "chase" in self._modes.values()
|
||||
return {"chase_ms_per_led": round(1000 / rate) if chasing else None,
|
||||
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": self._modes[zone],
|
||||
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in modes],
|
||||
"status": statuses[zone], "this_run_only": zone in self._overridden}
|
||||
for zone, modes in LIGHTING_MODES.items()]}
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Where The Kurgan keeps its settings and logs."""
|
||||
|
||||
import os
|
||||
|
||||
_LOCAL = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
|
||||
|
||||
# KURGAN_DATA_DIR moves settings and logs elsewhere (used by --demo runs next to the real service).
|
||||
DATA_DIR = os.environ.get("KURGAN_DATA_DIR") or os.path.join(_LOCAL, "Kurgan")
|
||||
LOG_PATH = os.path.join(DATA_DIR, "kurgan.log")
|
||||
SETTINGS_PATH = os.path.join(DATA_DIR, "settings.json")
|
||||
|
||||
# The TT LCD Dashboard's folder; its fan and lighting settings are imported once on first start.
|
||||
LEGACY_DIR = os.path.join(_LOCAL, "TTLcdDashboard")
|
||||
|
||||
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PROJECT_DIR = os.path.dirname(PACKAGE_DIR)
|
||||
@@ -0,0 +1,220 @@
|
||||
"""The Kurgan's settings: one JSON file, validated when loaded and before every save.
|
||||
|
||||
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
|
||||
|
||||
{
|
||||
"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5],
|
||||
"profile": "balanced"},
|
||||
"lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"},
|
||||
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
|
||||
"web": {"port": 8080}
|
||||
}
|
||||
|
||||
The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the
|
||||
rest by the web UI. An invalid file stops The Kurgan from starting rather than silently
|
||||
dropping fan control. On first start the TT LCD Dashboard's settings are imported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
|
||||
from kurgan import paths
|
||||
from kurgan.ai import config as ai_config
|
||||
from kurgan.cooling.profiles import DEFAULT_PROFILE, PROFILES
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
LIGHTING_MODES = {
|
||||
"case_fans": ("off", "temperature", "chase"), # Lighting Node CORE (QL120 fan LEDs)
|
||||
"memory": ("off", "temperature", "chase"), # Dominator Platinum DDR5
|
||||
"gpu": ("off", "chase"), # ASUS ROG STRIX RTX 4090
|
||||
}
|
||||
DEFAULT_WEB_PORT = 8080
|
||||
|
||||
DEFAULTS = {
|
||||
"cooling": {"profile": DEFAULT_PROFILE},
|
||||
"lighting": {zone: "off" for zone in LIGHTING_MODES},
|
||||
"ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL,
|
||||
"idle_stop_minutes": ai_config.IDLE_STOP_MINUTES},
|
||||
"web": {"port": DEFAULT_WEB_PORT},
|
||||
}
|
||||
_OPTIONAL = {
|
||||
"cooling": {"gpu_ports", "cpu_ports", "top_channels"},
|
||||
"lighting": set(),
|
||||
"ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"},
|
||||
"web": set(),
|
||||
}
|
||||
|
||||
|
||||
class SettingsError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _ports(value, where: str) -> list[int]:
|
||||
from kurgan.cooling.control import parse_ports
|
||||
|
||||
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
||||
raise SettingsError(f"{where} must be an array of integers")
|
||||
try:
|
||||
return list(parse_ports(",".join(map(str, value))))
|
||||
except argparse.ArgumentTypeError as e:
|
||||
raise SettingsError(f"{where}: {e}") from None
|
||||
|
||||
|
||||
def _port_number(value, where: str) -> int:
|
||||
if type(value) is not int or not 1024 <= value <= 65535:
|
||||
raise SettingsError(f"{where} must be a TCP port number 1024-65535")
|
||||
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"]
|
||||
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:
|
||||
raise SettingsError("cooling: save the GPU-side ports (gpu_ports) first")
|
||||
for key in ("gpu_ports", "cpu_ports"):
|
||||
if key in cooling:
|
||||
cooling[key] = _ports(cooling[key], f"cooling.{key}")
|
||||
if set(cooling.get("cpu_ports", ())) & set(cooling.get("gpu_ports", ())):
|
||||
raise SettingsError("cooling: cpu_ports and gpu_ports must not overlap")
|
||||
if "top_channels" in cooling:
|
||||
from kurgan.cooling.board_fans import parse_channels
|
||||
|
||||
value = cooling["top_channels"]
|
||||
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
||||
raise SettingsError("cooling.top_channels must be an array of integers")
|
||||
try:
|
||||
cooling["top_channels"] = list(parse_channels(",".join(map(str, value))))
|
||||
except argparse.ArgumentTypeError as e:
|
||||
raise SettingsError(f"cooling.top_channels: {e}") from None
|
||||
|
||||
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)}")
|
||||
|
||||
ai = out["ai"]
|
||||
if ai["active"] is not None and ai["active"] not in ai_config.BACKENDS:
|
||||
raise SettingsError(f"ai.active must be null or one of {', '.join(ai_config.BACKENDS)}")
|
||||
if ai["strata_model"] not in ai_config.STRATA_MODELS:
|
||||
raise SettingsError(f"ai.strata_model must be one of {', '.join(ai_config.STRATA_MODELS)}")
|
||||
if type(ai["idle_stop_minutes"]) is not int or not 0 <= ai["idle_stop_minutes"] <= 1440:
|
||||
raise SettingsError("ai.idle_stop_minutes must be 0 (never) to 1440")
|
||||
for key in ("strata_root", "llama_server", "llama_presets", "llama_model"):
|
||||
if key in ai and (not isinstance(ai[key], str) or not ai[key]):
|
||||
raise SettingsError(f"ai.{key} must be a non-empty string")
|
||||
for key in ("strata_port", "llama_port"):
|
||||
if key in ai:
|
||||
_port_number(ai[key], f"ai.{key}")
|
||||
if ai.get("strata_port", ai_config.STRATA_PORT) == ai.get("llama_port", ai_config.LLAMA_PORT):
|
||||
raise SettingsError("ai: Strata and llama.cpp need different ports")
|
||||
_port_number(out["web"]["port"], "web.port")
|
||||
return out
|
||||
|
||||
|
||||
def write_json_atomic(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
temporary = path + ".tmp"
|
||||
try:
|
||||
with open(temporary, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.remove(temporary)
|
||||
|
||||
|
||||
def _legacy(legacy_dir: str) -> dict:
|
||||
"""The TT LCD Dashboard's fan-control.json, memory-lighting.json and gpu-lighting.json."""
|
||||
data: dict = {}
|
||||
|
||||
def read(name: str):
|
||||
try:
|
||||
with open(os.path.join(legacy_dir, name), encoding="utf-8") as stream:
|
||||
return json.load(stream)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except ValueError as e:
|
||||
raise SettingsError(f"{legacy_dir}\\{name}: {e}") from None
|
||||
|
||||
fans = read("fan-control.json")
|
||||
if fans is not None:
|
||||
if not isinstance(fans, dict) or not set(fans) <= {"gpu_ports", "cpu_ports", "top_channels"}:
|
||||
raise SettingsError(f"{legacy_dir}\\fan-control.json has unexpected contents")
|
||||
data["cooling"] = dict(fans)
|
||||
for name, zone in (("memory-lighting.json", "memory"), ("gpu-lighting.json", "gpu")):
|
||||
mode = read(name)
|
||||
if mode is not None:
|
||||
if not isinstance(mode, dict) or set(mode) != {"mode"}:
|
||||
raise SettingsError(f"{legacy_dir}\\{name} has unexpected contents")
|
||||
data.setdefault("lighting", {})[zone] = mode["mode"]
|
||||
return data
|
||||
|
||||
|
||||
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)."""
|
||||
self.path = path
|
||||
self._lock = threading.RLock()
|
||||
self.created = False
|
||||
try:
|
||||
with open(path, encoding="utf-8") as stream:
|
||||
raw = json.load(stream)
|
||||
except FileNotFoundError:
|
||||
raw = _legacy(legacy_dir) if legacy_dir else {}
|
||||
for section, values in (seed or {}).items():
|
||||
raw.setdefault(section, {}).update(values)
|
||||
self.created = True
|
||||
except ValueError as e:
|
||||
raise SettingsError(f"{path}: {e}") from None
|
||||
try:
|
||||
self._data = validate(raw)
|
||||
except SettingsError as e:
|
||||
raise SettingsError(f"{path}: {e}") from None
|
||||
if self.created:
|
||||
write_json_atomic(path, self._data)
|
||||
log.info("Created %s%s", path, " from the TT LCD Dashboard's settings" if raw else "")
|
||||
|
||||
def section(self, name: str) -> dict:
|
||||
with self._lock:
|
||||
return copy.deepcopy(self._data[name])
|
||||
|
||||
def get(self, section: str, key: str, default=None):
|
||||
with self._lock:
|
||||
return copy.deepcopy(self._data[section].get(key, default))
|
||||
|
||||
def update(self, section: str, **changes) -> None:
|
||||
"""Validate and save; on any error nothing changes, in memory or on disk."""
|
||||
with self._lock:
|
||||
data = copy.deepcopy(self._data)
|
||||
data[section].update(changes)
|
||||
data = validate(data)
|
||||
write_json_atomic(self.path, data)
|
||||
self._data = data
|
||||
@@ -0,0 +1 @@
|
||||
"""Telemetry: CPU, GPU and whole-PC power readings, sampled once for every consumer."""
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Sensor readings shared by the LCD, lighting, cooling and the web UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class Readings:
|
||||
temp: float | None = None # deg C
|
||||
load: float | None = None # percent
|
||||
clock: float | None = None # MHz
|
||||
power: float | None = None # W
|
||||
|
||||
|
||||
@dataclass
|
||||
class PowerReadings:
|
||||
cpu: float | None = None # W, CPU package (measured)
|
||||
gpu: float | None = None # W, graphics card board power (measured)
|
||||
other: float | None = None # W, rest of the PC (partly measured, partly estimated)
|
||||
parts: dict[str, float] = field(default_factory=dict) # what makes up `other`
|
||||
|
||||
@property
|
||||
def total(self) -> float | None:
|
||||
if self.cpu is None or self.gpu is None or self.other is None:
|
||||
return None
|
||||
return self.cpu + self.gpu + self.other
|
||||
@@ -0,0 +1,877 @@
|
||||
"""Hardware readings for the dashboard (Windows).
|
||||
|
||||
CPU load / clock : Windows performance counters (no admin needed)
|
||||
CPU temp / power : Intel MSRs via the PawnIO driver (needs PawnIO installed and admin)
|
||||
GPU load : Windows GPU Engine counters, i.e. the Task Manager figure (NVML as fallback)
|
||||
GPU temp etc. : NVIDIA NVML (nvidia-ml-py)
|
||||
Everything else : SystemPower, which adds up the rest of the PC. Fan speeds come from a Corsair
|
||||
Commander PRO, drive activity from performance counters, drive ratings from the
|
||||
NVMe drives themselves and the memory layout from the BIOS (SMBIOS). Parts with no
|
||||
sensor at all use the fixed figures in PowerModel.
|
||||
|
||||
Run `python sensors.py` for a live breakdown of where the watts go.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from kurgan.hardware import PAWNIO_DIR
|
||||
from kurgan.hardware.hid import HidChannel, hid_device_paths
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- PDH
|
||||
|
||||
class _PdhValue(ctypes.Structure):
|
||||
_fields_ = [("CStatus", wt.DWORD), ("_pad", wt.DWORD), ("doubleValue", ctypes.c_double)]
|
||||
|
||||
|
||||
class _PdhItem(ctypes.Structure):
|
||||
_fields_ = [("szName", wt.LPWSTR), ("FmtValue", _PdhValue)]
|
||||
|
||||
|
||||
PDH_FMT_DOUBLE = 0x00000200
|
||||
PDH_FMT_NOCAP100 = 0x00008000
|
||||
PDH_MORE_DATA = 0x800007D2
|
||||
_pdh_dll = None
|
||||
|
||||
|
||||
def _pdh():
|
||||
global _pdh_dll
|
||||
if _pdh_dll is None:
|
||||
p = ctypes.WinDLL("pdh")
|
||||
p.PdhOpenQueryW.argtypes = [wt.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wt.HANDLE)]
|
||||
p.PdhAddEnglishCounterW.argtypes = [wt.HANDLE, wt.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wt.HANDLE)]
|
||||
p.PdhCollectQueryData.argtypes = [wt.HANDLE]
|
||||
p.PdhGetFormattedCounterValue.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.DWORD),
|
||||
ctypes.POINTER(_PdhValue)]
|
||||
p.PdhGetFormattedCounterArrayW.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.DWORD),
|
||||
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
|
||||
p.PdhGetFormattedCounterArrayW.restype = wt.DWORD
|
||||
_pdh_dll = p
|
||||
return _pdh_dll
|
||||
|
||||
|
||||
def _pdh_query() -> wt.HANDLE:
|
||||
q = wt.HANDLE()
|
||||
if _pdh().PdhOpenQueryW(None, 0, ctypes.byref(q)) != 0:
|
||||
raise OSError("PdhOpenQuery failed")
|
||||
return q
|
||||
|
||||
|
||||
class PerfCounters:
|
||||
def __init__(self, paths: dict[str, str]):
|
||||
self._pdh = _pdh()
|
||||
self.query = _pdh_query()
|
||||
self.counters: dict[str, wt.HANDLE] = {}
|
||||
for name, path in paths.items():
|
||||
h = wt.HANDLE()
|
||||
if self._pdh.PdhAddEnglishCounterW(self.query, path, 0, ctypes.byref(h)) == 0:
|
||||
self.counters[name] = h
|
||||
else:
|
||||
log.warning("Performance counter unavailable: %s", path)
|
||||
self._pdh.PdhCollectQueryData(self.query)
|
||||
|
||||
def sample(self) -> dict[str, float | None]:
|
||||
self._pdh.PdhCollectQueryData(self.query)
|
||||
out: dict[str, float | None] = {}
|
||||
for name, h in self.counters.items():
|
||||
v = _PdhValue()
|
||||
st = self._pdh.PdhGetFormattedCounterValue(h, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100, None, ctypes.byref(v))
|
||||
out[name] = v.doubleValue if st == 0 else None
|
||||
return out
|
||||
|
||||
|
||||
class PdhArray:
|
||||
"""Every instance of a wildcard counter, e.g. \\PhysicalDisk(*)\\% Idle Time."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self._pdh = _pdh()
|
||||
self.query = _pdh_query()
|
||||
self.counter = wt.HANDLE()
|
||||
if self._pdh.PdhAddEnglishCounterW(self.query, path, 0, ctypes.byref(self.counter)) != 0:
|
||||
raise OSError(f"Performance counter unavailable: {path}")
|
||||
self._pdh.PdhCollectQueryData(self.query)
|
||||
|
||||
def sample(self) -> list[tuple[str, float]] | None:
|
||||
self._pdh.PdhCollectQueryData(self.query)
|
||||
fmt = PDH_FMT_DOUBLE | PDH_FMT_NOCAP100
|
||||
size, count = wt.DWORD(0), wt.DWORD(0)
|
||||
st = self._pdh.PdhGetFormattedCounterArrayW(self.counter, fmt, ctypes.byref(size), ctypes.byref(count), None)
|
||||
if st != PDH_MORE_DATA or not size.value:
|
||||
return None
|
||||
buf = (ctypes.c_byte * size.value)()
|
||||
if self._pdh.PdhGetFormattedCounterArrayW(self.counter, fmt, ctypes.byref(size), ctypes.byref(count), buf) != 0:
|
||||
return None
|
||||
# from_buffer, not ctypes.cast: cast makes buf reference itself, so each ~100 KB buffer
|
||||
# (GPU Engine has hundreds of instances) waited for the cycle collector instead of being freed here.
|
||||
items = (_PdhItem * count.value).from_buffer(buf)
|
||||
return [(items[i].szName, items[i].FmtValue.doubleValue) for i in range(count.value)
|
||||
if items[i].FmtValue.CStatus in (0, 1)] # PDH_CSTATUS_VALID_DATA / NEW_DATA
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- GPU load as Task Manager shows it
|
||||
|
||||
def nvidia_adapter_luid() -> str | None:
|
||||
"""LUID of the NVIDIA adapter as it appears in GPU Engine counter names ("0xHHHHHHHH_0xLLLLLLLL")."""
|
||||
|
||||
class LUID(ctypes.Structure):
|
||||
_fields_ = [("LowPart", wt.DWORD), ("HighPart", wt.LONG)]
|
||||
|
||||
class DESC1(ctypes.Structure):
|
||||
_fields_ = [("Description", wt.WCHAR * 128), ("VendorId", wt.UINT), ("DeviceId", wt.UINT),
|
||||
("SubSysId", wt.UINT), ("Revision", wt.UINT), ("DedicatedVideoMemory", ctypes.c_size_t),
|
||||
("DedicatedSystemMemory", ctypes.c_size_t), ("SharedSystemMemory", ctypes.c_size_t),
|
||||
("AdapterLuid", LUID), ("Flags", wt.UINT)]
|
||||
|
||||
class GUID(ctypes.Structure):
|
||||
_fields_ = [("a", wt.DWORD), ("b", wt.WORD), ("c", wt.WORD), ("d", ctypes.c_ubyte * 8)]
|
||||
|
||||
def vcall(obj, index, restype, *argtypes):
|
||||
vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
||||
return ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *argtypes)(vtbl[index])
|
||||
|
||||
iid_factory1 = GUID(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87))
|
||||
factory = ctypes.c_void_p()
|
||||
if ctypes.WinDLL("dxgi").CreateDXGIFactory1(ctypes.byref(iid_factory1), ctypes.byref(factory)) != 0:
|
||||
return None
|
||||
best = None
|
||||
try:
|
||||
i = 0
|
||||
while True:
|
||||
adapter = ctypes.c_void_p()
|
||||
# IDXGIFactory1::EnumAdapters1 (vtable 12)
|
||||
if vcall(factory, 12, ctypes.c_long, wt.UINT, ctypes.POINTER(ctypes.c_void_p))(factory, i, ctypes.byref(adapter)) != 0:
|
||||
break
|
||||
desc = DESC1()
|
||||
# IDXGIAdapter1::GetDesc1 (vtable 10)
|
||||
vcall(adapter, 10, ctypes.c_long, ctypes.POINTER(DESC1))(adapter, ctypes.byref(desc))
|
||||
vcall(adapter, 2, wt.ULONG)(adapter) # Release
|
||||
if desc.VendorId == 0x10DE and (best is None or desc.DedicatedVideoMemory > best[0]):
|
||||
luid = f"0x{desc.AdapterLuid.HighPart & 0xFFFFFFFF:08X}_0x{desc.AdapterLuid.LowPart:08X}"
|
||||
best = (desc.DedicatedVideoMemory, luid)
|
||||
i += 1
|
||||
finally:
|
||||
vcall(factory, 2, wt.ULONG)(factory)
|
||||
return best[1] if best else None
|
||||
|
||||
|
||||
class GpuEngineLoad:
|
||||
"""GPU utilisation computed the way Task Manager does it.
|
||||
|
||||
Windows reports, per process and per GPU engine, how much of the time that engine had
|
||||
work. Task Manager adds the processes up per engine and shows the busiest engine. NVML
|
||||
instead reports the time a kernel was actually executing, which reads ~10% lower for
|
||||
queue-heavy workloads.
|
||||
"""
|
||||
|
||||
def __init__(self, luid: str):
|
||||
self.luid = f"luid_{luid}".lower()
|
||||
self.counter = PdhArray(r"\GPU Engine(*)\Utilization Percentage")
|
||||
|
||||
def sample(self) -> float | None:
|
||||
items = self.counter.sample()
|
||||
if items is None:
|
||||
return None
|
||||
engines: dict[str, float] = {}
|
||||
for name, value in items:
|
||||
name = name.lower()
|
||||
pos = name.find(self.luid)
|
||||
if pos < 0:
|
||||
continue
|
||||
key = name[pos:] # luid_..._phys_N_eng_N_engtype_X (drops the pid_ prefix)
|
||||
engines[key] = engines.get(key, 0.0) + value
|
||||
if not engines:
|
||||
return 0.0
|
||||
return min(100.0, max(engines.values()))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- PawnIO / Intel MSR
|
||||
|
||||
class IntelMsr:
|
||||
"""Reads Intel MSRs through PawnIO's signed IntelMSR module."""
|
||||
|
||||
DEVICE = r"\\?\GLOBALROOT\Device\PawnIO"
|
||||
IOCTL_LOAD_BINARY = (41394 << 16) | (0x821 << 2) # 0xA1B22084
|
||||
IOCTL_EXECUTE_FN = (41394 << 16) | (0x841 << 2) # 0xA1B22104
|
||||
MODULE = os.path.join(PAWNIO_DIR, "IntelMSR.bin")
|
||||
|
||||
def __init__(self):
|
||||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
||||
k32.CreateFileW.restype = wt.HANDLE
|
||||
k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD,
|
||||
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
|
||||
k32.DeviceIoControl.restype = wt.BOOL
|
||||
k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
k32.GetCurrentThread.restype = wt.HANDLE
|
||||
k32.SetThreadAffinityMask.argtypes = [wt.HANDLE, ctypes.c_size_t]
|
||||
k32.SetThreadAffinityMask.restype = ctypes.c_size_t
|
||||
self._k32 = k32
|
||||
h = k32.CreateFileW(self.DEVICE, 0xC0000000, 0x3, None, 3, 0, None)
|
||||
if h == wt.HANDLE(-1).value:
|
||||
err = ctypes.get_last_error()
|
||||
reason = "run as administrator" if err == 5 else "is PawnIO installed?"
|
||||
raise OSError(f"Cannot open PawnIO ({ctypes.FormatError(err).strip()}; {reason})")
|
||||
self.handle = h
|
||||
with open(self.MODULE, "rb") as f:
|
||||
blob = f.read()
|
||||
buf = ctypes.create_string_buffer(blob, len(blob))
|
||||
ret = wt.DWORD()
|
||||
if not k32.DeviceIoControl(h, self.IOCTL_LOAD_BINARY, buf, len(blob), None, 0, ctypes.byref(ret), None):
|
||||
err = ctypes.get_last_error()
|
||||
k32.CloseHandle(h)
|
||||
raise OSError(f"PawnIO refused the IntelMSR module: {ctypes.FormatError(err).strip()}")
|
||||
|
||||
def close(self) -> None:
|
||||
if self.handle:
|
||||
self._k32.CloseHandle(self.handle)
|
||||
self.handle = None
|
||||
|
||||
def read(self, msr: int, cpu: int | None = None) -> int:
|
||||
name = b"ioctl_read_msr".ljust(32, b"\x00")
|
||||
inbuf = ctypes.create_string_buffer(name + struct.pack("<Q", msr), 40)
|
||||
outbuf = ctypes.create_string_buffer(8)
|
||||
ret = wt.DWORD()
|
||||
old = None
|
||||
if cpu is not None:
|
||||
old = self._k32.SetThreadAffinityMask(self._k32.GetCurrentThread(), 1 << cpu)
|
||||
try:
|
||||
ok = self._k32.DeviceIoControl(self.handle, self.IOCTL_EXECUTE_FN, inbuf, 40, outbuf, 8, ctypes.byref(ret), None)
|
||||
finally:
|
||||
if old:
|
||||
self._k32.SetThreadAffinityMask(self._k32.GetCurrentThread(), old)
|
||||
if not ok:
|
||||
raise OSError(f"MSR 0x{msr:X} read failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
||||
return struct.unpack("<Q", outbuf.raw)[0]
|
||||
|
||||
|
||||
class IntelPackage:
|
||||
"""Package temperature and RAPL package power for Intel CPUs."""
|
||||
|
||||
MSR_TEMPERATURE_TARGET = 0x1A2
|
||||
MSR_PACKAGE_THERM_STATUS = 0x1B1
|
||||
MSR_RAPL_POWER_UNIT = 0x606
|
||||
MSR_PKG_ENERGY_STATUS = 0x611
|
||||
|
||||
def __init__(self):
|
||||
self.msr = IntelMsr()
|
||||
tjmax = (self.msr.read(self.MSR_TEMPERATURE_TARGET, cpu=0) >> 16) & 0xFF
|
||||
self.tjmax = tjmax if 60 <= tjmax <= 125 else 100
|
||||
unit_bits = (self.msr.read(self.MSR_RAPL_POWER_UNIT) >> 8) & 0x1F
|
||||
self.energy_unit = 1.0 / (1 << unit_bits)
|
||||
self._last_energy = self.msr.read(self.MSR_PKG_ENERGY_STATUS) & 0xFFFFFFFF
|
||||
self._last_time = time.perf_counter()
|
||||
log.info("PawnIO OK: TjMax %d C, energy unit %.3g J", self.tjmax, self.energy_unit)
|
||||
|
||||
def temperature(self) -> float | None:
|
||||
v = self.msr.read(self.MSR_PACKAGE_THERM_STATUS, cpu=0)
|
||||
readout = (v >> 16) & 0x7F # degrees below TjMax
|
||||
# Bit 31 ("reading valid") is documented for the per-core MSR; not every CPU sets it
|
||||
# for the package MSR, so also accept any non-zero readout.
|
||||
if not (v & 0x80000000) and readout == 0:
|
||||
return None
|
||||
return float(self.tjmax - readout)
|
||||
|
||||
def power(self) -> float | None:
|
||||
now = time.perf_counter()
|
||||
e = self.msr.read(self.MSR_PKG_ENERGY_STATUS) & 0xFFFFFFFF
|
||||
dt = now - self._last_time
|
||||
if dt < 0.05:
|
||||
return None
|
||||
delta = (e - self._last_energy) & 0xFFFFFFFF
|
||||
self._last_energy, self._last_time = e, now
|
||||
return delta * self.energy_unit / dt
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- CPU
|
||||
|
||||
class CpuSensors:
|
||||
def __init__(self):
|
||||
base = r"\Processor Information(_Total)"
|
||||
self.pdh = PerfCounters({
|
||||
"utility": base + r"\% Processor Utility",
|
||||
"time": base + r"\% Processor Time",
|
||||
"perf": base + r"\% Processor Performance",
|
||||
"freq": base + r"\Processor Frequency",
|
||||
})
|
||||
self.pkg: IntelPackage | None = None
|
||||
self._pkg_error: str | None = None
|
||||
self._next_pkg_attempt = 0.0
|
||||
self._try_pkg()
|
||||
|
||||
def _try_pkg(self) -> None:
|
||||
if self.pkg or time.monotonic() < self._next_pkg_attempt:
|
||||
return
|
||||
try:
|
||||
self.pkg = IntelPackage()
|
||||
self._pkg_error = None
|
||||
except Exception as e: # PawnIO missing, not admin, non-Intel CPU, ...
|
||||
if str(e) != self._pkg_error:
|
||||
log.warning("CPU temperature/power unavailable: %s", e)
|
||||
self._pkg_error = str(e)
|
||||
self._next_pkg_attempt = time.monotonic() + 60
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
return "ok" if self.pkg else (self._pkg_error or "not started")
|
||||
|
||||
def read(self) -> Readings:
|
||||
s = self.pdh.sample()
|
||||
load = s.get("utility")
|
||||
if load is None:
|
||||
load = s.get("time")
|
||||
if load is not None:
|
||||
load = max(0.0, min(100.0, load))
|
||||
clock = None
|
||||
if s.get("perf") is not None and s.get("freq"):
|
||||
clock = s["freq"] * s["perf"] / 100.0
|
||||
temp = power = None
|
||||
self._try_pkg()
|
||||
if self.pkg:
|
||||
try:
|
||||
temp = self.pkg.temperature()
|
||||
power = self.pkg.power()
|
||||
except OSError as e:
|
||||
log.warning("MSR read failed, will retry: %s", e)
|
||||
self.pkg.msr.close()
|
||||
self.pkg = None
|
||||
return Readings(temp=temp, load=load, clock=clock, power=power)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- GPU
|
||||
|
||||
class GpuSensors:
|
||||
def __init__(self, index: int = 0, load_source: str = "windows"):
|
||||
"""load_source: "windows" = same figure as Task Manager, "nvml" = NVIDIA's kernel-busy figure."""
|
||||
import pynvml
|
||||
|
||||
self.nv = pynvml
|
||||
self.index = index
|
||||
self.handle = None
|
||||
self._last_sample_ts = 0
|
||||
self.engine_load: GpuEngineLoad | None = None
|
||||
if load_source == "windows":
|
||||
try:
|
||||
luid = nvidia_adapter_luid()
|
||||
if luid is None:
|
||||
raise OSError("no NVIDIA adapter found via DXGI")
|
||||
self.engine_load = GpuEngineLoad(luid)
|
||||
log.info("GPU load from Windows GPU engine counters (adapter %s)", luid)
|
||||
except Exception as e:
|
||||
log.warning("Task Manager-style GPU load unavailable, using NVML: %s", e)
|
||||
self._connect()
|
||||
|
||||
def _connect(self) -> None:
|
||||
try:
|
||||
self.nv.nvmlInit()
|
||||
self.handle = self.nv.nvmlDeviceGetHandleByIndex(self.index)
|
||||
limit = self.nv.nvmlDeviceGetEnforcedPowerLimit(self.handle) / 1000.0
|
||||
log.info("GPU: %s, power limit %.0f W", self.nv.nvmlDeviceGetName(self.handle), limit)
|
||||
except Exception as e:
|
||||
log.warning("NVIDIA GPU unavailable: %s", e)
|
||||
self.handle = None
|
||||
|
||||
def _get(self, fn, *args):
|
||||
try:
|
||||
return fn(self.handle, *args)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _utilization(self) -> float | None:
|
||||
"""Average GPU load since the previous call.
|
||||
|
||||
nvmlDeviceGetUtilizationRates only covers the driver's last ~1/6 s window, so a
|
||||
bursty workload can read 3% for one update while the whole second averaged 80%.
|
||||
The driver's sample buffer (about 6 samples/s) gives the true average instead.
|
||||
"""
|
||||
nv = self.nv
|
||||
try:
|
||||
_, samples = nv.nvmlDeviceGetSamples(self.handle, nv.NVML_GPU_UTILIZATION_SAMPLES,
|
||||
self._last_sample_ts)
|
||||
if samples:
|
||||
self._last_sample_ts = max(s.timeStamp for s in samples)
|
||||
values = [s.sampleValue.uiVal for s in samples]
|
||||
return sum(values) / len(values)
|
||||
except Exception:
|
||||
pass
|
||||
util = self._get(nv.nvmlDeviceGetUtilizationRates)
|
||||
return None if util is None else float(util.gpu)
|
||||
|
||||
def memory(self) -> tuple[int, int] | None:
|
||||
"""(used, total) bytes of graphics memory, or None while the GPU is unavailable."""
|
||||
if self.handle is None:
|
||||
return None
|
||||
info = self._get(self.nv.nvmlDeviceGetMemoryInfo)
|
||||
return None if info is None else (int(info.used), int(info.total))
|
||||
|
||||
def read(self) -> Readings:
|
||||
if self.handle is None:
|
||||
self._connect()
|
||||
if self.handle is None:
|
||||
return Readings()
|
||||
nv = self.nv
|
||||
temp = self._get(nv.nvmlDeviceGetTemperature, nv.NVML_TEMPERATURE_GPU)
|
||||
util = None
|
||||
if self.engine_load is not None:
|
||||
try:
|
||||
util = self.engine_load.sample()
|
||||
except Exception as e:
|
||||
log.debug("GPU engine counters failed: %s", e)
|
||||
if util is None:
|
||||
util = self._utilization()
|
||||
# Board power: everything on the card, including its fans, lighting and memory.
|
||||
power = self._get(nv.nvmlDeviceGetPowerUsage)
|
||||
clock = self._get(nv.nvmlDeviceGetClockInfo, nv.NVML_CLOCK_GRAPHICS)
|
||||
if temp is None and util is None and power is None:
|
||||
# driver reset or similar: reconnect next time
|
||||
try:
|
||||
nv.nvmlShutdown()
|
||||
except Exception:
|
||||
pass
|
||||
self.handle = None
|
||||
return Readings(
|
||||
temp=None if temp is None else float(temp),
|
||||
load=util,
|
||||
clock=None if clock is None else float(clock),
|
||||
power=None if power is None else power / 1000.0,
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- rest of the system
|
||||
|
||||
@dataclass
|
||||
class PowerModel:
|
||||
"""Figures for the parts of the PC that have no power sensor.
|
||||
|
||||
These are typical values for the hardware in this PC (MSI PRO Z790-P, DDR5, PCIe 4.0
|
||||
NVMe, Corsair 120 mm RGB fans); edit them to suit. Everything is DC watts, i.e. load on
|
||||
the power supply, not draw from the wall (which is ~8-12% higher for an 80 Plus Gold unit).
|
||||
"""
|
||||
|
||||
motherboard: float = 15.0 # chipset (~6 W on Z790), audio, LAN, Wi-Fi, Super I/O
|
||||
cpu_vrm_efficiency: float = 0.90 # the board's CPU regulators lose ~10% of what the package draws
|
||||
ddr5_dimm: tuple[float, float] = (2.5, 5.5) # W per DIMM: idle, flat out (scaled by CPU load)
|
||||
ddr4_dimm: tuple[float, float] = (1.5, 3.5)
|
||||
fan_idle: float = 0.3 # W per case fan: electronics, plus...
|
||||
fan_full: float = 1.7 # ...this much more at fan_ref_rpm (scales with rpm^2.5)
|
||||
fan_ref_rpm: float = 1500.0
|
||||
board_fans: float = 5.0 # CPU cooler fans/pump on motherboard headers (speeds not readable)
|
||||
usb_and_lighting: float = 12.0 # RGB on fans/RAM/board, keyboard, mouse, webcam, this LCD
|
||||
hdd_idle_minutes: float = 10.0 # assume a hard drive has spun down after this long without I/O
|
||||
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
||||
_k32.CreateFileW.restype = wt.HANDLE
|
||||
_k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD,
|
||||
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
|
||||
_k32.DeviceIoControl.restype = wt.BOOL
|
||||
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
_k32.GetSystemFirmwareTable.argtypes = [wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD]
|
||||
_k32.GetSystemFirmwareTable.restype = wt.UINT
|
||||
_k32.CreateToolhelp32Snapshot.argtypes = [wt.DWORD, wt.DWORD]
|
||||
_k32.CreateToolhelp32Snapshot.restype = wt.HANDLE
|
||||
_k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR]
|
||||
_k32.CreateMutexW.restype = wt.HANDLE
|
||||
|
||||
|
||||
class _PROCESSENTRY32W(ctypes.Structure):
|
||||
_fields_ = [("dwSize", wt.DWORD), ("cntUsage", wt.DWORD), ("th32ProcessID", wt.DWORD),
|
||||
("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", wt.DWORD), ("cntThreads", wt.DWORD),
|
||||
("th32ParentProcessID", wt.DWORD), ("pcPriClassBase", ctypes.c_long), ("dwFlags", wt.DWORD),
|
||||
("szExeFile", wt.WCHAR * 260)]
|
||||
|
||||
|
||||
_k32.Process32FirstW.argtypes = [wt.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
|
||||
_k32.Process32NextW.argtypes = [wt.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)]
|
||||
|
||||
|
||||
def _process_names() -> list[str]:
|
||||
snap = _k32.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS
|
||||
if snap == wt.HANDLE(-1).value:
|
||||
raise OSError("Cannot enumerate processes to check Commander PRO ownership")
|
||||
names: list[str] = []
|
||||
try:
|
||||
entry = _PROCESSENTRY32W()
|
||||
entry.dwSize = ctypes.sizeof(entry)
|
||||
ok = _k32.Process32FirstW(snap, ctypes.byref(entry))
|
||||
while ok:
|
||||
names.append(entry.szExeFile.lower())
|
||||
ok = _k32.Process32NextW(snap, ctypes.byref(entry))
|
||||
finally:
|
||||
_k32.CloseHandle(snap)
|
||||
return names
|
||||
|
||||
|
||||
def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> bool:
|
||||
"""True if iCUE (or, with `fan_tools`, FanControl) runs, or a running OpenRGB may drive the device.
|
||||
|
||||
Corsair controllers' replies don't say which request they answer, so sharing one with other
|
||||
software risks swapped replies. OpenRGB counts as released only when the named detector is
|
||||
disabled in both the app's and the Windows service's settings.
|
||||
"""
|
||||
names = _process_names()
|
||||
if any("icue" in n or "corsair" in n or (fan_tools and "fancontrol" in n) for n in names):
|
||||
return True
|
||||
if not any("openrgb" in n for n in names):
|
||||
return False
|
||||
configs = [os.path.join(os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"),
|
||||
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "OpenRGB",
|
||||
"service_config", "OpenRGB.json")]
|
||||
try:
|
||||
configs = [c for c in configs if os.path.exists(c)]
|
||||
if not configs:
|
||||
raise OSError("no OpenRGB settings found")
|
||||
for config in configs:
|
||||
with open(config, encoding="utf-8") as f:
|
||||
settings = json.load(f)
|
||||
if settings["Detectors"]["detectors"][openrgb_detector] is not False:
|
||||
log.warning("OpenRGB %s detector is enabled in %s", openrgb_detector, config)
|
||||
return True
|
||||
return False
|
||||
except (OSError, ValueError, KeyError, TypeError) as e:
|
||||
log.warning("Cannot verify OpenRGB has released %s: %s", openrgb_detector, e)
|
||||
return True
|
||||
|
||||
|
||||
_MEMORY_TYPES = {0x18: "DDR3", 0x1A: "DDR4", 0x1E: "LPDDR4", 0x22: "DDR5", 0x23: "LPDDR5"}
|
||||
|
||||
|
||||
def memory_modules() -> list[tuple[str, float]]:
|
||||
"""(type, GB) for each installed memory module, from the SMBIOS type 17 records."""
|
||||
rsmb = 0x52534D42
|
||||
size = _k32.GetSystemFirmwareTable(rsmb, 0, None, 0)
|
||||
if not size:
|
||||
return []
|
||||
buf = ctypes.create_string_buffer(size)
|
||||
if _k32.GetSystemFirmwareTable(rsmb, 0, buf, size) != size:
|
||||
return []
|
||||
length = struct.unpack_from("<I", buf.raw, 4)[0]
|
||||
data = buf.raw[8:8 + length]
|
||||
modules = []
|
||||
i = 0
|
||||
while i + 4 <= len(data):
|
||||
kind, hdr_len = data[i], data[i + 1]
|
||||
if hdr_len < 4 or kind == 127: # malformed / end-of-table
|
||||
break
|
||||
if kind == 17 and hdr_len >= 0x13:
|
||||
raw_size = struct.unpack_from("<H", data, i + 0x0C)[0]
|
||||
if raw_size == 0x7FFF and hdr_len >= 0x20:
|
||||
mb = struct.unpack_from("<I", data, i + 0x1C)[0] & 0x7FFFFFFF
|
||||
elif raw_size in (0, 0xFFFF):
|
||||
mb = 0
|
||||
else:
|
||||
mb = (raw_size & 0x7FFF) / 1024 if raw_size & 0x8000 else raw_size
|
||||
if mb:
|
||||
modules.append((_MEMORY_TYPES.get(data[i + 0x12], "DIMM"), mb / 1024))
|
||||
j = i + hdr_len # skip the string set, which ends with a double NUL
|
||||
while j + 1 < len(data) and (data[j] or data[j + 1]):
|
||||
j += 1
|
||||
i = j + 2
|
||||
return modules
|
||||
|
||||
|
||||
class CommanderPro:
|
||||
"""Commander PRO readings, with explicitly opted-in PWM control.
|
||||
|
||||
Uses the same status commands as liquidctl. Its replies don't say which request they
|
||||
answer, so it steps aside while iCUE (or any Corsair service) is running, rather than
|
||||
risk swapping replies with it.
|
||||
"""
|
||||
|
||||
VID, PID = 0x1B1C, 0x0C10
|
||||
CMD_FAN_MODES = 0x20
|
||||
CMD_FAN_RPM = 0x21
|
||||
PORTS = 6
|
||||
RECHECK = 30.0
|
||||
|
||||
def __init__(self):
|
||||
self.ch: HidChannel | None = None
|
||||
self._mutex: int | None = None
|
||||
self._lock = threading.RLock()
|
||||
self.controlled = False
|
||||
self.ports: list[int] = []
|
||||
self.rpm: dict[int, int] = {}
|
||||
self._next_check = 0.0
|
||||
self._note: str | None = None
|
||||
|
||||
def _say(self, note: str) -> None:
|
||||
if note != self._note:
|
||||
log.info("Commander PRO: %s", note)
|
||||
self._note = note
|
||||
|
||||
def _cmd(self, op: int, *args: int) -> bytes:
|
||||
ch = self.ch
|
||||
if ch is None:
|
||||
raise OSError("Commander PRO is not open")
|
||||
ch.drain()
|
||||
ch.send(bytes((op, *args)))
|
||||
r = ch.read(300)
|
||||
if not r or len(r) < 4 or r[1] != 0: # [report id, status, data...]
|
||||
raise OSError(f"no reply to command 0x{op:02X}")
|
||||
return r
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self.ch is not None:
|
||||
self.ch.close()
|
||||
self.ch = None
|
||||
if self._mutex is not None:
|
||||
_k32.CloseHandle(self._mutex)
|
||||
self._mutex = None
|
||||
|
||||
def _corsair_software_running(self) -> bool:
|
||||
return corsair_software_running("Corsair Commander Pro")
|
||||
|
||||
def _open(self) -> None:
|
||||
if self.ch is not None:
|
||||
return
|
||||
ctypes.set_last_error(0)
|
||||
mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdCommanderPro")
|
||||
err = ctypes.get_last_error()
|
||||
if not mutex or err == 183:
|
||||
if mutex:
|
||||
_k32.CloseHandle(mutex)
|
||||
raise OSError("Commander PRO is in use by another dashboard/sensor process")
|
||||
self._mutex = mutex
|
||||
try:
|
||||
paths = hid_device_paths(self.VID, self.PID)
|
||||
if len(paths) != 1:
|
||||
raise OSError(f"Expected one Commander PRO interface, found {len(paths)}")
|
||||
self.ch = HidChannel(paths[0], 63)
|
||||
modes = self._cmd(self.CMD_FAN_MODES)
|
||||
if len(modes) < 8:
|
||||
raise OSError("Incomplete Commander PRO fan modes reply")
|
||||
self.ports = [p for p in range(self.PORTS) if modes[2 + p] in (1, 2)]
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def set_duty(self, ports: tuple[int, ...], duty: int) -> dict[int, int]:
|
||||
"""Set only the selected one-based PWM ports; return fresh one-based RPMs."""
|
||||
if (not ports or len(set(ports)) != len(ports)
|
||||
or any(p not in range(1, 7) for p in ports) or not 0 <= duty <= 100):
|
||||
raise ValueError("Fan ports must be unique values 1-6 and duty must be 0-100")
|
||||
with self._lock:
|
||||
if self._corsair_software_running():
|
||||
self.close()
|
||||
raise OSError("Commander PRO busy: exit iCUE/FanControl, or disable OpenRGB's "
|
||||
"Corsair Commander Pro detector and restart OpenRGB")
|
||||
self._open()
|
||||
modes = self._cmd(self.CMD_FAN_MODES)
|
||||
if len(modes) < 8 or any(modes[p + 1] != 2 for p in ports):
|
||||
raise OSError("Every selected fan port must have a connected PWM fan")
|
||||
for p in ports:
|
||||
self._cmd(0x23, p - 1, duty)
|
||||
for p in self.ports:
|
||||
r = self._cmd(self.CMD_FAN_RPM, p)
|
||||
self.rpm[p] = (r[2] << 8) | r[3]
|
||||
return {p + 1: rpm for p, rpm in self.rpm.items()}
|
||||
|
||||
def read(self) -> list[int]:
|
||||
"""RPM of each connected fan (the last known values while iCUE has the device)."""
|
||||
with self._lock:
|
||||
if self.controlled:
|
||||
return list(self.rpm.values())
|
||||
return self._read()
|
||||
|
||||
def _read(self) -> list[int]:
|
||||
now = time.monotonic()
|
||||
if now >= self._next_check:
|
||||
self._next_check = now + self.RECHECK
|
||||
if self._corsair_software_running():
|
||||
self.close()
|
||||
self._say("iCUE is running, leaving the device to it")
|
||||
elif self.ch is None:
|
||||
try:
|
||||
self._open()
|
||||
self._say(f"reading {len(self.ports)} fans (ports {', '.join(str(p + 1) for p in self.ports)})")
|
||||
except Exception as e:
|
||||
self.close()
|
||||
self._say(f"unavailable ({e})")
|
||||
if self.ch is not None:
|
||||
try:
|
||||
for p in self.ports:
|
||||
r = self._cmd(self.CMD_FAN_RPM, p)
|
||||
self.rpm[p] = (r[2] << 8) | r[3]
|
||||
except Exception as e:
|
||||
self.close()
|
||||
self._say(f"lost ({e}), retrying in {self.RECHECK:.0f} s")
|
||||
return [self.rpm[p] for p in self.ports if p in self.rpm]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Disk:
|
||||
name: str
|
||||
kind: str # nvme, ssd, hdd, usb-hdd, usb-ssd, flash, virtual
|
||||
idle: float # W
|
||||
active: float # W when busy 100% of the time
|
||||
standby: float | None = None # W once a hard drive spins down
|
||||
last_io: float = 0.0
|
||||
|
||||
|
||||
class StoragePower:
|
||||
"""Drive power estimated from each drive's activity (% of time busy, from Windows)."""
|
||||
|
||||
IOCTL_STORAGE_QUERY_PROPERTY = 0x2D1400
|
||||
BUS_USB, BUS_NVME = 7, 17
|
||||
BUS_VIRTUAL = (14, 15, 16) # VHD, file-backed, Storage Spaces
|
||||
|
||||
def __init__(self, model: PowerModel):
|
||||
self.model = model
|
||||
self.idle_time = PdhArray(r"\PhysicalDisk(*)\% Idle Time")
|
||||
self.disks: dict[int, _Disk] = {}
|
||||
|
||||
def _query(self, h, property_id: int, extra: bytes, out_size: int) -> bytes | None:
|
||||
q = struct.pack("<II", property_id, 0) + extra
|
||||
inbuf = ctypes.create_string_buffer(q, max(12, len(q)))
|
||||
outbuf = ctypes.create_string_buffer(out_size)
|
||||
ret = wt.DWORD()
|
||||
if not _k32.DeviceIoControl(h, self.IOCTL_STORAGE_QUERY_PROPERTY, inbuf, len(inbuf), outbuf, out_size,
|
||||
ctypes.byref(ret), None):
|
||||
return None
|
||||
return outbuf.raw[:ret.value]
|
||||
|
||||
def _nvme_max_power(self, h) -> float | None:
|
||||
"""Max power of power state 0 from the drive's Identify Controller data."""
|
||||
# STORAGE_PROTOCOL_SPECIFIC_DATA: NVMe, Identify, CNS 1 (controller), data right after it, 4 KiB
|
||||
spec = struct.pack("<10I", 3, 1, 1, 0, 40, 4096, 0, 0, 0, 0)
|
||||
raw = self._query(h, 49, spec + bytes(4096), 8 + 40 + 4096) # StorageAdapterProtocolSpecificProperty
|
||||
if not raw or len(raw) < 8 + 40:
|
||||
return None
|
||||
off = 8 + struct.unpack_from("<I", raw, 8 + 16)[0]
|
||||
ident = raw[off:off + 4096]
|
||||
if len(ident) < 2048 + 32:
|
||||
return None
|
||||
mp, flags = struct.unpack_from("<H", ident, 2048)[0], ident[2048 + 3]
|
||||
watts = mp * (0.0001 if flags & 1 else 0.01)
|
||||
return watts if 0.5 <= watts <= 50 else None
|
||||
|
||||
def _probe(self, number: int) -> _Disk:
|
||||
m = self.model
|
||||
h = _k32.CreateFileW(f"\\\\.\\PhysicalDrive{number}", 0, 0x3, None, 3, 0, None)
|
||||
if h == wt.HANDLE(-1).value:
|
||||
return _Disk(f"disk {number}", "unknown", 1.0, 3.0)
|
||||
try:
|
||||
desc = self._query(h, 0, b"", 1024) or b"" # StorageDeviceProperty
|
||||
bus = struct.unpack_from("<I", desc, 28)[0] if len(desc) >= 32 else 0
|
||||
removable = len(desc) > 10 and desc[10] != 0
|
||||
name = f"disk {number}"
|
||||
if len(desc) >= 20:
|
||||
pid_off = struct.unpack_from("<I", desc, 16)[0]
|
||||
if 0 < pid_off < len(desc):
|
||||
name = desc[pid_off:].split(b"\0", 1)[0].decode(errors="replace").strip() or name
|
||||
seek = self._query(h, 7, b"", 12) # StorageDeviceSeekPenaltyProperty
|
||||
spinning = bool(seek[8]) if seek and len(seek) > 8 else None
|
||||
if bus in self.BUS_VIRTUAL:
|
||||
return _Disk(name, "virtual", 0.0, 0.0)
|
||||
if bus == self.BUS_NVME:
|
||||
mx = self._nvme_max_power(h) or 7.0
|
||||
return _Disk(f"{name} (max {mx:.1f} W)", "nvme", min(1.5, max(0.3, 0.15 * mx)), 0.8 * mx)
|
||||
if bus == self.BUS_USB:
|
||||
if removable:
|
||||
return _Disk(name, "flash", 0.1, 0.5)
|
||||
if spinning is False:
|
||||
return _Disk(name, "usb-ssd", 0.3, 2.0)
|
||||
return _Disk(name, "usb-hdd", 1.5, 2.5, standby=0.2) # bus-powered 2.5" drive
|
||||
if spinning:
|
||||
return _Disk(name, "hdd", 5.0, 7.5, standby=0.8)
|
||||
return _Disk(name, "ssd", 0.5, 3.0)
|
||||
finally:
|
||||
_k32.CloseHandle(h)
|
||||
|
||||
def read(self) -> list[tuple[str, float]]:
|
||||
now = time.monotonic()
|
||||
out = []
|
||||
for inst, idle_pct in self.idle_time.sample() or []:
|
||||
head = inst.split(" ", 1)[0]
|
||||
if not head.isdigit():
|
||||
continue # _Total
|
||||
number = int(head)
|
||||
disk = self.disks.get(number)
|
||||
if disk is None:
|
||||
disk = self.disks[number] = self._probe(number)
|
||||
disk.last_io = now
|
||||
log.info("Drive %d: %s [%s] %.1f-%.1f W", number, disk.name, disk.kind, disk.idle, disk.active)
|
||||
busy = min(1.0, max(0.0, 1.0 - idle_pct / 100.0))
|
||||
if busy > 0.002:
|
||||
disk.last_io = now
|
||||
if disk.standby is not None and now - disk.last_io > 60 * self.model.hdd_idle_minutes:
|
||||
watts = disk.standby
|
||||
else:
|
||||
watts = disk.idle + (disk.active - disk.idle) * busy
|
||||
out.append((disk.name, watts))
|
||||
return out
|
||||
|
||||
|
||||
class SystemPower:
|
||||
"""Everything that isn't the CPU package or the graphics card, in watts."""
|
||||
|
||||
def __init__(self, model: PowerModel | None = None):
|
||||
self.model = model or PowerModel()
|
||||
self.dimms = memory_modules()
|
||||
self.fans = CommanderPro()
|
||||
try:
|
||||
self.storage: StoragePower | None = StoragePower(self.model)
|
||||
except OSError as e:
|
||||
log.warning("Drive activity unavailable: %s", e)
|
||||
self.storage = None
|
||||
kinds = sorted({k for k, _ in self.dimms})
|
||||
log.info("Memory: %d module(s) %s, %.0f GB", len(self.dimms), "/".join(kinds),
|
||||
sum(gb for _, gb in self.dimms))
|
||||
|
||||
def read(self, cpu: Readings, gpu: Readings) -> PowerReadings:
|
||||
m = self.model
|
||||
parts: dict[str, float] = {"Motherboard & chipset": m.motherboard}
|
||||
if cpu.power is not None:
|
||||
parts["CPU regulator losses"] = cpu.power * (1.0 / m.cpu_vrm_efficiency - 1.0)
|
||||
if self.dimms:
|
||||
load = (cpu.load or 0.0) / 100.0
|
||||
w = 0.0
|
||||
for kind, _gb in self.dimms:
|
||||
idle, full = m.ddr4_dimm if kind in ("DDR4", "DDR3", "LPDDR4") else m.ddr5_dimm
|
||||
w += idle + (full - idle) * load
|
||||
parts[f"Memory ({len(self.dimms)} modules)"] = w
|
||||
if self.storage is not None:
|
||||
try:
|
||||
drives = self.storage.read()
|
||||
except Exception as e:
|
||||
log.debug("Drive activity failed: %s", e)
|
||||
drives = []
|
||||
for name, w in drives:
|
||||
parts[f"Drive: {name}"] = w
|
||||
rpms = self.fans.read()
|
||||
if rpms:
|
||||
parts[f"Case fans ({len(rpms)}, Commander PRO)"] = sum(
|
||||
m.fan_idle + m.fan_full * (r / m.fan_ref_rpm) ** 2.5 for r in rpms if r > 0)
|
||||
parts["Motherboard-header fans/pump (fixed)"] = m.board_fans
|
||||
parts["USB devices & RGB lighting (fixed)"] = m.usb_and_lighting
|
||||
return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=sum(parts.values()), parts=parts)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
cpu, gpu, system = CpuSensors(), GpuSensors(), SystemPower()
|
||||
for _ in range(3):
|
||||
time.sleep(1)
|
||||
c, g = cpu.read(), gpu.read()
|
||||
p = system.read(c, g)
|
||||
print("CPU", c)
|
||||
print("GPU", g)
|
||||
for name, w in p.parts.items():
|
||||
print(f" {w:6.1f} W {name}")
|
||||
fmt = lambda v: "--" if v is None else f"{v:.0f} W"
|
||||
print(f" CPU {fmt(p.cpu)} + GPU {fmt(p.gpu)} + other {fmt(p.other)} = total {fmt(p.total)}")
|
||||
print("CPU temp/power status:", cpu.status)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Telemetry service: reads every sensor once a second on one thread and shares the result.
|
||||
|
||||
The LCD, the lighting, the tray tooltip and the web UI all use these samples, so the hardware
|
||||
is polled once however many things are watching. (The fan worker keeps its own temperature
|
||||
reads on purpose: cooling must not depend on any other worker staying healthy.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
HISTORY_SECONDS = 600
|
||||
SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Sample:
|
||||
seq: int
|
||||
t: float # time.time()
|
||||
cpu: Readings = field(default_factory=Readings)
|
||||
gpu: Readings = field(default_factory=Readings)
|
||||
power: PowerReadings = field(default_factory=PowerReadings)
|
||||
vram: tuple[int, int] | None = None # (used, total) bytes
|
||||
|
||||
def row(self) -> tuple:
|
||||
return (round(self.t, 1), _r(self.cpu.temp), _r(self.gpu.temp), _r(self.cpu.load), _r(self.gpu.load),
|
||||
_r(self.power.cpu), _r(self.power.gpu), _r(self.power.other), _r(self.power.total),
|
||||
None if self.vram is None else self.vram[0])
|
||||
|
||||
|
||||
def _r(value: float | None, digits: int = 1) -> float | None:
|
||||
return None if value is None else round(value, digits)
|
||||
|
||||
|
||||
class Telemetry:
|
||||
def __init__(self, cpu, gpu, system, interval: float = 1.0):
|
||||
self.cpu, self.gpu, self.system = cpu, gpu, system
|
||||
self.interval = interval
|
||||
self._cond = threading.Condition()
|
||||
self._latest: Sample | None = None
|
||||
self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval))
|
||||
self._listeners: list[Callable[[Sample], None]] = []
|
||||
self._seq = 0
|
||||
|
||||
def subscribe(self, listener: Callable[[Sample], None]) -> None:
|
||||
self._listeners.append(listener)
|
||||
|
||||
def read(self) -> Sample:
|
||||
c, g = self.cpu.read(), self.gpu.read()
|
||||
p = self.system.read(c, g)
|
||||
self._seq += 1
|
||||
return Sample(self._seq, time.time(), c, g, p, self.gpu.memory())
|
||||
|
||||
def run(self, stop: threading.Event) -> None:
|
||||
while not stop.is_set():
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
sample = self.read()
|
||||
except Exception:
|
||||
log.exception("Sensor read failed; retrying")
|
||||
stop.wait(5)
|
||||
continue
|
||||
with self._cond:
|
||||
self._latest = sample
|
||||
self._history.append(sample.row())
|
||||
self._cond.notify_all()
|
||||
if sample.seq == 5: # once the counters have settled
|
||||
fmt = lambda v: "--" if v is None else f"{v:.0f}"
|
||||
p = sample.power
|
||||
log.info("Power: CPU %s + GPU %s + other %s = %s W; other = %s", fmt(p.cpu), fmt(p.gpu),
|
||||
fmt(p.other), fmt(p.total), ", ".join(f"{k} {v:.1f}" for k, v in p.parts.items()))
|
||||
for listener in self._listeners:
|
||||
try:
|
||||
listener(sample)
|
||||
except Exception:
|
||||
log.exception("Telemetry listener %r failed", listener)
|
||||
stop.wait(max(0.0, self.interval - (time.monotonic() - t0)))
|
||||
with self._cond:
|
||||
self._cond.notify_all()
|
||||
|
||||
@property
|
||||
def latest(self) -> Sample | None:
|
||||
with self._cond:
|
||||
return self._latest
|
||||
|
||||
def wait_newer(self, seq: int, timeout: float) -> Sample | None:
|
||||
"""The first sample after `seq`, or the latest one (possibly None) after `timeout`."""
|
||||
with self._cond:
|
||||
self._cond.wait_for(lambda: self._latest is not None and self._latest.seq > seq, timeout)
|
||||
return self._latest
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
s = self.latest
|
||||
if s is None:
|
||||
return {"seq": 0}
|
||||
return {
|
||||
"seq": s.seq, "t": s.t,
|
||||
"cpu": {"temp": _r(s.cpu.temp), "load": _r(s.cpu.load), "clock": _r(s.cpu.clock, 0), "power": _r(s.cpu.power)},
|
||||
"gpu": {"temp": _r(s.gpu.temp), "load": _r(s.gpu.load), "clock": _r(s.gpu.clock, 0), "power": _r(s.gpu.power),
|
||||
"vram_used": None if s.vram is None else s.vram[0],
|
||||
"vram_total": None if s.vram is None else s.vram[1]},
|
||||
"power": {"cpu": _r(s.power.cpu), "gpu": _r(s.power.gpu), "other": _r(s.power.other),
|
||||
"total": _r(s.power.total),
|
||||
"parts": {k: round(v, 1) for k, v in s.power.parts.items()}},
|
||||
"row": s.row(),
|
||||
}
|
||||
|
||||
def history(self) -> dict:
|
||||
with self._cond:
|
||||
rows = list(self._history)
|
||||
return {"series": SERIES, "rows": rows, "interval": self.interval}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Colours and thresholds shared by the LCD, the case/RAM lighting and the tray icon."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Theme:
|
||||
accent: tuple[int, int, int] = (232, 28, 44)
|
||||
cpu_temp_range: tuple[float, float] = (20.0, 100.0)
|
||||
gpu_temp_range: tuple[float, float] = (20.0, 90.0)
|
||||
psu_watts: float = 1000.0 # fills the power tank
|
||||
# Optional mirrored direction on the right; by default all gauges fill clockwise.
|
||||
mirror_gauge_direction: bool = False
|
||||
titles: tuple[str, str] = ("GPU", "CPU")
|
||||
# Gauges are green below *_warn, yellow from *_warn to *_hot, red above.
|
||||
temp_warn: float = 50.0 # deg C
|
||||
temp_hot: float = 80.0
|
||||
load_warn: float = 50.0 # percent
|
||||
load_hot: float = 80.0
|
||||
cool_color: tuple[int, int, int] = (38, 204, 72)
|
||||
warm_color: tuple[int, int, int] = (244, 192, 22)
|
||||
hot_color: tuple[int, int, int] = (232, 28, 44)
|
||||
# Power tank layers. Kept clear of the gauges' green/yellow/red, and checked to stay
|
||||
# distinguishable with colour-blindness against the dark glass.
|
||||
cpu_color: tuple[int, int, int] = (57, 135, 229) # blue
|
||||
gpu_color: tuple[int, int, int] = (25, 158, 112) # aqua
|
||||
other_color: tuple[int, int, int] = (217, 89, 38) # copper orange
|
||||
|
||||
def level_color(self, value: float, warn: float, hot: float) -> tuple[int, int, int]:
|
||||
if value < warn:
|
||||
return self.cool_color
|
||||
if value <= hot:
|
||||
return self.warm_color
|
||||
return self.hot_color
|
||||
+407
@@ -0,0 +1,407 @@
|
||||
"""Notification-area icon for The Kurgan.
|
||||
|
||||
The tooltip shows the power draw; the menu shows each capability's status and has
|
||||
"Open The Kurgan" (the web UI), "Start with Windows" and "Exit". Clicking the icon with the
|
||||
left button opens the web UI directly.
|
||||
|
||||
"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task (installed by
|
||||
setup.ps1) on or off. The task itself stays enabled, so it can still be started by hand,
|
||||
with admin rights and no UAC prompt: Start-ScheduledTask "The Kurgan"
|
||||
|
||||
The Kurgan usually runs elevated while Explorer doesn't, so Windows would drop Explorer's
|
||||
clicks on the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import logging
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
TASK_NAME = "The Kurgan"
|
||||
LEGACY_TASK_NAME = "TT LCD Dashboard" # until setup.ps1 re-registers the task
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- startup task
|
||||
|
||||
def _powershell(script: str) -> str:
|
||||
r = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script],
|
||||
capture_output=True, text=True, timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
if r.returncode != 0:
|
||||
lines = [ln.strip() for ln in (r.stderr or r.stdout).splitlines() if ln.strip()]
|
||||
raise RuntimeError(lines[0] if lines else f"PowerShell exited with code {r.returncode}")
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
_QUERY = """
|
||||
$t = Get-ScheduledTask -TaskName '%TASK%' -ErrorAction SilentlyContinue
|
||||
if (-not $t) { 'missing' }
|
||||
elseif ($t.State -ne 'Disabled' -and @($t.Triggers | Where-Object {
|
||||
$_.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger' -and $_.Enabled }).Count) { 'on' }
|
||||
else { 'off' }
|
||||
"""
|
||||
|
||||
_SET = """
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$t = Get-ScheduledTask -TaskName '%TASK%'
|
||||
$n = 0
|
||||
foreach ($tr in $t.Triggers) {
|
||||
if ($tr.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger') { $tr.Enabled = %ON%; $n++ }
|
||||
}
|
||||
if (-not $n) { throw 'The startup task has no logon trigger; run setup.ps1 again.' }
|
||||
Set-ScheduledTask -InputObject $t | Out-Null
|
||||
if (%ON% -and $t.State -eq 'Disabled') { Enable-ScheduledTask -TaskName '%TASK%' | Out-Null }
|
||||
"""
|
||||
|
||||
|
||||
def _task_state(name: str) -> str:
|
||||
return _powershell(_QUERY.replace("%TASK%", name))
|
||||
|
||||
|
||||
def startup_task() -> str | None:
|
||||
"""The installed startup task's name, preferring The Kurgan's own."""
|
||||
for name in (TASK_NAME, LEGACY_TASK_NAME):
|
||||
if _task_state(name) != "missing":
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def autostart_enabled() -> bool | None:
|
||||
"""True/False: the startup task does/doesn't run at logon. None: it isn't installed."""
|
||||
name = startup_task()
|
||||
return None if name is None else _task_state(name) == "on"
|
||||
|
||||
|
||||
def set_autostart(on: bool) -> None:
|
||||
name = startup_task()
|
||||
if name is None:
|
||||
raise RuntimeError("The startup task isn't installed; run setup.ps1.")
|
||||
_powershell(_SET.replace("%TASK%", name).replace("%ON%", "$true" if on else "$false"))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- icon image
|
||||
|
||||
def make_icon(path: str, layers: list[tuple[int, int, int]]) -> str:
|
||||
"""Draw a small version of the dashboard's power tank and save it as a .ico file.
|
||||
|
||||
layers: colours from the bottom up (other, CPU, GPU).
|
||||
"""
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
s = 256
|
||||
img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(img)
|
||||
chrome, dark = (206, 206, 212, 255), (20, 20, 24, 255)
|
||||
x0, x1 = 52, 204 # glass
|
||||
d.rectangle([x0, 30, x1, 226], fill=dark)
|
||||
y = 226
|
||||
for h, c in zip((50, 42, 56), layers): # bottom up
|
||||
d.rectangle([x0, y - h, x1, y], fill=c + (255,))
|
||||
y -= h
|
||||
d.rectangle([x0, y - 3, x1, y + 3], fill=dark)
|
||||
hl = Image.new("RGBA", (s, s), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(hl).rectangle([x0 + 22, 36, x0 + 40, 222], fill=(255, 255, 255, 70))
|
||||
img.alpha_composite(hl)
|
||||
d = ImageDraw.Draw(img)
|
||||
for y0, y1 in ((4, 40), (216, 252)): # end caps
|
||||
d.rounded_rectangle([28, y0, 228, y1], radius=12, fill=chrome)
|
||||
d.rectangle([28, (y0 + y1) // 2 - 2, 228, (y0 + y1) // 2 + 2], fill=(120, 120, 128, 255))
|
||||
img.save(path, sizes=[(16, 16), (20, 20), (24, 24), (32, 32), (40, 40), (48, 48), (64, 64)])
|
||||
return path
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- Win32
|
||||
|
||||
_u32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
_shell32 = ctypes.WinDLL("shell32", use_last_error=True)
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
LRESULT = ctypes.c_ssize_t
|
||||
WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM)
|
||||
|
||||
WM_NULL, WM_DESTROY, WM_CLOSE, WM_TIMER = 0x0000, 0x0002, 0x0010, 0x0113
|
||||
WM_LBUTTONUP, WM_RBUTTONUP = 0x0202, 0x0205
|
||||
WM_TRAY = 0x8000 + 1 # WM_APP + 1: Explorer -> us, mouse events on the icon
|
||||
WM_TRAY_TIP = 0x8000 + 2 # WM_APP + 2: main thread -> us, tooltip changed
|
||||
NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2
|
||||
NIF_MESSAGE, NIF_ICON, NIF_TIP = 0x1, 0x2, 0x4
|
||||
MF_STRING, MF_GRAYED, MF_CHECKED, MF_SEPARATOR = 0x0, 0x1, 0x8, 0x800
|
||||
TPM_RIGHTBUTTON, TPM_NONOTIFY, TPM_RETURNCMD = 0x2, 0x80, 0x100
|
||||
MB_ICONWARNING, MB_SETFOREGROUND = 0x30, 0x10000
|
||||
MSGFLT_ALLOW = 1
|
||||
RETRY_TIMER = 1
|
||||
|
||||
|
||||
class WNDCLASSEXW(ctypes.Structure):
|
||||
_fields_ = [("cbSize", wt.UINT), ("style", wt.UINT), ("lpfnWndProc", WNDPROC), ("cbClsExtra", ctypes.c_int),
|
||||
("cbWndExtra", ctypes.c_int), ("hInstance", wt.HINSTANCE), ("hIcon", wt.HICON),
|
||||
("hCursor", wt.HANDLE), ("hbrBackground", wt.HBRUSH), ("lpszMenuName", wt.LPCWSTR),
|
||||
("lpszClassName", wt.LPCWSTR), ("hIconSm", wt.HICON)]
|
||||
|
||||
|
||||
class NOTIFYICONDATAW(ctypes.Structure):
|
||||
_fields_ = [("cbSize", wt.DWORD), ("hWnd", wt.HWND), ("uID", wt.UINT), ("uFlags", wt.UINT),
|
||||
("uCallbackMessage", wt.UINT), ("hIcon", wt.HICON), ("szTip", wt.WCHAR * 128),
|
||||
("dwState", wt.DWORD), ("dwStateMask", wt.DWORD), ("szInfo", wt.WCHAR * 256),
|
||||
("uVersion", wt.UINT), ("szInfoTitle", wt.WCHAR * 64), ("dwInfoFlags", wt.DWORD),
|
||||
("guidItem", ctypes.c_byte * 16), ("hBalloonIcon", wt.HICON)]
|
||||
|
||||
|
||||
_u32.RegisterClassExW.argtypes = [ctypes.POINTER(WNDCLASSEXW)]
|
||||
_u32.RegisterClassExW.restype = wt.ATOM
|
||||
_u32.CreateWindowExW.argtypes = [wt.DWORD, wt.LPCWSTR, wt.LPCWSTR, wt.DWORD, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, wt.HWND, wt.HMENU, wt.HINSTANCE, wt.LPVOID]
|
||||
_u32.CreateWindowExW.restype = wt.HWND
|
||||
_u32.DefWindowProcW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
|
||||
_u32.DefWindowProcW.restype = LRESULT
|
||||
_u32.GetMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT]
|
||||
_u32.GetMessageW.restype = wt.BOOL
|
||||
_u32.TranslateMessage.argtypes = [ctypes.POINTER(wt.MSG)]
|
||||
_u32.DispatchMessageW.argtypes = [ctypes.POINTER(wt.MSG)]
|
||||
_u32.DispatchMessageW.restype = LRESULT
|
||||
_u32.PostMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
|
||||
_u32.PostMessageW.restype = wt.BOOL
|
||||
_u32.PostQuitMessage.argtypes = [ctypes.c_int]
|
||||
_u32.DestroyWindow.argtypes = [wt.HWND]
|
||||
_u32.RegisterWindowMessageW.argtypes = [wt.LPCWSTR]
|
||||
_u32.RegisterWindowMessageW.restype = wt.UINT
|
||||
_u32.ChangeWindowMessageFilterEx.argtypes = [wt.HWND, wt.UINT, wt.DWORD, wt.LPVOID]
|
||||
_u32.ChangeWindowMessageFilterEx.restype = wt.BOOL
|
||||
_u32.LoadImageW.argtypes = [wt.HINSTANCE, wt.LPCWSTR, wt.UINT, ctypes.c_int, ctypes.c_int, wt.UINT]
|
||||
_u32.LoadImageW.restype = wt.HANDLE
|
||||
_u32.DestroyIcon.argtypes = [wt.HICON]
|
||||
_u32.CreatePopupMenu.restype = wt.HMENU
|
||||
_u32.AppendMenuW.argtypes = [wt.HMENU, wt.UINT, ctypes.c_size_t, wt.LPCWSTR]
|
||||
_u32.TrackPopupMenu.argtypes = [wt.HMENU, wt.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, wt.HWND, wt.LPVOID]
|
||||
_u32.TrackPopupMenu.restype = ctypes.c_int
|
||||
_u32.DestroyMenu.argtypes = [wt.HMENU]
|
||||
_u32.GetCursorPos.argtypes = [ctypes.POINTER(wt.POINT)]
|
||||
_u32.SetForegroundWindow.argtypes = [wt.HWND]
|
||||
_u32.SetTimer.argtypes = [wt.HWND, ctypes.c_size_t, wt.UINT, wt.LPVOID]
|
||||
_u32.SetTimer.restype = ctypes.c_size_t
|
||||
_u32.KillTimer.argtypes = [wt.HWND, ctypes.c_size_t]
|
||||
_u32.MessageBoxW.argtypes = [wt.HWND, wt.LPCWSTR, wt.LPCWSTR, wt.UINT]
|
||||
_shell32.Shell_NotifyIconW.argtypes = [wt.DWORD, ctypes.POINTER(NOTIFYICONDATAW)]
|
||||
_shell32.Shell_NotifyIconW.restype = wt.BOOL
|
||||
_k32.GetModuleHandleW.argtypes = [wt.LPCWSTR]
|
||||
_k32.GetModuleHandleW.restype = wt.HMODULE
|
||||
|
||||
|
||||
def _is_admin() -> bool:
|
||||
try:
|
||||
return bool(_shell32.IsUserAnAdmin())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class TrayIcon:
|
||||
"""Notification-area icon on its own thread.
|
||||
|
||||
status_lines() is called when the menu opens; on_open/on_exit are called from the tray thread."""
|
||||
|
||||
CLASS_NAME = "KurganTray"
|
||||
ID_OPEN, ID_AUTOSTART, ID_EXIT = 1, 2, 3
|
||||
|
||||
def __init__(self, title: str, icon_path: str, on_exit, on_open=None, status_lines=None):
|
||||
self.title = title
|
||||
self.icon_path = icon_path
|
||||
self.on_exit = on_exit
|
||||
self.on_open = on_open
|
||||
self.status_lines = status_lines or (lambda: [])
|
||||
self._tip = title
|
||||
self._hwnd = None
|
||||
self._hicon = None
|
||||
self._shown = False
|
||||
self._autostart: bool | None = None
|
||||
self._autostart_known = False
|
||||
self._msg_taskbar = _u32.RegisterWindowMessageW("TaskbarCreated")
|
||||
self._wndproc = WNDPROC(self._proc) # keep a reference: Windows calls it
|
||||
self._thread = threading.Thread(target=self._run, name="tray", daemon=True)
|
||||
|
||||
# -- called from other threads
|
||||
|
||||
def start(self) -> None:
|
||||
self._thread.start()
|
||||
threading.Thread(target=self._refresh_autostart, name="tray-autostart", daemon=True).start()
|
||||
|
||||
def set_tooltip(self, text: str) -> None:
|
||||
text = text[:127]
|
||||
if text != self._tip:
|
||||
self._tip = text
|
||||
if self._hwnd:
|
||||
_u32.PostMessageW(self._hwnd, WM_TRAY_TIP, 0, 0)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._hwnd:
|
||||
_u32.PostMessageW(self._hwnd, WM_CLOSE, 0, 0)
|
||||
self._thread.join(timeout=3)
|
||||
|
||||
# -- tray thread
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
try:
|
||||
_u32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # per-monitor v2: crisp menu and icon
|
||||
except Exception:
|
||||
pass
|
||||
hinst = _k32.GetModuleHandleW(None)
|
||||
wc = WNDCLASSEXW()
|
||||
wc.cbSize = ctypes.sizeof(wc)
|
||||
wc.lpfnWndProc = self._wndproc
|
||||
wc.hInstance = hinst
|
||||
wc.lpszClassName = self.CLASS_NAME
|
||||
_u32.RegisterClassExW(ctypes.byref(wc)) # fails harmlessly if already registered
|
||||
# A hidden top-level window: message-only windows miss the TaskbarCreated broadcast.
|
||||
hwnd = _u32.CreateWindowExW(0, self.CLASS_NAME, self.title, 0, 0, 0, 0, 0, None, None, hinst, None)
|
||||
if not hwnd:
|
||||
raise OSError(f"CreateWindowEx failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
||||
for msg in (WM_TRAY, self._msg_taskbar):
|
||||
_u32.ChangeWindowMessageFilterEx(hwnd, msg, MSGFLT_ALLOW, None)
|
||||
size = _u32.GetSystemMetrics(49) # SM_CXSMICON
|
||||
self._hicon = _u32.LoadImageW(None, self.icon_path, 1, size, size, 0x10) # IMAGE_ICON, LR_LOADFROMFILE
|
||||
self._hwnd = hwnd
|
||||
self._add()
|
||||
msg = wt.MSG()
|
||||
while _u32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
|
||||
_u32.TranslateMessage(ctypes.byref(msg))
|
||||
_u32.DispatchMessageW(ctypes.byref(msg))
|
||||
except Exception:
|
||||
log.exception("Tray icon failed")
|
||||
finally:
|
||||
if self._hicon:
|
||||
_u32.DestroyIcon(self._hicon)
|
||||
self._hwnd = None
|
||||
|
||||
def _notify(self, op: int) -> bool:
|
||||
nid = NOTIFYICONDATAW()
|
||||
nid.cbSize = ctypes.sizeof(nid)
|
||||
nid.hWnd = self._hwnd
|
||||
nid.uID = 1
|
||||
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP
|
||||
nid.uCallbackMessage = WM_TRAY
|
||||
nid.hIcon = self._hicon
|
||||
nid.szTip = self._tip
|
||||
return bool(_shell32.Shell_NotifyIconW(op, ctypes.byref(nid)))
|
||||
|
||||
def _add(self) -> None:
|
||||
"""Add the icon; at logon the taskbar may not exist yet, so keep retrying."""
|
||||
self._shown = self._notify(NIM_ADD) or self._notify(NIM_MODIFY)
|
||||
if self._shown:
|
||||
_u32.KillTimer(self._hwnd, RETRY_TIMER)
|
||||
log.info("Tray icon shown")
|
||||
else:
|
||||
_u32.SetTimer(self._hwnd, RETRY_TIMER, 5000, None)
|
||||
|
||||
def _proc(self, hwnd, msg, wparam, lparam):
|
||||
try:
|
||||
if msg == WM_TRAY:
|
||||
event = lparam & 0xFFFF
|
||||
if event == WM_LBUTTONUP and self.on_open is not None:
|
||||
self.on_open()
|
||||
elif event in (WM_LBUTTONUP, WM_RBUTTONUP):
|
||||
self._menu()
|
||||
return 0
|
||||
if msg == WM_TRAY_TIP:
|
||||
if self._shown:
|
||||
self._notify(NIM_MODIFY)
|
||||
return 0
|
||||
if msg == self._msg_taskbar or (msg == WM_TIMER and wparam == RETRY_TIMER):
|
||||
self._add() # Explorer restarted (or the taskbar wasn't up yet)
|
||||
return 0
|
||||
if msg == WM_CLOSE:
|
||||
self._notify(NIM_DELETE)
|
||||
_u32.DestroyWindow(hwnd)
|
||||
return 0
|
||||
if msg == WM_DESTROY:
|
||||
_u32.PostQuitMessage(0)
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("Tray icon message %#x failed", msg)
|
||||
return _u32.DefWindowProcW(hwnd, msg, wparam, lparam)
|
||||
|
||||
def _menu(self) -> None:
|
||||
cmd = 0
|
||||
m = _u32.CreatePopupMenu()
|
||||
try:
|
||||
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, self.title)
|
||||
try:
|
||||
lines = list(self.status_lines())
|
||||
except Exception:
|
||||
log.exception("Tray status failed")
|
||||
lines = []
|
||||
for line in lines:
|
||||
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, line[:120])
|
||||
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
|
||||
if self.on_open is not None:
|
||||
_u32.AppendMenuW(m, MF_STRING, self.ID_OPEN, f"Open {self.title}")
|
||||
if not self._autostart_known:
|
||||
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART, "Start with Windows (checking...)")
|
||||
elif self._autostart is None:
|
||||
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART,
|
||||
"Start with Windows (run setup.ps1 first)")
|
||||
else:
|
||||
_u32.AppendMenuW(m, MF_STRING | (MF_CHECKED if self._autostart else 0), self.ID_AUTOSTART,
|
||||
"Start with Windows")
|
||||
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
|
||||
_u32.AppendMenuW(m, MF_STRING, self.ID_EXIT, "Exit")
|
||||
pt = wt.POINT()
|
||||
_u32.GetCursorPos(ctypes.byref(pt))
|
||||
_u32.SetForegroundWindow(self._hwnd) # otherwise the menu doesn't close when clicking elsewhere
|
||||
cmd = _u32.TrackPopupMenu(m, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, pt.x, pt.y, 0,
|
||||
self._hwnd, None)
|
||||
_u32.PostMessageW(self._hwnd, WM_NULL, 0, 0)
|
||||
finally:
|
||||
_u32.DestroyMenu(m)
|
||||
if cmd == self.ID_EXIT:
|
||||
log.info("Exit chosen from the tray menu")
|
||||
self.on_exit()
|
||||
elif cmd == self.ID_OPEN:
|
||||
self.on_open()
|
||||
elif cmd == self.ID_AUTOSTART:
|
||||
self._toggle_autostart()
|
||||
|
||||
def _refresh_autostart(self) -> None:
|
||||
try:
|
||||
self._autostart = autostart_enabled()
|
||||
except Exception as e:
|
||||
log.warning("Couldn't read the startup task: %s", e)
|
||||
self._autostart = None
|
||||
self._autostart_known = True
|
||||
|
||||
def _toggle_autostart(self) -> None:
|
||||
want = not self._autostart
|
||||
try:
|
||||
set_autostart(want)
|
||||
log.info("Start with Windows turned %s", "on" if want else "off")
|
||||
except Exception as e:
|
||||
log.warning("Couldn't change Start with Windows: %s", e)
|
||||
hint = "" if _is_admin() else (
|
||||
"\n\nChanging this needs admin rights. The Kurgan has them when its startup task "
|
||||
"starts it (Start-ScheduledTask \"The Kurgan\").")
|
||||
_u32.MessageBoxW(self._hwnd, f"Couldn't turn Start with Windows {'on' if want else 'off'}.\n\n{e}{hint}",
|
||||
self.title, MB_ICONWARNING | MB_SETFOREGROUND)
|
||||
self._refresh_autostart() # show what the task really says now
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Quick check: show the icon for 20 s with a test tooltip.
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
print("Start with Windows:", autostart_enabled())
|
||||
path = make_icon(os.path.join(tempfile.gettempdir(), "kurgan_tray_test.ico"),
|
||||
[(217, 89, 38), (57, 135, 229), (25, 158, 112)])
|
||||
done = threading.Event()
|
||||
tray = TrayIcon("The Kurgan (test)", path, on_exit=done.set, status_lines=lambda: ["Test run"])
|
||||
tray.start()
|
||||
for i in range(20):
|
||||
tray.set_tooltip(f"The Kurgan (test)\n{i} s")
|
||||
if done.wait(1):
|
||||
break
|
||||
tray.close()
|
||||
@@ -0,0 +1 @@
|
||||
"""Web: the control UI and its JSON API, on 127.0.0.1 only."""
|
||||
@@ -0,0 +1,284 @@
|
||||
"""The LLM servers' addresses on The Kurgan's web server: /strata/... and /llama/...
|
||||
|
||||
http://127.0.0.1:8080/strata/v1 OpenAI-compatible base URL for Strata
|
||||
http://127.0.0.1:8080/llama/v1 ... for llama.cpp (no API key needed; any key is accepted)
|
||||
http://127.0.0.1:8080/strata/ each server's own chat page (and everything else it serves)
|
||||
http://127.0.0.1:8080/llama/
|
||||
|
||||
A request starts its server if it isn't running (see AiService.claim, which also stops the other
|
||||
server once that one is idle) and the reply is streamed back as it is generated. A client that
|
||||
hangs up (a timeout, or the user cancelling) is noticed within a second, even while it is still
|
||||
waiting: its place is given up and the connection to the server closed, which stops the work on
|
||||
it. The log then says how long the client waited and at what stage. GET .../v1/models is
|
||||
answered here while a server is stopped, so a client listing the models of both doesn't make
|
||||
them swap.
|
||||
|
||||
Security: the web server's Host check applies (DNS rebinding). A request carrying an Origin
|
||||
header other than this server's comes from another site's page and is refused, as is anything
|
||||
else a browser marks cross-site except opening a page. Pages of this server (the chat pages) are
|
||||
let through with the Origin removed, so each server treats them like any local client.
|
||||
llama-server keeps its API key on its own port, and this proxy supplies it, so neither server
|
||||
asks clients here for a key.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import select
|
||||
import socket
|
||||
import time
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
ROUTE = re.compile(r"^/(strata|llama)(/[^?#]*)?(\?.*)?$")
|
||||
MAX_BODY = 64 * 1024 * 1024 # images and very long prompts are big, but not this big
|
||||
CONNECT_TIMEOUT = 10.0
|
||||
READ_TIMEOUT = 1800.0 # between bytes: a model load plus a long prompt can take minutes
|
||||
REQUEST_SKIP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
|
||||
"transfer-encoding", "upgrade", "host", "content-length", "origin", "expect"}
|
||||
RESPONSE_SKIP = {"connection", "keep-alive", "proxy-authenticate", "te", "trailer", "transfer-encoding",
|
||||
"upgrade", "server", "date"}
|
||||
|
||||
|
||||
class BodyError(Exception):
|
||||
def __init__(self, message: str, status: int):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
def match(path: str) -> tuple[str, str | None] | None:
|
||||
"""("llama", "/v1/models?x") for "/llama/v1/models?x"; ("llama", None) for "/llama"; None otherwise."""
|
||||
m = ROUTE.match(path)
|
||||
if m is None:
|
||||
return None
|
||||
rest = m[2]
|
||||
return m[1], None if rest is None else rest + (m[3] or "")
|
||||
|
||||
|
||||
def _error(handler, status: int, message: str) -> None:
|
||||
body = json.dumps({"error": {"message": message, "type": "kurgan"}}).encode()
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json")
|
||||
handler.send_header("Content-Length", str(len(body)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Connection", "close")
|
||||
handler.end_headers()
|
||||
handler.close_connection = True
|
||||
if handler.command != "HEAD":
|
||||
handler.wfile.write(body)
|
||||
|
||||
|
||||
def _read_body(handler) -> bytes | None:
|
||||
"""The request body (Content-Length or chunked), None if there is none."""
|
||||
if handler.headers.get("Transfer-Encoding", "").lower() == "chunked":
|
||||
parts, total = [], 0
|
||||
while True:
|
||||
line = handler.rfile.readline(1024)
|
||||
try:
|
||||
size = int(line.split(b";")[0].strip(), 16)
|
||||
except ValueError:
|
||||
raise BodyError("malformed chunked body", 400) from None
|
||||
if size == 0:
|
||||
while handler.rfile.readline(1024) not in (b"\r\n", b"\n", b""): # trailers
|
||||
pass
|
||||
return b"".join(parts)
|
||||
total += size
|
||||
if total > MAX_BODY:
|
||||
raise BodyError("request body too large", 413)
|
||||
parts.append(handler.rfile.read(size))
|
||||
handler.rfile.readline(8)
|
||||
length = handler.headers.get("Content-Length")
|
||||
if length is None:
|
||||
return None
|
||||
try:
|
||||
length = int(length)
|
||||
except ValueError:
|
||||
raise BodyError("bad Content-Length", 400) from None
|
||||
if length < 0:
|
||||
raise BodyError("bad Content-Length", 400)
|
||||
if length > MAX_BODY:
|
||||
remaining = min(length, 1024 * 1024) # read a little so the client sees the answer; beyond that, give up
|
||||
while remaining > 0:
|
||||
chunk = handler.rfile.read(min(remaining, 65536))
|
||||
if not chunk:
|
||||
break
|
||||
remaining -= len(chunk)
|
||||
raise BodyError("request body too large", 413)
|
||||
return handler.rfile.read(length)
|
||||
|
||||
|
||||
def _models(handler, backend, rest: str) -> None:
|
||||
"""OpenAI's model list, without starting the server."""
|
||||
path = rest.split("?", 1)[0].rstrip("/")
|
||||
models = [{"id": m, "object": "model", "created": 0, "owned_by": backend.key} for m in backend.model_ids()]
|
||||
if path == "/v1/models":
|
||||
data = {"object": "list", "data": models}
|
||||
else:
|
||||
wanted = path[len("/v1/models/"):]
|
||||
data = next((m for m in models if m["id"] == wanted), None)
|
||||
if data is None:
|
||||
_error(handler, 404, f"model {wanted!r} not found")
|
||||
return
|
||||
body = json.dumps(data).encode()
|
||||
handler.send_response(200)
|
||||
handler.send_header("Content-Type", "application/json")
|
||||
handler.send_header("Content-Length", str(len(body)))
|
||||
handler.send_header("Connection", "close")
|
||||
handler.end_headers()
|
||||
handler.close_connection = True
|
||||
handler.wfile.write(body)
|
||||
|
||||
|
||||
def _location(value: str, backend) -> str:
|
||||
"""Map a redirect from the server's own address onto its path here."""
|
||||
internal = f"http://127.0.0.1:{backend.port}"
|
||||
if value.startswith(internal):
|
||||
value = value[len(internal):] or "/"
|
||||
if not value.startswith("/"):
|
||||
return value
|
||||
if backend.prefix and value.startswith(backend.prefix):
|
||||
value = value[len(backend.prefix):] or "/"
|
||||
return f"/{backend.key}{value}"
|
||||
|
||||
|
||||
class ClientGone(Exception):
|
||||
"""The client closed its connection (it timed out or was cancelled); args[0] says when."""
|
||||
|
||||
|
||||
def client_gone(handler) -> bool:
|
||||
"""True once the client has closed its connection. The request has been read in full by
|
||||
then, so a readable socket with nothing to read means the client hung up."""
|
||||
sock = handler.connection
|
||||
try:
|
||||
readable, _, _ = select.select([sock], [], [], 0)
|
||||
return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
|
||||
except (OSError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def handle(handler, ai, hosts: set[str], origins: set[str]) -> None:
|
||||
"""Serve one request for /strata/... or /llama/... (handler is a BaseHTTPRequestHandler)."""
|
||||
started = time.monotonic()
|
||||
try:
|
||||
_serve(handler, ai, hosts, origins, started)
|
||||
except (ClientGone, ConnectionError) as e:
|
||||
handler.close_connection = True
|
||||
when = e.args[0] if isinstance(e, ClientGone) else "before its answer was sent"
|
||||
log.info("%s %s: the client gave up after %.0f s, %s", handler.command, handler.path,
|
||||
time.monotonic() - started, when)
|
||||
|
||||
|
||||
def _serve(handler, ai, hosts: set[str], origins: set[str], started: float) -> None:
|
||||
key, rest = match(handler.path)
|
||||
try:
|
||||
body = _read_body(handler) # before any answer: unread data would reset the connection on Windows
|
||||
except BodyError as e:
|
||||
_error(handler, e.status, str(e))
|
||||
return
|
||||
if handler.headers.get("Host") not in hosts:
|
||||
_error(handler, 403, "forbidden host")
|
||||
return
|
||||
origin = handler.headers.get("Origin")
|
||||
if origin is not None and origin not in origins:
|
||||
_error(handler, 403, f"web pages of {origin} may not use The Kurgan's AI servers")
|
||||
return
|
||||
# An <img> or <script> on another site's page sends no Origin but could still make the servers
|
||||
# swap; browsers mark it cross-site. Following a link (a top-level page load) is fine.
|
||||
if handler.headers.get("Sec-Fetch-Site") == "cross-site" and handler.headers.get("Sec-Fetch-Dest") != "document":
|
||||
_error(handler, 403, "other sites' pages may not use The Kurgan's AI servers")
|
||||
return
|
||||
if rest is None: # /llama -> /llama/, so the chat page's relative links resolve under it
|
||||
handler.send_response(308)
|
||||
handler.send_header("Location", f"/{key}/")
|
||||
handler.send_header("Content-Length", "0")
|
||||
handler.end_headers()
|
||||
return
|
||||
if ai is None:
|
||||
_error(handler, 503, "AI management is off for this run of The Kurgan (--no-ai)")
|
||||
return
|
||||
path = rest.split("?", 1)[0].rstrip("/")
|
||||
if handler.command == "GET" and (path == "/v1/models" or path.startswith("/v1/models/")) and not ai.running(key):
|
||||
_models(handler, ai.slots[key].backend, rest)
|
||||
return
|
||||
|
||||
from kurgan.ai.service import CLIENT_GONE, RouteError
|
||||
|
||||
try:
|
||||
# A client that leaves while waiting (for the other server to finish, or for this one to
|
||||
# start) releases its place, so an abandoned request never makes the servers swap.
|
||||
backend = ai.claim(key, gone=lambda: client_gone(handler))
|
||||
except RouteError as e:
|
||||
if e.status == CLIENT_GONE:
|
||||
raise ClientGone(str(e)) from None
|
||||
log.warning("%s %s: %s", handler.command, handler.path, e)
|
||||
_error(handler, e.status, str(e))
|
||||
return
|
||||
try:
|
||||
status = _relay(handler, backend, rest, body)
|
||||
finally:
|
||||
ai.release(key)
|
||||
if handler.command != "GET" or status >= 400:
|
||||
log.info("%s %s -> %s in %.1f s", handler.command, handler.path, status, time.monotonic() - started)
|
||||
|
||||
|
||||
def _await_reply(handler, upstream: socket.socket, backend) -> None:
|
||||
"""Wait for the server's reply to start: a request can sit in its queue, or its prompt be read,
|
||||
for minutes, and a reply that isn't streamed arrives all at once at the end. If the client
|
||||
hangs up meanwhile, give up: closing the connection tells the server to drop the request."""
|
||||
deadline = time.monotonic() + READ_TIMEOUT
|
||||
while not select.select([upstream], [], [], 0.5)[0]:
|
||||
if client_gone(handler):
|
||||
raise ClientGone(f"before {backend.label} started its reply")
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(f"no reply within {READ_TIMEOUT:.0f} s")
|
||||
|
||||
|
||||
def _relay(handler, backend, rest: str, body: bytes | None) -> int:
|
||||
extra = backend.proxy_headers() if hasattr(backend, "proxy_headers") else {}
|
||||
skip = REQUEST_SKIP | {k.lower() for k in extra}
|
||||
headers = {k: v for k, v in handler.headers.items() if k.lower() not in skip}
|
||||
headers.update(extra)
|
||||
headers["Host"] = f"127.0.0.1:{backend.port}"
|
||||
if body is not None:
|
||||
headers["Content-Length"] = str(len(body))
|
||||
connection = http.client.HTTPConnection("127.0.0.1", backend.port, timeout=CONNECT_TIMEOUT)
|
||||
try:
|
||||
try:
|
||||
connection.connect()
|
||||
connection.sock.settimeout(READ_TIMEOUT)
|
||||
connection.request(handler.command, backend.prefix + rest, body=body, headers=headers)
|
||||
_await_reply(handler, connection.sock, backend)
|
||||
response = connection.getresponse()
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
_error(handler, 502, f"{backend.label} isn't answering: {e}")
|
||||
return 502
|
||||
handler.send_response(response.status, response.reason)
|
||||
for name, value in response.getheaders():
|
||||
if name.lower() in RESPONSE_SKIP:
|
||||
continue
|
||||
handler.send_header(name, _location(value, backend) if name.lower() == "location" else value)
|
||||
handler.send_header("Connection", "close") # HTTP/1.0: the end of the stream ends the reply
|
||||
handler.end_headers()
|
||||
handler.close_connection = True
|
||||
if handler.command == "HEAD":
|
||||
return response.status
|
||||
sent = 0
|
||||
while True:
|
||||
try:
|
||||
chunk = response.read1(65536)
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
log.warning("%s stopped answering mid-reply: %s", backend.label, e)
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
try:
|
||||
handler.wfile.write(chunk)
|
||||
except OSError: # closing our side (finally, below) stops the generation
|
||||
raise ClientGone(f"mid-reply, after {sent:,} bytes") from None
|
||||
sent += len(chunk)
|
||||
return response.status
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -0,0 +1,225 @@
|
||||
"""The web UI and its JSON API, served on 127.0.0.1 only.
|
||||
|
||||
GET / the UI (static/index.html)
|
||||
GET /api/state everything live, polled by the UI once a second
|
||||
GET /api/history the last 10 minutes of telemetry (fetched once; the UI appends from /api/state)
|
||||
GET /api/config fan profiles, lighting zones and AI backends (static)
|
||||
POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...}
|
||||
POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"}
|
||||
POST /api/ai/active {"backend": "strata"|"llama"|null, "variant": "q5"|"iq3" (Strata only, optional)}
|
||||
POST /api/ai/model {"action": "load"|"unload"}
|
||||
|
||||
* /strata/... /llama/... the LLM servers, started on demand (kurgan/web/proxy.py)
|
||||
|
||||
The process runs elevated and controls fans, so requests are guarded: the Host header must
|
||||
name this server (blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header,
|
||||
which a page on another site can't send without a CORS preflight that this server never
|
||||
answers. There is no other authentication: anything already running on this PC as you can
|
||||
use the API.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from kurgan.web import proxy
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
|
||||
MAX_BODY = 16 * 1024
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, message: str, status: int = 400):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
def make_handler(app, port: int):
|
||||
hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
|
||||
origins = {f"http://{h}" for h in hosts}
|
||||
posts = {
|
||||
"/api/lighting": lambda b: app.set_lighting(_text(b, "zone"), _text(b, "mode")),
|
||||
"/api/cooling/profile": lambda b: app.set_fan_profile(_text(b, "profile")),
|
||||
"/api/ai/active": lambda b: app.set_ai(_optional_text(b, "backend"), _optional_text(b, "variant")),
|
||||
"/api/ai/model": lambda b: app.ai_model(_text(b, "action")),
|
||||
}
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "Kurgan"
|
||||
sys_version = ""
|
||||
|
||||
def log_message(self, fmt, *args) -> None:
|
||||
log.debug("%s %s", self.address_string(), fmt % args)
|
||||
|
||||
def _send(self, status: int, body: bytes, content_type: str = "application/json",
|
||||
cache: str = "no-store") -> None:
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", cache)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
|
||||
def _json(self, status: int, data) -> None:
|
||||
self._send(status, json.dumps(data, separators=(",", ":")).encode())
|
||||
|
||||
def _guard(self) -> bool:
|
||||
if self.headers.get("Host") not in hosts:
|
||||
self._json(403, {"error": "forbidden host"})
|
||||
return False
|
||||
return True
|
||||
|
||||
def _proxied(self) -> bool:
|
||||
"""Hand /strata/... and /llama/... to the LLM servers; True if it did."""
|
||||
if proxy.match(self.path) is None:
|
||||
return False
|
||||
try:
|
||||
proxy.handle(self, getattr(app, "ai", None), hosts, origins)
|
||||
except Exception:
|
||||
log.exception("%s %s failed", self.command, self.path)
|
||||
self.close_connection = True
|
||||
return True
|
||||
|
||||
def _other(self) -> None:
|
||||
if self._proxied():
|
||||
return
|
||||
self._read_body()
|
||||
if self._guard():
|
||||
self._json(405, {"error": "method not allowed"})
|
||||
|
||||
do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _other
|
||||
|
||||
def do_HEAD(self) -> None:
|
||||
if not self._proxied() and self._guard():
|
||||
self._json(405, {"error": "method not allowed"})
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if self._proxied() or not self._guard():
|
||||
return
|
||||
path = self.path.split("?", 1)[0]
|
||||
try:
|
||||
if path == "/api/state":
|
||||
self._json(200, app.state())
|
||||
elif path == "/api/history":
|
||||
self._json(200, app.history())
|
||||
elif path == "/api/config":
|
||||
self._json(200, app.config())
|
||||
elif path in ("/", "/index.html"):
|
||||
self._static("index.html")
|
||||
elif path.startswith("/static/"):
|
||||
self._static(path[len("/static/"):])
|
||||
else:
|
||||
self._json(404, {"error": "not found"})
|
||||
except Exception:
|
||||
log.exception("GET %s failed", path)
|
||||
self._json(500, {"error": "internal error; see kurgan.log"})
|
||||
|
||||
def _static(self, name: str) -> None:
|
||||
if name not in os.listdir(STATIC_DIR): # no paths, no traversal: only files in static/
|
||||
self._json(404, {"error": "not found"})
|
||||
return
|
||||
with open(os.path.join(STATIC_DIR, name), "rb") as f:
|
||||
body = f.read()
|
||||
kind = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||||
if kind.startswith("text/") or kind in ("application/javascript", "image/svg+xml"):
|
||||
kind += "; charset=utf-8"
|
||||
self._send(200, body, kind, cache="no-cache")
|
||||
|
||||
def _read_body(self) -> bytes | None:
|
||||
"""The request body, or None if missing or oversized. Read before any answer: closing a
|
||||
socket with unread data resets the connection on Windows, and the client would see a
|
||||
dropped connection instead of the error."""
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
except ValueError:
|
||||
self.close_connection = True
|
||||
return None
|
||||
if 0 < length <= MAX_BODY:
|
||||
return self.rfile.read(length)
|
||||
remaining = min(max(length, 0), 1024 * 1024) # drain a modest oversized body; beyond that, give up
|
||||
while remaining > 0:
|
||||
chunk = self.rfile.read(min(remaining, 65536))
|
||||
if not chunk:
|
||||
break
|
||||
remaining -= len(chunk)
|
||||
self.close_connection = True
|
||||
return None
|
||||
|
||||
def do_POST(self) -> None:
|
||||
if self._proxied():
|
||||
return
|
||||
raw = self._read_body()
|
||||
if not self._guard():
|
||||
return
|
||||
origin = self.headers.get("Origin")
|
||||
if self.headers.get("X-Kurgan") != "1" or (origin is not None and origin not in origins):
|
||||
self._json(403, {"error": "forbidden"})
|
||||
return
|
||||
if not self.headers.get("Content-Type", "").startswith("application/json"):
|
||||
self._json(415, {"error": "send application/json"})
|
||||
return
|
||||
action = posts.get(self.path)
|
||||
if action is None:
|
||||
self._json(404, {"error": "not found"})
|
||||
return
|
||||
try:
|
||||
if raw is None:
|
||||
raise ApiError("missing or oversized body")
|
||||
body = json.loads(raw)
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError("body must be a JSON object")
|
||||
action(body)
|
||||
self._json(200, app.state())
|
||||
except (ApiError, ValueError) as e:
|
||||
status = e.status if isinstance(e, ApiError) else 400
|
||||
self._json(status, {"error": str(e)})
|
||||
except OSError as e:
|
||||
log.warning("POST %s failed: %s", self.path, e)
|
||||
self._json(500, {"error": f"Couldn't save the setting: {e}"})
|
||||
except Exception:
|
||||
log.exception("POST %s failed", self.path)
|
||||
self._json(500, {"error": "internal error; see kurgan.log"})
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def _text(body: dict, key: str) -> str:
|
||||
value = body.get(key)
|
||||
if not isinstance(value, str) or not value:
|
||||
raise ApiError(f"{key} is required")
|
||||
return value
|
||||
|
||||
|
||||
def _optional_text(body: dict, key: str) -> str | None:
|
||||
value = body.get(key)
|
||||
if value is not None and not isinstance(value, str):
|
||||
raise ApiError(f"{key} must be a string or null")
|
||||
return value
|
||||
|
||||
|
||||
class WebServer:
|
||||
def __init__(self, app, port: int):
|
||||
self.port = port
|
||||
self.url = f"http://127.0.0.1:{port}/"
|
||||
self.httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(app, port))
|
||||
self.httpd.daemon_threads = True
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._thread = threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.5},
|
||||
name="web", daemon=True)
|
||||
self._thread.start()
|
||||
log.info("Web UI at %s", self.url)
|
||||
|
||||
def close(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
@@ -0,0 +1,802 @@
|
||||
/* The Kurgan - control UI. Polls /api/state once a second while the page is visible. */
|
||||
"use strict";
|
||||
|
||||
const SVGNS = "http://www.w3.org/2000/svg";
|
||||
const WINDOW_S = 600;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
/* Elements are built with textContent only: names and messages come from devices and servers. */
|
||||
function el(tag, attrs = {}, ...children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (v == null || v === false) continue;
|
||||
if (k === "class") node.className = v;
|
||||
else if (k === "style") node.style.cssText = v;
|
||||
else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
|
||||
else if (k === "text") node.textContent = v;
|
||||
else node.setAttribute(k, v === true ? "" : v);
|
||||
}
|
||||
for (const child of children.flat()) {
|
||||
if (child == null || child === false) continue;
|
||||
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function svg(tag, attrs = {}) {
|
||||
const node = document.createElementNS(SVGNS, tag);
|
||||
for (const [k, v] of Object.entries(attrs)) if (v != null) node.setAttribute(k, v);
|
||||
return node;
|
||||
}
|
||||
function setText(id, text) {
|
||||
const node = typeof id === "string" ? $(id) : id;
|
||||
if (node && node.textContent !== text) node.textContent = text;
|
||||
}
|
||||
|
||||
const fmt = {
|
||||
n0: (v) => (v == null ? "--" : Math.round(v).toLocaleString()),
|
||||
n1: (v) => (v == null ? "--" : (Math.round(v * 10) / 10).toLocaleString(undefined, { minimumFractionDigits: 1 })),
|
||||
gib: (bytes) => (bytes == null ? "--" : (bytes / 2 ** 30).toFixed(1)),
|
||||
dur(s) {
|
||||
if (s == null) return "--";
|
||||
s = Math.round(s);
|
||||
if (s < 60) return `${s} s`;
|
||||
if (s < 3600) return `${Math.floor(s / 60)} min ${s % 60} s`;
|
||||
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60);
|
||||
return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`;
|
||||
},
|
||||
clock: (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }),
|
||||
};
|
||||
|
||||
const ICON = {
|
||||
warning: "M8 1.5 15 14H1L8 1.5Zm0 4.2v4m0 2.2v.1",
|
||||
critical: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 3.8v4.4m0 2.2v.1",
|
||||
info: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 6v4.5m0-6.7v.1",
|
||||
};
|
||||
function note(kind, text) {
|
||||
const icon = svg("svg", { viewBox: "0 0 16 16", "aria-hidden": "true" });
|
||||
icon.append(svg("path", { d: ICON[kind], fill: "none", stroke: "currentColor", "stroke-width": "1.6",
|
||||
"stroke-linecap": "round", "stroke-linejoin": "round" }));
|
||||
const label = { warning: "Warning", critical: "Problem", info: "Note" }[kind];
|
||||
return el("div", { class: `note ${kind}` }, icon, el("span", {}, el("b", { text: `${label}: ` }), text));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ API */
|
||||
|
||||
async function api(path, body) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), body ? 15000 : 4000);
|
||||
try {
|
||||
const response = await fetch(path, body === undefined ? { signal: controller.signal } : {
|
||||
method: "POST", signal: controller.signal,
|
||||
headers: { "Content-Type": "application/json", "X-Kurgan": "1" }, body: JSON.stringify(body),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
let bannerTimer = null;
|
||||
function banner(kind, text, sticky = false) {
|
||||
const node = $("banner");
|
||||
clearTimeout(bannerTimer);
|
||||
if (!text) { node.hidden = true; node.dataset.kind = ""; return; }
|
||||
node.replaceChildren(note(kind, text));
|
||||
node.dataset.kind = kind;
|
||||
node.hidden = false;
|
||||
if (!sticky) bannerTimer = setTimeout(() => { node.hidden = true; }, 9000);
|
||||
}
|
||||
|
||||
/* Send a change; the group is disabled until the answer arrives, then the new state is drawn. */
|
||||
async function change(group, path, body) {
|
||||
group?.classList.add("busy");
|
||||
try {
|
||||
const state = await api(path, body);
|
||||
render(state);
|
||||
} catch (error) {
|
||||
banner("critical", error.message);
|
||||
if (lastState) render(lastState);
|
||||
} finally {
|
||||
group?.classList.remove("busy");
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tooltip */
|
||||
|
||||
const tip = {
|
||||
node: null,
|
||||
show(x, y, title, rows) {
|
||||
this.node ??= $("tooltip");
|
||||
const items = rows.map((r) => el("div", { class: "tip-row" },
|
||||
el("span", { class: "key line", style: `background:${r.color}` }), el("b", { text: r.value }), el("span", { text: r.label })));
|
||||
this.node.replaceChildren(el("div", { class: "when", text: title }), ...items);
|
||||
this.node.hidden = false;
|
||||
const w = this.node.offsetWidth, h = this.node.offsetHeight;
|
||||
const left = x + 16 + w > innerWidth ? x - 16 - w : x + 16;
|
||||
this.node.style.left = `${Math.max(4, left)}px`;
|
||||
this.node.style.top = `${Math.min(innerHeight - h - 4, Math.max(4, y - h / 2))}px`;
|
||||
},
|
||||
hide() { if (this.node) this.node.hidden = true; },
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ charts */
|
||||
|
||||
function niceMax(v) {
|
||||
if (!(v > 0)) return 1;
|
||||
const p = 10 ** Math.floor(Math.log10(v)), m = v / p;
|
||||
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p;
|
||||
}
|
||||
|
||||
/**
|
||||
* One chart: lines (or a stacked area) over time or over a numeric x, a crosshair tooltip,
|
||||
* selective end labels, an optional legend (2+ series) and a table view.
|
||||
*/
|
||||
class Chart {
|
||||
constructor(fig, opts) {
|
||||
this.o = { height: 210, unit: "", digits: 0, stacked: false, x: { type: "time" }, refs: [], ...opts };
|
||||
this.fig = fig;
|
||||
this.xs = [];
|
||||
this.cols = {};
|
||||
this.markers = [];
|
||||
const legend = this.o.series.length > 1 ? el("div", { class: "legend" },
|
||||
this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line",
|
||||
style: `background:var(${s.color})` }), s.label))) : null;
|
||||
this.toggle = el("button", { class: "btn table-toggle", type: "button", "aria-expanded": "false",
|
||||
onclick: () => this.toggleTable() }, "Table");
|
||||
this.titleNode = el("h3", { text: this.o.title });
|
||||
this.subNode = el("div", { class: "sub", style: "margin:2px 0 0", text: this.o.subtitle || "" });
|
||||
this.plot = el("div", { class: "plot" });
|
||||
this.svg = svg("svg", { role: "img", "aria-label": this.o.title });
|
||||
this.plot.append(this.svg);
|
||||
this.tableNode = el("div", { class: "chart-table", hidden: true });
|
||||
fig.replaceChildren(el("div", { class: "chart-head" }, el("div", {}, this.titleNode, this.subNode, legend), this.toggle),
|
||||
this.plot, this.tableNode);
|
||||
this.svg.addEventListener("pointermove", (e) => this.hover(e));
|
||||
this.svg.addEventListener("pointerleave", () => this.unhover());
|
||||
new ResizeObserver(() => this.draw()).observe(this.plot);
|
||||
}
|
||||
|
||||
setTitle(title, subtitle) {
|
||||
setText(this.titleNode, title);
|
||||
setText(this.subNode, subtitle || "");
|
||||
this.svg.setAttribute("aria-label", title);
|
||||
}
|
||||
|
||||
setData(xs, cols, markers = []) {
|
||||
this.xs = xs;
|
||||
this.cols = cols;
|
||||
this.markers = markers;
|
||||
this.draw();
|
||||
if (!this.tableNode.hidden) this.renderTable();
|
||||
}
|
||||
|
||||
value(key, i) { const v = this.cols[key]?.[i]; return v == null || Number.isNaN(v) ? null : v; }
|
||||
|
||||
/* Stacked: each layer's top edge; plain: the value. */
|
||||
levels() {
|
||||
const n = this.xs.length, out = {};
|
||||
let base = new Array(n).fill(0);
|
||||
for (const s of this.o.series) {
|
||||
const top = new Array(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v = this.value(s.key, i);
|
||||
top[i] = v == null ? null : (this.o.stacked ? base[i] + v : v);
|
||||
}
|
||||
out[s.key] = { base, top };
|
||||
if (this.o.stacked) base = top.map((v, i) => (v == null ? base[i] : v));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
draw() {
|
||||
const width = this.plot.clientWidth;
|
||||
if (!width) return;
|
||||
const H = this.o.height, m = { l: 44, r: 64, t: 10, b: 24 };
|
||||
const w = width - m.l - m.r, h = H - m.t - m.b;
|
||||
this.svg.setAttribute("viewBox", `0 0 ${width} ${H}`);
|
||||
this.svg.replaceChildren();
|
||||
const xo = this.o.x;
|
||||
let x0, x1;
|
||||
if (xo.type === "time") {
|
||||
x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000;
|
||||
x0 = x1 - WINDOW_S;
|
||||
} else {
|
||||
[x0, x1] = [xo.min, xo.max];
|
||||
}
|
||||
const levels = this.levels();
|
||||
let dataMax = 0;
|
||||
for (const s of this.o.series) for (const v of levels[s.key].top) if (v != null && v > dataMax) dataMax = v;
|
||||
const yMax = typeof this.o.yMax === "function" ? this.o.yMax(dataMax) : (this.o.yMax ?? niceMax(dataMax * 1.1));
|
||||
const X = (x) => m.l + ((x - x0) / (x1 - x0)) * w;
|
||||
const Y = (y) => m.t + h - (Math.max(0, Math.min(yMax, y)) / yMax) * h;
|
||||
this.geom = { X, Y, m, w, h, x0, x1, yMax, width, levels };
|
||||
|
||||
// grid + y ticks
|
||||
const grid = svg("g", { class: "grid" });
|
||||
// 4 steps unless that gives a ragged step (25 GiB / 4 = 6.25); then 5.
|
||||
const ticks = Number.isInteger((yMax / 4) * 10) ? 4 : 5;
|
||||
for (let i = 0; i <= ticks; i++) {
|
||||
const v = (yMax / ticks) * i, y = Y(v);
|
||||
if (i > 0) grid.append(svg("line", { x1: m.l, x2: m.l + w, y1: y, y2: y }));
|
||||
const t = svg("text", { x: m.l - 8, y: y + 4, "text-anchor": "end", class: "tick" });
|
||||
t.textContent = `${Number.isInteger(v) ? v.toLocaleString() : v.toFixed(1)}${this.o.unit}`;
|
||||
this.svg.append(t);
|
||||
}
|
||||
this.svg.append(grid);
|
||||
this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) }));
|
||||
// x ticks
|
||||
const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks;
|
||||
for (const xv of xticks) {
|
||||
const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" });
|
||||
t.textContent = xo.type === "time" ? (x1 - xv < 1 ? "now" : `−${Math.round((x1 - xv) / 60)} min`) : xo.fmt(xv);
|
||||
this.svg.append(t);
|
||||
}
|
||||
// reference lines (e.g. the warn/hot temperatures)
|
||||
for (const r of this.o.refs) {
|
||||
if (r.value > yMax) continue;
|
||||
this.svg.append(svg("line", { class: "ref", x1: m.l, x2: m.l + w, y1: Y(r.value), y2: Y(r.value) }));
|
||||
const t = svg("text", { x: m.l + 6, y: Y(r.value) - 5, class: "ref-label" });
|
||||
t.textContent = r.label;
|
||||
this.svg.append(t);
|
||||
}
|
||||
// series
|
||||
const ends = [];
|
||||
for (const s of this.o.series) {
|
||||
const { base, top } = levels[s.key];
|
||||
const segs = [];
|
||||
let cur = [];
|
||||
for (let i = 0; i < this.xs.length; i++) {
|
||||
if (top[i] == null || this.xs[i] < x0) { if (cur.length) segs.push(cur); cur = []; continue; }
|
||||
cur.push(i);
|
||||
}
|
||||
if (cur.length) segs.push(cur);
|
||||
for (const seg of segs) {
|
||||
const line = seg.map((i, k) => `${k ? "L" : "M"}${X(this.xs[i]).toFixed(1)},${Y(top[i]).toFixed(1)}`).join("");
|
||||
if (this.o.stacked || this.o.area) {
|
||||
const back = seg.slice().reverse().map((i) => `L${X(this.xs[i]).toFixed(1)},${Y(this.o.stacked ? base[i] : 0).toFixed(1)}`).join("");
|
||||
this.svg.append(svg("path", { d: line + back + "Z", class: "series-area", fill: `var(${s.color})` }));
|
||||
}
|
||||
this.svg.append(svg("path", { d: line, class: "series-line", stroke: `var(${s.color})` }));
|
||||
}
|
||||
const last = this.lastIndex(s.key);
|
||||
if (last != null && !this.o.noEndLabels) ends.push({ s, i: last, y: Y(top[last]) });
|
||||
}
|
||||
// operating points (fan curves): a dot with a surface ring
|
||||
for (const mk of this.markers) {
|
||||
if (mk.x == null || mk.y == null) continue;
|
||||
this.svg.append(svg("circle", { cx: X(Math.max(x0, Math.min(x1, mk.x))), cy: Y(mk.y), r: 5, class: "marker", fill: `var(${mk.color})` }));
|
||||
}
|
||||
// end labels: only where they don't collide (the legend and tooltip carry the rest)
|
||||
ends.sort((a, b) => a.y - b.y);
|
||||
let lastY = -Infinity;
|
||||
const placed = [];
|
||||
for (const e of ends) {
|
||||
if (e.y - lastY < 14) { placed.pop(); lastY = e.y; continue; }
|
||||
placed.push(e);
|
||||
lastY = e.y;
|
||||
}
|
||||
for (const e of placed) {
|
||||
const v = this.o.stacked ? this.value(e.s.key, e.i) : levels[e.s.key].top[e.i];
|
||||
const t = svg("text", { x: m.l + w + 6, y: e.y + 4, class: "end-label" });
|
||||
t.textContent = `${v.toFixed(this.o.digits)}${this.o.unit}`;
|
||||
this.svg.append(t);
|
||||
}
|
||||
this.cross = svg("line", { class: "cross", y1: m.t, y2: m.t + h, visibility: "hidden" });
|
||||
this.svg.append(this.cross);
|
||||
}
|
||||
|
||||
lastIndex(key) {
|
||||
for (let i = this.xs.length - 1; i >= 0; i--) if (this.value(key, i) != null) return i;
|
||||
return null;
|
||||
}
|
||||
|
||||
hover(e) {
|
||||
const g = this.geom;
|
||||
if (!g || !this.xs.length) return;
|
||||
const rect = this.svg.getBoundingClientRect();
|
||||
const px = ((e.clientX - rect.left) / rect.width) * g.width;
|
||||
const xv = g.x0 + ((px - g.m.l) / g.w) * (g.x1 - g.x0);
|
||||
let best = null, bestD = Infinity;
|
||||
for (let i = 0; i < this.xs.length; i++) {
|
||||
const d = Math.abs(this.xs[i] - xv);
|
||||
if (d < bestD && this.xs[i] >= g.x0) { best = i; bestD = d; }
|
||||
}
|
||||
if (best == null) return this.unhover();
|
||||
const cx = g.X(this.xs[best]);
|
||||
this.cross.setAttribute("x1", cx);
|
||||
this.cross.setAttribute("x2", cx);
|
||||
this.cross.setAttribute("visibility", "visible");
|
||||
const title = this.o.x.type === "time" ? fmt.clock(this.xs[best]) : this.o.x.fmt(this.xs[best]);
|
||||
const rows = this.o.series.slice().reverse().map((s) => {
|
||||
const v = this.value(s.key, best);
|
||||
return { color: `var(${s.color})`, label: s.label, value: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` };
|
||||
});
|
||||
if (this.o.stacked && this.o.totalLabel) {
|
||||
const total = this.o.series.reduce((a, s) => a + (this.value(s.key, best) ?? 0), 0);
|
||||
rows.unshift({ color: "transparent", label: this.o.totalLabel, value: `${total.toFixed(this.o.digits)}${this.o.unit}` });
|
||||
}
|
||||
tip.show(e.clientX, e.clientY, title, rows);
|
||||
}
|
||||
|
||||
unhover() {
|
||||
this.cross?.setAttribute("visibility", "hidden");
|
||||
tip.hide();
|
||||
}
|
||||
|
||||
toggleTable() {
|
||||
const open = this.tableNode.hidden;
|
||||
this.tableNode.hidden = !open;
|
||||
this.toggle.setAttribute("aria-expanded", String(open));
|
||||
this.toggle.textContent = open ? "Hide table" : "Table";
|
||||
if (open) this.renderTable();
|
||||
}
|
||||
|
||||
renderTable() {
|
||||
const time = this.o.x.type === "time";
|
||||
const head = el("tr", {}, el("th", { text: time ? "Time" : this.o.x.label }),
|
||||
this.o.series.map((s) => el("th", { class: "r", text: s.label })));
|
||||
const rows = [];
|
||||
let lastT = Infinity;
|
||||
const order = time ? [...this.xs.keys()].reverse() : [...this.xs.keys()];
|
||||
for (const i of order) {
|
||||
if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s
|
||||
lastT = this.xs[i];
|
||||
if (!time && this.xs[i] % 5 !== 0) continue;
|
||||
rows.push(el("tr", {}, el("td", { class: "num", text: time ? fmt.clock(this.xs[i]) : this.o.x.fmt(this.xs[i]) }),
|
||||
this.o.series.map((s) => { const v = this.value(s.key, i); return el("td", { class: "r", text: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }); })));
|
||||
}
|
||||
this.tableNode.replaceChildren(el("table", {}, el("caption", { class: "muted", style: "text-align:left;caption-side:top;padding:0 0 6px",
|
||||
text: time ? "Every 30 seconds, newest first" : "" }), el("thead", {}, head), el("tbody", {}, rows)));
|
||||
}
|
||||
|
||||
stale(on) { this.plot.classList.toggle("stale", on); }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ history */
|
||||
|
||||
class Series {
|
||||
constructor(names) { this.names = names; this.t = []; this.cols = Object.fromEntries(names.slice(1).map((n) => [n, []])); }
|
||||
load(rows) { this.t = []; for (const k in this.cols) this.cols[k] = []; for (const r of rows) this.push(r); }
|
||||
push(row) {
|
||||
if (!row || (this.t.length && row[0] <= this.t[this.t.length - 1])) return false;
|
||||
this.t.push(row[0]);
|
||||
this.names.slice(1).forEach((n, i) => this.cols[n].push(row[i + 1]));
|
||||
const cutoff = row[0] - WINDOW_S - 2;
|
||||
let drop = 0;
|
||||
while (drop < this.t.length && this.t[drop] < cutoff) drop++;
|
||||
if (drop) { this.t.splice(0, drop); for (const k in this.cols) this.cols[k].splice(0, drop); }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ app state */
|
||||
|
||||
let config = null;
|
||||
let lastState = null;
|
||||
let telemetry = null, fanHistory = null;
|
||||
let charts = {};
|
||||
let built = { profiles: false, groups: "", zones: false, backends: "" };
|
||||
let strataVariant = null;
|
||||
let profileShown = null;
|
||||
|
||||
function buildCharts() {
|
||||
const temps = config.theme;
|
||||
charts.power = new Chart($("chart-power"), {
|
||||
title: "Power", subtitle: `Whole PC, last 10 minutes (DC watts; ${fmt.n0(temps.psu_watts)} W supply)`,
|
||||
stacked: true, unit: " W", totalLabel: "Total",
|
||||
series: [{ key: "other_w", label: "Other", color: "--other" }, { key: "cpu_w", label: "CPU", color: "--cpu" },
|
||||
{ key: "gpu_w", label: "GPU", color: "--gpu" }],
|
||||
});
|
||||
charts.temps = new Chart($("chart-temps"), {
|
||||
title: "Temperatures", subtitle: "Last 10 minutes", unit: "°", yMax: (m) => Math.max(100, niceMax(m)),
|
||||
series: [{ key: "cpu_temp", label: "CPU", color: "--cpu" }, { key: "gpu_temp", label: "GPU", color: "--gpu" }],
|
||||
refs: [{ value: temps.temp_warn, label: `warm ${temps.temp_warn}°` }, { value: temps.temp_hot, label: `hot ${temps.temp_hot}°` }],
|
||||
});
|
||||
charts.fans = new Chart($("chart-fans"), {
|
||||
title: "Fan speeds", subtitle: "PWM duty, last 10 minutes", unit: "%", yMax: 100,
|
||||
series: [{ key: "cpu_duty", label: "CPU side", color: "--cpu" }, { key: "gpu_duty", label: "GPU side", color: "--gpu" },
|
||||
{ key: "top_duty", label: "Top", color: "--top" }],
|
||||
});
|
||||
charts.curves = new Chart($("chart-curves"), {
|
||||
title: "Profile curves", unit: "%", yMax: 100, noEndLabels: true,
|
||||
x: { type: "linear", min: 20, max: 100, ticks: [20, 30, 40, 50, 60, 70, 80, 90, 100], fmt: (v) => `${v} °C`, label: "Temperature" },
|
||||
series: [{ key: "cpu", label: "CPU side", color: "--cpu" }, { key: "gpu", label: "GPU side", color: "--gpu" },
|
||||
{ key: "top", label: "Top", color: "--top" }],
|
||||
});
|
||||
charts.vram = new Chart($("chart-vram"), {
|
||||
title: "GPU memory used", subtitle: "Last 10 minutes", unit: " GiB", digits: 1, area: true,
|
||||
series: [{ key: "vram", label: "GPU memory", color: "--gpu" }],
|
||||
yMax: () => niceMax((lastState?.telemetry?.gpu?.vram_total ?? 24 * 2 ** 30) / 2 ** 30),
|
||||
});
|
||||
}
|
||||
|
||||
function curveDuty(curve, t) {
|
||||
if (t <= curve[0][0]) return curve[0][1];
|
||||
for (let i = 1; i < curve.length; i++) {
|
||||
const [t0, d0] = curve[i - 1], [t1, d1] = curve[i];
|
||||
if (t <= t1) return Math.ceil(d0 + (t - t0) * (d1 - d0) / (t1 - t0));
|
||||
}
|
||||
return 100;
|
||||
}
|
||||
|
||||
function drawCurves(state) {
|
||||
const p = config.profiles.find((x) => x.key === (profileShown ?? state.cooling.profile)) ?? config.profiles[0];
|
||||
const xs = [], cols = { cpu: [], gpu: [], top: [] };
|
||||
for (let t = 20; t <= 100; t++) {
|
||||
xs.push(t);
|
||||
cols.cpu.push(curveDuty(p.cpu_curve, t));
|
||||
cols.gpu.push(curveDuty(p.gpu_curve, t));
|
||||
cols.top.push(t < p.top_start ? 0 : curveDuty(p.top_curve, t));
|
||||
}
|
||||
const markers = [];
|
||||
for (const g of state.cooling.groups) markers.push({ x: g.temp, y: g.duty, color: g.name === "GPU" ? "--gpu" : "--cpu" });
|
||||
if (state.cooling.top) markers.push({ x: state.cooling.top.temp, y: state.cooling.top.duty, color: "--top" });
|
||||
charts.curves.setTitle(`${p.name} profile curves`,
|
||||
`Dots: each group now. Top fans start at ${p.top_start} °C and stop below ${p.top_stop} °C.`);
|
||||
charts.curves.setData(xs, cols, state.cooling.groups.length || state.cooling.top ? markers : []);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ render: header & system */
|
||||
|
||||
function renderHeader(s) {
|
||||
setText("hero-total", fmt.n0(s.telemetry.power?.total));
|
||||
const meta = $("meta");
|
||||
const elevated = s.app.token?.elevated;
|
||||
meta.replaceChildren(
|
||||
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
|
||||
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
|
||||
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
|
||||
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
|
||||
);
|
||||
setText("footer", `${s.app.name} ${s.app.version} · pid ${s.app.pid} · log: %LOCALAPPDATA%\\Kurgan\\kurgan.log · JSON: /api/state`);
|
||||
}
|
||||
|
||||
function renderSystem(s) {
|
||||
const t = s.telemetry;
|
||||
if (!t.cpu) return;
|
||||
setText("cpu-temp", fmt.n0(t.cpu.temp));
|
||||
setText("cpu-detail", `${fmt.n0(t.cpu.load)}% load · ${fmt.n0(t.cpu.clock)} MHz · ${fmt.n0(t.cpu.power)} W`);
|
||||
setText("gpu-temp", fmt.n0(t.gpu.temp));
|
||||
setText("gpu-detail", `${fmt.n0(t.gpu.load)}% load · ${fmt.n0(t.gpu.clock)} MHz · ${fmt.n0(t.gpu.power)} W`);
|
||||
setText("vram-used", fmt.gib(t.gpu.vram_used));
|
||||
setText("vram-total", t.gpu.vram_total ? ` / ${fmt.gib(t.gpu.vram_total)} GiB` : "");
|
||||
const share = t.gpu.vram_total ? (100 * t.gpu.vram_used) / t.gpu.vram_total : 0;
|
||||
$("vram-meter").firstChild.style.width = `${share.toFixed(1)}%`;
|
||||
$("vram-meter").setAttribute("aria-valuenow", share.toFixed(0));
|
||||
$("vram-meter").className = `meter ${share > 92 ? "warning" : "gpu"}`;
|
||||
setText("lcd-status", s.display.status);
|
||||
setText("lcd-detail", s.display.frames != null ? `${fmt.n0(s.display.frames)} frames sent` : "");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ render: cooling */
|
||||
|
||||
function buildProfiles() {
|
||||
const group = $("profiles");
|
||||
group.replaceChildren(...config.profiles.map((p) => el("label", {},
|
||||
el("input", { type: "radio", name: "profile", value: p.key,
|
||||
onchange: () => { profileShown = p.key; change(group, "/api/cooling/profile", { profile: p.key }); } }),
|
||||
el("span", { text: p.name }))));
|
||||
group.addEventListener("mouseover", (e) => {
|
||||
const key = e.target.closest("label")?.querySelector("input")?.value;
|
||||
if (key && key !== profileShown) { profileShown = key; drawCurves(lastState); describeProfile(); }
|
||||
});
|
||||
group.addEventListener("mouseleave", () => { profileShown = null; drawCurves(lastState); describeProfile(); });
|
||||
built.profiles = true;
|
||||
}
|
||||
|
||||
function describeProfile() {
|
||||
const key = profileShown ?? lastState.cooling.profile;
|
||||
const p = config.profiles.find((x) => x.key === key);
|
||||
setText("profile-desc", p ? (key === lastState.cooling.profile ? p.description : `Preview: ${p.description}`) : "");
|
||||
}
|
||||
|
||||
function fanCard(g, kind) {
|
||||
const ports = Object.entries(g.rpms ?? {});
|
||||
return el("div", { class: "card", "data-group": kind },
|
||||
el("div", { class: "tile" }, el("div", { class: "label" }, el("span", { class: "key", style: `background:var(--${kind})` }),
|
||||
kind === "top" ? `Top fans · channels ${g.channels.join(", ")}` : `${g.name}-side case fans · ports ${g.ports.join(", ")}`)),
|
||||
el("div", { class: "fan-head", style: "margin-top:4px" }, el("span", { class: "fan-duty", "data-f": "duty" }),
|
||||
el("span", { class: "muted", "data-f": "temp" })),
|
||||
el("div", { class: `meter ${kind}`, role: "meter", "aria-label": "PWM duty", "data-f": "meter" }, el("span")),
|
||||
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {}, `Port ${p} `, el("b", { "data-port": p }), " rpm"))),
|
||||
el("div", { "data-f": "note" }));
|
||||
}
|
||||
|
||||
function updateFanCard(card, g, kind) {
|
||||
const q = (f) => card.querySelector(`[data-f="${f}"]`);
|
||||
setText(q("duty"), `${g.duty}%`);
|
||||
const temp = g.temp == null ? "temperature unavailable" : `at ${fmt.n0(g.temp)} °C ${kind === "top" ? "(hotter of CPU/GPU)" : g.name}`;
|
||||
setText(q("temp"), kind === "top" && !g.running ? `stopped · ${fmt.n0(g.temp)} °C` : temp);
|
||||
const meter = q("meter");
|
||||
meter.firstChild.style.width = `${g.duty}%`;
|
||||
meter.setAttribute("aria-valuenow", g.duty);
|
||||
meter.className = `meter ${g.failsafe ? "critical" : kind}`;
|
||||
for (const [p, rpm] of Object.entries(g.rpms ?? {})) setText(card.querySelector(`[data-port="${p}"]`), fmt.n0(rpm));
|
||||
const n = q("note");
|
||||
const text = g.failsafe ? g.status : kind === "top" && g.boosted ? "Held at 100% while a case-fan group runs at 85% or more." : "";
|
||||
if (n.dataset.text !== text) {
|
||||
n.dataset.text = text;
|
||||
n.replaceChildren(...(text ? [note(g.failsafe ? "critical" : "info", text)] : []));
|
||||
}
|
||||
}
|
||||
|
||||
function renderCooling(s) {
|
||||
const c = s.cooling;
|
||||
if (!built.profiles) buildProfiles();
|
||||
if (!$("profiles").classList.contains("busy")) {
|
||||
for (const input of $("profiles").querySelectorAll("input")) input.checked = input.value === c.profile;
|
||||
}
|
||||
describeProfile();
|
||||
const noteNode = $("cooling-note");
|
||||
if ((noteNode.dataset.text ?? "") !== (c.note ?? "")) {
|
||||
noteNode.dataset.text = c.note ?? "";
|
||||
noteNode.replaceChildren(...(c.note ? [note("warning", c.note)] : []));
|
||||
}
|
||||
const kinds = c.groups.map((g) => [g, g.name === "GPU" ? "gpu" : "cpu"]);
|
||||
if (c.top) kinds.push([c.top, "top"]);
|
||||
const signature = kinds.map(([g, k]) => k + (g.ports ?? g.channels).join()).join("|");
|
||||
if (built.groups !== signature) {
|
||||
$("fan-groups").replaceChildren(...kinds.map(([g, k]) => fanCard(g, k)));
|
||||
built.groups = signature;
|
||||
}
|
||||
for (const [g, k] of kinds) updateFanCard($("fan-groups").querySelector(`[data-group="${k}"]`), g, k);
|
||||
if (fanHistory.push(c.row)) charts.fans.setData(fanHistory.t, fanHistory.cols);
|
||||
$("chart-fans").hidden = !c.groups.length;
|
||||
drawCurves(s);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ render: lighting */
|
||||
|
||||
function buildZones(lighting) {
|
||||
$("light-zones").replaceChildren(...lighting.zones.map((z) => {
|
||||
const group = el("div", { class: "seg", role: "radiogroup", "aria-label": z.label });
|
||||
group.append(...z.modes.map((m) => el("label", {},
|
||||
el("input", { type: "radio", name: `zone-${z.key}`, value: m.key,
|
||||
onchange: () => change(group, "/api/lighting", { zone: z.key, mode: m.key }) }),
|
||||
el("span", { text: m.label }))));
|
||||
return el("div", { class: "card zone", "data-zone": z.key }, el("h3", { text: z.label, style: "margin-bottom:10px" }),
|
||||
group, el("div", { class: "status" }), el("div", { "data-f": "note" }));
|
||||
}));
|
||||
built.zones = true;
|
||||
}
|
||||
|
||||
function renderLighting(s) {
|
||||
if (!built.zones) buildZones(s.lighting);
|
||||
for (const z of s.lighting.zones) {
|
||||
const card = $("light-zones").querySelector(`[data-zone="${z.key}"]`);
|
||||
const group = card.querySelector(".seg");
|
||||
if (!group.classList.contains("busy")) for (const i of group.querySelectorAll("input")) i.checked = i.value === z.mode;
|
||||
const bad = /unavailable|busy|error|stopped/i.test(z.status);
|
||||
setText(card.querySelector(".status"), bad ? "" : (z.status === "off" ? "Off" : z.status));
|
||||
const n = card.querySelector('[data-f="note"]');
|
||||
const text = (bad ? z.status : "") + (z.this_run_only ? (bad ? " " : "") + "Set by a command-line option for this run; choosing here saves it." : "");
|
||||
if (n.dataset.text !== text) {
|
||||
n.dataset.text = text;
|
||||
n.replaceChildren(...(text ? [note(bad ? "warning" : "info", text)] : []));
|
||||
}
|
||||
}
|
||||
setText("chase-note", s.lighting.chase_ms_per_led
|
||||
? `The chases share one clock: ${s.lighting.chase_ms_per_led} ms per LED now, faster as total power rises.` : "");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ render: AI */
|
||||
|
||||
const MODEL_STATE = {
|
||||
offline: ["Not answering", ""], unloaded: ["Model unloaded · loads on the first request", ""],
|
||||
sleeping: ["Model asleep · loads on the first request", ""], loading: ["Loading model", "warning"],
|
||||
idle: ["Model loaded · idle", "good"], reading: ["Reading the prompt", "good"], generating: ["Generating", "good"],
|
||||
failed: ["Model failed to load", "critical"],
|
||||
};
|
||||
const PROCESS = { running: "Running", starting: "Starting", stopping: "Stopping", external: "Running outside The Kurgan", stopped: "Stopped" };
|
||||
|
||||
function busyBackend(ai) {
|
||||
return ai.backends.find((b) => b.key === ai.active && b.live);
|
||||
}
|
||||
|
||||
function chooseBackend(key, variant) {
|
||||
const ai = lastState.ai, busy = busyBackend(ai);
|
||||
if (busy && (key !== busy.key || (variant && variant !== busy.variant)) &&
|
||||
!confirm(`${busy.label} is answering a request right now. Switching stops it. Switch anyway?`)) {
|
||||
render(lastState);
|
||||
return;
|
||||
}
|
||||
change($("backends"), "/api/ai/active", variant ? { backend: key, variant } : { backend: key });
|
||||
}
|
||||
|
||||
function buildBackends(ai) {
|
||||
const cards = ai.backends.map((b) => {
|
||||
const select = b.variants.length ? el("select", { "aria-label": `${b.label} model`,
|
||||
onchange: (e) => { strataVariant = e.target.value; if (ai.active === b.key || lastState.ai.active === b.key) chooseBackend(b.key, strataVariant); } },
|
||||
b.variants.map((v) => el("option", { value: v.key, text: v.label }))) : null;
|
||||
return el("label", { class: "choice", "data-key": b.key },
|
||||
el("input", { type: "radio", name: "backend", value: b.key,
|
||||
onchange: () => chooseBackend(b.key, b.variants.length ? (strataVariant ?? b.variant) : null) }),
|
||||
el("div", { class: "name" }, b.label, el("span", { class: "check" })),
|
||||
el("div", { class: "what", "data-f": "what" }), select,
|
||||
el("div", { class: "state", "data-f": "state" }));
|
||||
});
|
||||
cards.push(el("label", { class: "choice", "data-key": "" },
|
||||
el("input", { type: "radio", name: "backend", value: "", onchange: () => chooseBackend(null) }),
|
||||
el("div", { class: "name" }, "None", el("span", { class: "check" })),
|
||||
el("div", { class: "what", text: "Nothing running; the GPU's memory is free. The next request to either address starts its server." }),
|
||||
el("div", { class: "state", "data-f": "state" })));
|
||||
$("backends").replaceChildren(...cards);
|
||||
built.backends = ai.backends.map((b) => b.key).join();
|
||||
}
|
||||
|
||||
function stateLine(b) {
|
||||
const [text, kind] = b.process === "running" || b.process === "external" ? MODEL_STATE[b.model.state] ?? [b.model.state, ""]
|
||||
: [PROCESS[b.process], b.process === "starting" || b.process === "stopping" ? "warning" : ""];
|
||||
const pill = el("span", { class: "pill" }, el("span", { class: `dot ${kind}` }), text);
|
||||
if (b.process !== "external") return pill;
|
||||
return el("span", { class: "pills" }, el("span", { class: "pill" }, el("span", { class: "dot warning" }), "Outside The Kurgan"), pill);
|
||||
}
|
||||
|
||||
function renderAI(s) {
|
||||
const ai = s.ai;
|
||||
if (!ai) { $("ai").hidden = true; return; }
|
||||
if (built.backends !== ai.backends.map((b) => b.key).join()) buildBackends(ai);
|
||||
const group = $("backends");
|
||||
group.classList.toggle("busy", !!ai.transition);
|
||||
for (const b of ai.backends) {
|
||||
const card = group.querySelector(`[data-key="${b.key}"]`);
|
||||
setText(card.querySelector('[data-f="what"]'), `${b.model_label} · ${b.route}v1`);
|
||||
const select = card.querySelector("select");
|
||||
if (select && document.activeElement !== select) select.value = ai.active === b.key ? b.variant : (strataVariant ?? b.variant);
|
||||
card.querySelector('[data-f="state"]').replaceChildren(stateLine(b));
|
||||
}
|
||||
const noneState = group.querySelector('[data-key=""] [data-f="state"]');
|
||||
const serving = ai.backends.some((b) => b.process !== "stopped");
|
||||
noneState.replaceChildren(...(ai.active == null && !serving
|
||||
? [el("span", { class: "pill" }, el("span", { class: "dot good" }), "GPU memory free")] : []));
|
||||
if (!group.classList.contains("pending")) {
|
||||
for (const input of group.querySelectorAll('input[type="radio"]')) input.checked = input.value === (ai.active ?? "");
|
||||
}
|
||||
|
||||
const m = ai.idle_stop_minutes;
|
||||
setText("ai-idle", m ? `A server nobody uses for ${m} minutes stops and frees the GPU's memory; the next request starts it again.`
|
||||
: "Servers keep running when nobody uses them (ai.idle_stop_minutes is 0).");
|
||||
|
||||
const notes = [];
|
||||
if (ai.transition) notes.push(note("info", `${ai.transition}…`));
|
||||
if (ai.warning) notes.push(note("warning", ai.warning));
|
||||
if (ai.message) notes.push(note("critical", ai.message));
|
||||
$("ai-notes").replaceChildren(...notes);
|
||||
|
||||
renderActive(ai);
|
||||
const vram = telemetry.cols.vram_used.map((v) => (v == null ? null : v / 2 ** 30));
|
||||
charts.vram.setData(telemetry.t, { vram });
|
||||
}
|
||||
|
||||
function renderActive(ai) {
|
||||
const box = $("ai-active");
|
||||
const b = ai.backends.find((x) => x.key === ai.active);
|
||||
if (!b) {
|
||||
const kv = el("dl", { class: "kv" }, ai.backends.flatMap((x) => [
|
||||
el("dt", { text: x.label }), el("dd", {}, el("code", { text: x.links.api }))]));
|
||||
box.replaceChildren(el("h3", { text: "No LLM server running" }),
|
||||
el("p", { class: "sub", text: "A request to either address starts its server, or pick one above. The Kurgan remembers a choice made here and starts it at every logon." }),
|
||||
kv);
|
||||
renderRequests(null);
|
||||
return;
|
||||
}
|
||||
const running = b.process === "running" || b.process === "external";
|
||||
const st = b.model.state;
|
||||
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
|
||||
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
|
||||
: `${b.token.elevated ? "restricted token" : "normal user"}, ${b.token.integrity} integrity`;
|
||||
const kv = el("dl", { class: "kv" },
|
||||
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
|
||||
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,
|
||||
el("dt", { text: "API" }), el("dd", {}, el("code", { text: b.links.api }), " · no API key needed"),
|
||||
b.pid ? [el("dt", { text: "Process" }), el("dd", { text: `pid ${b.pid}${b.external_program ? ` (${b.external_program})` : ""} · port ${b.port}${token ? ` · ${token}` : ""}` })] : null,
|
||||
b.uptime != null ? [el("dt", { text: "Up" }), el("dd", { text: fmt.dur(b.uptime) + (b.restarts ? ` · ${b.restarts} restart${b.restarts > 1 ? "s" : ""}` : "") })] : null,
|
||||
b.inflight ? [el("dt", { text: "Requests" }), el("dd", { text: `${b.inflight} in progress` })] : null,
|
||||
b.idle_stop_in != null ? [el("dt", { text: "Idle stop" }), el("dd", { text: `in ${fmt.dur(b.idle_stop_in)} if unused` })] : null,
|
||||
);
|
||||
const canLoad = running && ["unloaded", "sleeping"].includes(st);
|
||||
const canUnload = running && ["idle", "loading"].includes(st);
|
||||
const actions = el("div", { class: "row", style: "margin-top:14px" },
|
||||
el("button", { class: "btn", type: "button", disabled: !(canLoad || canUnload) || !!ai.action,
|
||||
onclick: (e) => change(e.target, "/api/ai/model", { action: canLoad ? "load" : "unload" }) },
|
||||
ai.action ? `${ai.action}…` : canUnload ? "Unload model" : "Load model"),
|
||||
el("a", { class: "btn", href: b.links.chat, target: "_blank", rel: "noopener" }, `Open ${b.label} chat ↗`));
|
||||
let live = null;
|
||||
if (b.live) {
|
||||
const L = b.live;
|
||||
const text = L.phase === "reading"
|
||||
? `Reading the prompt${L.progress != null ? ` · ${Math.round(L.progress * 100)}%` : ""}${L.read != null ? ` · ${fmt.n0(L.read)}${L.total ? ` of ${fmt.n0(L.total)}` : ""} tokens` : ""}`
|
||||
: `Generating · ${fmt.n0(L.generated)} tokens`;
|
||||
live = el("div", { class: "live" }, el("div", { class: "row" }, el("b", { text }), el("span", { class: "spacer" }),
|
||||
el("span", { class: "muted num", text: `${L.tok_s != null ? `${fmt.n1(L.tok_s)} tok/s · ` : ""}${fmt.dur(L.elapsed)}` })),
|
||||
L.phase === "reading" && L.progress != null
|
||||
? el("div", { class: "meter", role: "progressbar", "aria-valuenow": Math.round(L.progress * 100) },
|
||||
el("span", { style: `width:${(L.progress * 100).toFixed(1)}%` })) : null);
|
||||
}
|
||||
const avg = b.averages;
|
||||
const speeds = el("div", { class: "speeds" },
|
||||
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.prefill_tps) }), el("div", { class: "label", text: "tok/s reading (average)" })),
|
||||
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.decode_tps) }), el("div", { class: "label", text: "tok/s writing (average)" })),
|
||||
el("div", {}, el("div", { class: "value", text: fmt.n0(avg.requests) }), el("div", { class: "label", text: "requests" })));
|
||||
const notes = [];
|
||||
if (b.process === "external") notes.push(note("info", `Started outside The Kurgan${b.external_program ? ` by ${b.external_program}` : ""}. The Kurgan only watches it; retire that program's own startup task so The Kurgan can manage it.`));
|
||||
if (b.error) notes.push(note("critical", b.error));
|
||||
if (b.model.state === "failed" && b.model.detail) notes.push(note("critical", b.model.detail));
|
||||
if (adminLevel) notes.push(note("warning", "This server is running with admin rights; it should not be."));
|
||||
// replaceChildren would print a null as the text "null", so drop the empty parts first.
|
||||
box.replaceChildren(...[el("div", { class: "row" }, el("h3", { text: b.label }), stateLine(b)),
|
||||
kv, live, running && avg.requests ? speeds : null, ...notes, actions].filter(Boolean));
|
||||
renderRequests(b);
|
||||
}
|
||||
|
||||
function renderRequests(b) {
|
||||
const list = b?.requests ?? [];
|
||||
setText("requests-sub", b ? `${b.label}, newest first${list.length ? "" : " · none yet"}` : "No server selected");
|
||||
if (!list.length) { $("requests").replaceChildren(); return; }
|
||||
const head = el("tr", {}, ["Time", "Prompt", "Cached", "Output", "Reading tok/s", "Writing tok/s", "Took", "Result"]
|
||||
.map((h, i) => el("th", { class: i && i < 7 ? "r" : "", text: h })));
|
||||
const rows = list.map((r) => el("tr", {},
|
||||
el("td", { class: "num", text: r.time ?? "--" }), el("td", { class: "r", text: fmt.n0(r.prompt) }),
|
||||
el("td", { class: "r", text: fmt.n0(r.reused) }), el("td", { class: "r", text: fmt.n0(r.output) }),
|
||||
el("td", { class: "r", text: fmt.n1(r.prefill_tps) }), el("td", { class: "r", text: fmt.n1(r.decode_tps) }),
|
||||
el("td", { class: "r", text: r.duration != null ? `${fmt.n1(r.duration)} s` : "--" }), el("td", { text: r.status })));
|
||||
$("requests").replaceChildren(el("table", {}, el("thead", {}, head), el("tbody", {}, rows)));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main loop */
|
||||
|
||||
function render(s) {
|
||||
lastState = s;
|
||||
renderHeader(s);
|
||||
renderSystem(s);
|
||||
if (telemetry.push(s.telemetry.row)) {
|
||||
charts.power.setData(telemetry.t, telemetry.cols);
|
||||
charts.temps.setData(telemetry.t, telemetry.cols);
|
||||
}
|
||||
renderCooling(s);
|
||||
renderLighting(s);
|
||||
renderAI(s);
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
async function poll() {
|
||||
if (document.hidden) return;
|
||||
try {
|
||||
const s = await api("/api/state");
|
||||
if (failures) { banner(null); Object.values(charts).forEach((c) => c.stale(false)); }
|
||||
failures = 0;
|
||||
render(s);
|
||||
} catch (error) {
|
||||
failures++;
|
||||
if (failures === 2) {
|
||||
banner("critical", "Can't reach The Kurgan. It may be restarting; this page keeps trying.", true);
|
||||
Object.values(charts).forEach((c) => c.stale(true));
|
||||
$("meta").replaceChildren(el("span", { class: "pill" }, el("span", { class: "dot critical" }), "Disconnected"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
config = await api("/api/config");
|
||||
const history = await api("/api/history");
|
||||
telemetry = new Series(history.series);
|
||||
telemetry.load(history.rows);
|
||||
fanHistory = new Series(history.fans.series);
|
||||
fanHistory.load(history.fans.rows);
|
||||
} catch (error) {
|
||||
banner("critical", `Can't load The Kurgan's data: ${error.message}. Reload the page to try again.`, true);
|
||||
return;
|
||||
}
|
||||
buildCharts();
|
||||
charts.power.setData(telemetry.t, telemetry.cols);
|
||||
charts.temps.setData(telemetry.t, telemetry.cols);
|
||||
charts.fans.setData(fanHistory.t, fanHistory.cols);
|
||||
await poll();
|
||||
setInterval(poll, 1000);
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<symbol id="tank" viewBox="0 0 32 32">
|
||||
<rect x="6.5" y="4" width="19" height="24" rx="1" fill="#141418"/>
|
||||
<rect x="6.5" y="21" width="19" height="7" fill="#d95926"/>
|
||||
<rect x="6.5" y="14.5" width="19" height="6" fill="#3987e5"/>
|
||||
<rect x="6.5" y="8" width="19" height="6" fill="#199e70"/>
|
||||
<rect x="9" y="5" width="2.2" height="22" fill="#fff" opacity=".25"/>
|
||||
<rect x="3.5" y="1" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
|
||||
<rect x="3.5" y="26.5" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
|
||||
</symbol>
|
||||
<use href="#tank"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 632 B |
@@ -0,0 +1,117 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>The Kurgan</title>
|
||||
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<script src="/static/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="masthead">
|
||||
<div class="brand">
|
||||
<svg viewBox="0 0 32 32" aria-hidden="true"><use href="/static/favicon.svg#tank"/></svg>
|
||||
<h1>THE KURGAN</h1>
|
||||
</div>
|
||||
<nav aria-label="Sections">
|
||||
<a href="#system">System</a><a href="#cooling">Cooling</a><a href="#lighting">Lighting</a><a href="#ai">AI</a>
|
||||
</nav>
|
||||
<div class="hero" title="Whole-PC power draw (DC, load on the power supply)">
|
||||
<span class="hero-value" id="hero-total">--</span><span class="hero-unit">W</span>
|
||||
<span class="hero-label">whole PC</span>
|
||||
</div>
|
||||
<div class="meta" id="meta" aria-live="polite"></div>
|
||||
</header>
|
||||
<div class="banner" id="banner" role="status" hidden></div>
|
||||
|
||||
<main>
|
||||
<!-- ======================================================== SYSTEM -->
|
||||
<section id="system" aria-labelledby="h-system">
|
||||
<h2 id="h-system">System</h2>
|
||||
<div class="tiles">
|
||||
<div class="card tile">
|
||||
<div class="label"><span class="key" style="background:var(--cpu)"></span>CPU</div>
|
||||
<div class="value"><span id="cpu-temp">--</span><small>°C</small></div>
|
||||
<div class="detail" id="cpu-detail"> </div>
|
||||
</div>
|
||||
<div class="card tile">
|
||||
<div class="label"><span class="key" style="background:var(--gpu)"></span>GPU</div>
|
||||
<div class="value"><span id="gpu-temp">--</span><small>°C</small></div>
|
||||
<div class="detail" id="gpu-detail"> </div>
|
||||
</div>
|
||||
<div class="card tile">
|
||||
<div class="label">GPU memory</div>
|
||||
<div class="value"><span id="vram-used">--</span><small id="vram-total"></small></div>
|
||||
<div class="meter" role="meter" aria-label="GPU memory used" id="vram-meter"><span></span></div>
|
||||
</div>
|
||||
<div class="card tile">
|
||||
<div class="label">LCD</div>
|
||||
<div class="value" style="font-size:18px;margin-top:8px" id="lcd-status">--</div>
|
||||
<div class="detail" id="lcd-detail"> </div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid2">
|
||||
<figure class="card chart" id="chart-power"></figure>
|
||||
<figure class="card chart" id="chart-temps"></figure>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ======================================================== COOLING -->
|
||||
<section id="cooling" aria-labelledby="h-cooling">
|
||||
<h2 id="h-cooling">Cooling</h2>
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<div>
|
||||
<h3>Fan profile</h3>
|
||||
<p class="sub" style="margin:0">Applies to the Commander PRO case fans and the motherboard top fans. Fail-safes stay on in every profile.</p>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" role="radiogroup" aria-label="Fan profile" id="profiles"></div>
|
||||
</div>
|
||||
<p class="profile-desc" id="profile-desc"></p>
|
||||
<div id="cooling-note"></div>
|
||||
</div>
|
||||
<div class="grid3" id="fan-groups"></div>
|
||||
<div class="grid2">
|
||||
<figure class="card chart" id="chart-fans"></figure>
|
||||
<figure class="card chart" id="chart-curves"></figure>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ======================================================== LIGHTING -->
|
||||
<section id="lighting" aria-labelledby="h-lighting">
|
||||
<h2 id="h-lighting">Lighting</h2>
|
||||
<div class="grid3" id="light-zones"></div>
|
||||
<p class="muted" style="font-size:13px;margin:10px 2px 0" id="chase-note"></p>
|
||||
</section>
|
||||
|
||||
<!-- ======================================================== AI -->
|
||||
<section id="ai" aria-labelledby="h-ai">
|
||||
<h2 id="h-ai">AI</h2>
|
||||
<div class="card">
|
||||
<div class="row" style="margin-bottom:12px">
|
||||
<div>
|
||||
<h3>Local LLM server</h3>
|
||||
<p class="sub" style="margin:0">One runs at a time, so they never share the GPU's memory. A request to either one's address starts it, once the other has finished what it's doing; switching stops the other completely first.</p>
|
||||
<p class="sub" style="margin:4px 0 0" id="ai-idle"></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="backends" role="radiogroup" aria-label="LLM server" id="backends"></div>
|
||||
<div id="ai-notes"></div>
|
||||
</div>
|
||||
<div class="grid2">
|
||||
<div class="card" id="ai-active"></div>
|
||||
<figure class="card chart" id="chart-vram"></figure>
|
||||
</div>
|
||||
<div class="card" style="margin-top:16px">
|
||||
<h3>Recent requests</h3>
|
||||
<p class="sub" id="requests-sub">Newest first</p>
|
||||
<div class="table-wrap" id="requests"></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<footer id="footer"></footer>
|
||||
<div class="tooltip" id="tooltip" role="tooltip" hidden></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,277 @@
|
||||
/* The Kurgan - control UI. Dark by default; a selected light theme follows the OS setting. */
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0b0b0b;
|
||||
--surface: #191919;
|
||||
--surface-2: #222222;
|
||||
--raised: #2a2a2a;
|
||||
--text: #efefef;
|
||||
--text-2: #9c9c9c;
|
||||
--grid: #303030;
|
||||
--axis: #474747;
|
||||
--border: rgba(255, 255, 255, 0.10);
|
||||
--brand: #e81c2c;
|
||||
--select-bg: #efefef;
|
||||
--select-text: #0b0b0b;
|
||||
/* series: validated together (dataviz validator, dark surface #191919) */
|
||||
--cpu: #338ced;
|
||||
--gpu: #00a888;
|
||||
--other: #e76624;
|
||||
--top: #e76624;
|
||||
/* status: reserved for state, always with an icon and a word */
|
||||
--good: #0aac23;
|
||||
--warning: #fbb315;
|
||||
--serious: #f18a59;
|
||||
--critical: #dc3c3d;
|
||||
--meter-track: #2c2c2c;
|
||||
--meter-fill: #9c9c9c;
|
||||
--font: system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f9f9f9;
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f3f3f3;
|
||||
--raised: #e9e9e9;
|
||||
--text: #191919;
|
||||
--text-2: #666666;
|
||||
--grid: #e7e7e7;
|
||||
--axis: #c2c2c2;
|
||||
--border: rgba(11, 11, 11, 0.10);
|
||||
--brand: #c4121f;
|
||||
--select-bg: #191919;
|
||||
--select-text: #ffffff;
|
||||
--cpu: #257de0;
|
||||
--gpu: #00b894;
|
||||
--other: #f47230;
|
||||
--top: #f47230;
|
||||
--meter-track: #e7e7e7;
|
||||
--meter-fill: #666666;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior: smooth; scroll-padding-top: 76px; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--page);
|
||||
color: var(--text);
|
||||
font: 14px/1.45 var(--font);
|
||||
}
|
||||
a { color: inherit; }
|
||||
button, select, input { font: inherit; color: inherit; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
/* ---------------------------------------------------------------- header */
|
||||
.masthead {
|
||||
position: sticky; top: 0; z-index: 10;
|
||||
display: flex; align-items: center; gap: 24px; flex-wrap: wrap;
|
||||
padding: 10px 24px;
|
||||
background: color-mix(in srgb, var(--page) 92%, transparent);
|
||||
backdrop-filter: blur(6px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 10px; }
|
||||
.brand svg { width: 22px; height: 22px; }
|
||||
.brand h1 {
|
||||
margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.22em; color: var(--brand);
|
||||
}
|
||||
.masthead nav { display: flex; gap: 4px; }
|
||||
.masthead nav a {
|
||||
text-decoration: none; color: var(--text-2); padding: 4px 10px; border-radius: 6px;
|
||||
}
|
||||
.masthead nav a:hover, .masthead nav a:focus-visible { background: var(--surface-2); color: var(--text); }
|
||||
.hero { margin-left: auto; display: flex; align-items: baseline; gap: 6px; }
|
||||
.hero-value { font-size: 48px; font-weight: 600; line-height: 1; }
|
||||
.hero-unit { font-size: 18px; font-weight: 600; }
|
||||
.hero-label { color: var(--text-2); margin-left: 4px; }
|
||||
.meta { color: var(--text-2); font-size: 13px; display: flex; gap: 14px; flex-wrap: wrap; }
|
||||
|
||||
.banner {
|
||||
margin: 12px 24px 0; padding: 10px 14px; border-radius: 8px;
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
display: flex; gap: 10px; align-items: flex-start;
|
||||
}
|
||||
.banner .note { margin: 0; font-size: 14px; }
|
||||
|
||||
/* ---------------------------------------------------------------- layout */
|
||||
main { padding: 8px 24px 40px; max-width: 1480px; margin: 0 auto; }
|
||||
section { margin-top: 28px; }
|
||||
section > h2 {
|
||||
font-size: 13px; font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase;
|
||||
color: var(--text-2); margin: 0 0 12px;
|
||||
}
|
||||
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 16px; margin-top: 16px; }
|
||||
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; }
|
||||
.card {
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
|
||||
padding: 16px 18px; margin: 0; min-width: 0;
|
||||
}
|
||||
.card h3 { margin: 0 0 2px; font-size: 15px; font-weight: 600; }
|
||||
.card .sub { color: var(--text-2); font-size: 13px; margin: 0 0 12px; }
|
||||
.row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.spacer { flex: 1; }
|
||||
.muted { color: var(--text-2); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* ---------------------------------------------------------------- stat tiles */
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
|
||||
.tile .label { color: var(--text-2); font-size: 13px; display: flex; align-items: center; gap: 6px; }
|
||||
.tile .value { font-size: 30px; font-weight: 600; line-height: 1.15; margin-top: 2px; }
|
||||
.tile .value small { font-size: 15px; font-weight: 600; margin-left: 2px; }
|
||||
.tile .detail { color: var(--text-2); font-size: 13px; margin-top: 4px; }
|
||||
.key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; flex: none; }
|
||||
.key.line { width: 14px; height: 2px; border-radius: 1px; }
|
||||
|
||||
/* ---------------------------------------------------------------- meters */
|
||||
.meter { height: 8px; border-radius: 4px; background: var(--meter-track); overflow: hidden; margin-top: 8px; }
|
||||
.meter > span { display: block; height: 100%; border-radius: 4px; background: var(--meter-fill); width: 0; transition: width .4s; }
|
||||
.meter.cpu > span { background: var(--cpu); }
|
||||
.meter.gpu > span { background: var(--gpu); }
|
||||
.meter.top > span { background: var(--top); }
|
||||
.meter.warning > span { background: var(--warning); }
|
||||
.meter.critical > span { background: var(--critical); }
|
||||
|
||||
/* ---------------------------------------------------------------- controls */
|
||||
.seg {
|
||||
display: inline-flex; background: var(--surface-2); border-radius: 8px; padding: 3px; gap: 2px;
|
||||
border: 1px solid var(--border); flex-wrap: wrap;
|
||||
}
|
||||
.seg label { position: relative; }
|
||||
.seg input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
|
||||
.seg span {
|
||||
display: block; padding: 6px 14px; border-radius: 6px; color: var(--text-2); cursor: pointer;
|
||||
white-space: nowrap; user-select: none;
|
||||
}
|
||||
.seg label:hover span { color: var(--text); background: var(--raised); }
|
||||
.seg input:checked + span { background: var(--select-bg); color: var(--select-text); font-weight: 600; }
|
||||
.seg input:focus-visible + span { outline: 2px solid var(--text); outline-offset: 1px; }
|
||||
.seg.busy { opacity: 0.6; pointer-events: none; }
|
||||
|
||||
.btn {
|
||||
border: 1px solid var(--border); background: var(--surface-2); border-radius: 8px;
|
||||
padding: 7px 14px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;
|
||||
}
|
||||
.btn:hover:not(:disabled) { background: var(--raised); }
|
||||
.btn:disabled { opacity: 0.5; cursor: default; }
|
||||
.btn:focus-visible { outline: 2px solid var(--text); outline-offset: 1px; }
|
||||
select {
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- status */
|
||||
.pill {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px;
|
||||
background: var(--surface-2); border: 1px solid var(--border); font-size: 13px; white-space: nowrap;
|
||||
}
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-2); flex: none; }
|
||||
.dot.good { background: var(--good); }
|
||||
.dot.busy { background: var(--cpu); }
|
||||
.dot.warning { background: var(--warning); }
|
||||
.dot.critical { background: var(--critical); }
|
||||
.note { display: flex; gap: 8px; align-items: flex-start; font-size: 13px; margin-top: 10px; }
|
||||
.note svg { flex: none; width: 16px; height: 16px; margin-top: 1px; }
|
||||
.note.warning svg { color: var(--warning); }
|
||||
.note.critical svg { color: var(--critical); }
|
||||
.note.info svg { color: var(--text-2); }
|
||||
|
||||
/* ---------------------------------------------------------------- fan groups */
|
||||
.fan-head { display: flex; align-items: baseline; gap: 8px; }
|
||||
.fan-duty { font-size: 30px; font-weight: 600; line-height: 1.1; }
|
||||
.fan-ports { display: flex; gap: 14px; margin-top: 10px; color: var(--text-2); font-size: 13px; flex-wrap: wrap; }
|
||||
.fan-ports b { color: var(--text); font-weight: 600; }
|
||||
.profile-desc { color: var(--text-2); margin: 10px 0 0; font-size: 13px; }
|
||||
|
||||
/* ---------------------------------------------------------------- lighting */
|
||||
.zone .status { color: var(--text-2); font-size: 13px; margin-top: 10px; min-height: 19px; }
|
||||
|
||||
/* ---------------------------------------------------------------- AI */
|
||||
.backends { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
|
||||
.choice {
|
||||
position: relative; display: block; border: 1px solid var(--border); border-radius: 10px;
|
||||
padding: 12px 14px; background: var(--surface-2); cursor: pointer;
|
||||
}
|
||||
.choice:hover { background: var(--raised); }
|
||||
.choice input[type=radio] { position: absolute; opacity: 0; }
|
||||
.choice:has(input[type=radio]:checked) { border-color: var(--text); box-shadow: inset 0 0 0 1px var(--text); }
|
||||
.choice:has(input[type=radio]:focus-visible) { outline: 2px solid var(--text); outline-offset: 2px; }
|
||||
.choice .name { font-weight: 600; display: flex; align-items: center; gap: 8px; }
|
||||
.choice .what { color: var(--text-2); font-size: 13px; margin-top: 2px; }
|
||||
.choice .state { margin-top: 8px; }
|
||||
.choice select { margin-top: 8px; max-width: 100%; }
|
||||
.check {
|
||||
margin-left: auto; width: 18px; height: 18px; border-radius: 50%; border: 2px solid var(--axis);
|
||||
display: inline-grid; place-items: center;
|
||||
}
|
||||
.choice:has(input[type=radio]:checked) .check { border-color: var(--text); background: var(--text); }
|
||||
.choice:has(input[type=radio]:checked) .check::after {
|
||||
content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--surface);
|
||||
}
|
||||
.backends.busy { opacity: 0.6; pointer-events: none; }
|
||||
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 12px 0 0; font-size: 13px; }
|
||||
.kv dt { color: var(--text-2); }
|
||||
.kv dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.live { margin-top: 14px; padding: 12px; border-radius: 8px; background: var(--surface-2); }
|
||||
.live .meter > span { background: var(--cpu); }
|
||||
.speeds { display: flex; gap: 28px; margin-top: 14px; flex-wrap: wrap; }
|
||||
.speeds .value { font-size: 24px; font-weight: 600; }
|
||||
.speeds .label { color: var(--text-2); font-size: 13px; }
|
||||
code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; }
|
||||
|
||||
/* ---------------------------------------------------------------- tables */
|
||||
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
th { text-align: left; font-weight: 600; color: var(--text-2); padding: 6px 8px; border-bottom: 1px solid var(--axis); }
|
||||
td { padding: 6px 8px; border-bottom: 1px solid var(--grid); }
|
||||
td.r, th.r { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
|
||||
/* ---------------------------------------------------------------- charts */
|
||||
.chart-head { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
|
||||
.chart-head h3 { margin: 0; }
|
||||
.legend { display: flex; gap: 14px; flex-wrap: wrap; color: var(--text-2); font-size: 13px; margin-top: 4px; }
|
||||
.legend span { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.table-toggle { margin-left: auto; font-size: 12.5px; padding: 4px 10px; }
|
||||
.plot { position: relative; margin-top: 10px; }
|
||||
.plot svg { display: block; width: 100%; height: 210px; overflow: visible; touch-action: none; }
|
||||
.plot .grid line { stroke: var(--grid); stroke-width: 1; }
|
||||
.plot .baseline { stroke: var(--axis); stroke-width: 1; }
|
||||
.plot .tick { fill: var(--text-2); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.plot .ref { stroke: var(--axis); stroke-width: 1; }
|
||||
.plot .ref-label { fill: var(--text-2); font-size: 11px; }
|
||||
.plot .series-line { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
|
||||
.plot .series-area { opacity: 0.12; }
|
||||
.plot .cross { stroke: var(--text-2); stroke-width: 1; }
|
||||
.plot .marker { stroke: var(--surface); stroke-width: 2; }
|
||||
.plot .end-label { fill: var(--text); font-size: 12px; font-weight: 600; }
|
||||
.plot.stale { opacity: 0.45; }
|
||||
.chart-table { margin-top: 10px; max-height: 260px; overflow: auto; }
|
||||
|
||||
.tooltip {
|
||||
position: fixed; z-index: 20; pointer-events: none; min-width: 150px;
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 8px 10px; font-size: 13px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
.tooltip .when { color: var(--text-2); margin-bottom: 4px; }
|
||||
.tooltip .tip-row { display: flex; align-items: center; gap: 8px; }
|
||||
.tooltip .tip-row b { font-weight: 600; min-width: 56px; font-variant-numeric: tabular-nums; }
|
||||
.tooltip .tip-row span:last-child { color: var(--text-2); }
|
||||
|
||||
footer { color: var(--text-2); font-size: 12.5px; padding: 0 24px 28px; max-width: 1480px; margin: 0 auto; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.masthead { padding: 10px 14px; gap: 12px; }
|
||||
main { padding: 8px 14px 32px; }
|
||||
.hero-value { font-size: 36px; }
|
||||
.grid2 { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html { scroll-behavior: auto; }
|
||||
.meter > span { transition: none; }
|
||||
}
|
||||
|
||||
/* the server card sits at the top of its row instead of stretching beside the chart */
|
||||
#ai-active { align-self: start; }
|
||||
.pills { display: inline-flex; gap: 6px; flex-wrap: wrap; }
|
||||
Reference in new issue
Block a user