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 @@
|
||||
"""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
|
||||
Reference in new issue
Block a user