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,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())
|
||||
Reference in new issue
Block a user