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