- readings.py: PowerReadings.total now sums the known parts (None only when nothing is known), with a complete property saying whether it under-counts; the snapshot exposes it as partial and the web UI marks it with a tilde. - display/service.py: telemetry older than 15 s is drawn as -- instead of re-rendering frozen readings as if they were current. - sensors.py: Commander PRO last-known RPMs expire after 10 s instead of feeding the power model forever (empty list = unknown); a runtime MSR failure backs off 15 s instead of re-opening PawnIO every second; GPU NVML reconnects back off 10 s instead of nvmlInit() every second, and the sample-buffer timestamp resets on a driver-reset reconnect. - control.py: CpuTemperature read failures back off 15 s instead of churning the MSR handle every poll.
909 lines
39 KiB
Python
909 lines
39 KiB
Python
"""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:
|
|
# A runtime MSR failure usually means the PawnIO device is gone: pause before re-opening
|
|
# it, or a broken driver costs a heavy CreateFile+DeviceIoControl every second.
|
|
RETRY_SECONDS = 15.0
|
|
|
|
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
|
|
self._next_pkg_attempt = time.monotonic() + self.RETRY_SECONDS
|
|
return Readings(temp=temp, load=load, clock=clock, power=power)
|
|
|
|
|
|
# ----------------------------------------------------------------------------- GPU
|
|
|
|
class GpuSensors:
|
|
# Pause between re-open attempts while the GPU/driver is gone, like CpuSensors'.
|
|
RECONNECT_SECONDS = 10.0
|
|
|
|
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._next_connect = 0.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:
|
|
now = time.monotonic()
|
|
if now < self._next_connect:
|
|
return Readings()
|
|
self._next_connect = now + self.RECONNECT_SECONDS
|
|
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
|
|
self._last_sample_ts = 0 # the driver's sample buffer restarts with the driver
|
|
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
|
|
# Last known RPMs must not feed the power model forever: after this long without a
|
|
# successful read the fan speeds are unknown, not merely stale.
|
|
RPM_STALE = 10.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._read_at = 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]
|
|
self._read_at = time.monotonic()
|
|
return {p + 1: rpm for p, rpm in self.rpm.items()}
|
|
|
|
def _fresh_rpms(self) -> bool:
|
|
return time.monotonic() - self._read_at <= self.RPM_STALE
|
|
|
|
def read(self) -> list[int]:
|
|
"""RPM of each connected fan; empty while the device is lost or held by other software."""
|
|
with self._lock:
|
|
if self.controlled:
|
|
return list(self.rpm.values()) if self._fresh_rpms() else []
|
|
return self._read()
|
|
|
|
def _read(self) -> list[int]:
|
|
now = time.monotonic()
|
|
if now >= self._next_check:
|
|
self._next_check = now + self.RECHECK
|
|
try:
|
|
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})")
|
|
except Exception as e:
|
|
# Ownership cannot be established (e.g. process enumeration failed): give the
|
|
# device up rather than risk swapped replies, and retry on the next check.
|
|
self.close()
|
|
self._say(f"ownership check failed ({e}); device released, retrying in {self.RECHECK:.0f} s")
|
|
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]
|
|
self._read_at = time.monotonic()
|
|
except Exception as e:
|
|
self.close()
|
|
self._say(f"lost ({e}), retrying in {self.RECHECK:.0f} s")
|
|
if not self._fresh_rpms():
|
|
return []
|
|
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)
|