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 @@
|
||||
"""Lighting: Lighting Node CORE fan LEDs, Dominator DDR5 RAM and ASUS GPU LEDs."""
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Opt-in temperature lighting and calibrated QL120 side chase on the Lighting Node CORE.
|
||||
|
||||
Header 1 of the CORE holds the six QL120 case fans (34 LEDs each, 204 in total); header 2 is
|
||||
left alone. The node is driven directly over HID (see lighting_node.py), so no OpenRGB is needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.lighting_node import MAX_LEDS, LightingNodeBusy, LightingNodeCore
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_RETRY_SECONDS = 10.0
|
||||
_FAN_TOP_RIGHT = (17, 17, 17, 20, 11, 20)
|
||||
_CHASE_EASE_SECONDS = 1.0
|
||||
# The CORE shares a USB 2.0 hub with the LCD; flooding it hung the LCD firmware, so cap
|
||||
# frames at ~22/s and let a fast chase advance more than one LED per frame instead.
|
||||
MIN_CHASE_FRAME_SECONDS = 0.045
|
||||
CHASE_POLL_SECONDS = 0.02
|
||||
|
||||
|
||||
def _side_chase_route(cpu_side: bool) -> tuple[int, ...]:
|
||||
fans = (4, 5, 3) if cpu_side else (0, 1, 2) # bottom, middle, top; zero-based chain
|
||||
# Clock positions 0 and 11 flank 12; 5 and 6 flank 6.
|
||||
segments = (
|
||||
(0, range(12)),
|
||||
(1, range(5, -1, -1)),
|
||||
(2, range(6, 18)),
|
||||
(1, range(11, 5, -1)),
|
||||
)
|
||||
route = []
|
||||
for position, clock_positions in segments:
|
||||
for clock in clock_positions:
|
||||
if not cpu_side:
|
||||
clock = 11 - clock
|
||||
led = 10 + (_FAN_TOP_RIGHT[fans[position]] - 10 + clock) % 12
|
||||
route.append(fans[position] * 34 + led)
|
||||
return tuple(route)
|
||||
|
||||
|
||||
_SIDE_CHASE_ROUTES = (_side_chase_route(True), _side_chase_route(False))
|
||||
SIDE_CHASE_CYCLE_STEPS = len(_SIDE_CHASE_ROUTES[0])
|
||||
# Bottom fan at 6 o'clock; the top fan reaches 12 o'clock half a cycle later.
|
||||
SIDE_CHASE_BOTTOM_STEP = 6
|
||||
_LEDS_PER_SIDE = 3 * 34 # chain fans 0-2 are the GPU side, 3-5 the CPU side
|
||||
|
||||
|
||||
def side_chase_color(strength: float) -> tuple[int, int, int]:
|
||||
"""Blend the dark-red ring base into the warm-orange chase head (strength 0-1)."""
|
||||
return (round(24 + 231 * strength), round(48 * strength), 0)
|
||||
|
||||
|
||||
def side_chase_frame(step: int) -> list[tuple[int, int, int]]:
|
||||
"""Render mirrored sides, with each inner ring reflected left-to-right."""
|
||||
colors = [(48, 0, 0) if index % 34 < 10 else (24, 0, 0) for index in range(204)]
|
||||
for route in _SIDE_CHASE_ROUTES:
|
||||
for age in range(5):
|
||||
strength = (5 - age) / 5
|
||||
color = side_chase_color(strength)
|
||||
outer = route[(step - age) % len(route)]
|
||||
fan, local = divmod(outer, 34)
|
||||
right_of_top = _FAN_TOP_RIGHT[fan]
|
||||
clock = (local - right_of_top) % 12
|
||||
inner = fan * 34 + 22 + (right_of_top - 10 + 11 - clock) % 12
|
||||
colors[outer] = colors[inner] = color
|
||||
return colors
|
||||
|
||||
|
||||
class ChaseTiming:
|
||||
"""Elapsed-time chase phase with power-dependent speed and gradual acceleration."""
|
||||
|
||||
def __init__(self, step_seconds: float = 0.15, fast_step_seconds: float = 0.025,
|
||||
watts: tuple[float, float] = (150.0, 550.0)):
|
||||
for step in (step_seconds, fast_step_seconds):
|
||||
if not math.isfinite(step) or step < 0.02:
|
||||
raise ValueError("Chase step must be finite and at least 0.02 seconds")
|
||||
if fast_step_seconds > step_seconds:
|
||||
raise ValueError("Fast chase step can't be slower than the idle step")
|
||||
if not all(math.isfinite(w) for w in watts) or watts[1] <= watts[0]:
|
||||
raise ValueError("Chase power range must be finite and increasing")
|
||||
self.step_seconds = step_seconds
|
||||
self.fast_step_seconds = fast_step_seconds
|
||||
self.watts = watts
|
||||
self._lock = threading.Lock()
|
||||
self._power: float | None = None
|
||||
self.reset()
|
||||
|
||||
def reset(self, phase: float = 0.0) -> None:
|
||||
with self._lock:
|
||||
self.last_time: float | None = None
|
||||
self.phase = phase
|
||||
self.rate = 0.0
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
with self._lock:
|
||||
self._power = total_watts
|
||||
|
||||
def rate_for(self, total_watts: float | None) -> float:
|
||||
slow, fast = 1 / self.step_seconds, 1 / self.fast_step_seconds
|
||||
if total_watts is None or not math.isfinite(total_watts):
|
||||
return slow
|
||||
lo, hi = self.watts
|
||||
t = min(1.0, max(0.0, (total_watts - lo) / (hi - lo)))
|
||||
return slow + t * (fast - slow)
|
||||
|
||||
def sample(self, now: float) -> tuple[float, float]:
|
||||
with self._lock:
|
||||
target = self.rate_for(self._power)
|
||||
if self.last_time is None:
|
||||
self.last_time, self.rate = now, target
|
||||
dt = max(0.0, now - self.last_time)
|
||||
self.last_time = max(now, self.last_time)
|
||||
self.rate += (target - self.rate) * min(1.0, dt / _CHASE_EASE_SECONDS)
|
||||
self.phase += self.rate * dt
|
||||
return self.phase, self.rate
|
||||
|
||||
def step(self, now: float) -> int:
|
||||
return int(self.sample(now)[0])
|
||||
|
||||
|
||||
class RGBLighting:
|
||||
"""Run a selected pattern on the Lighting Node CORE; hand it back to its hardware effect when off."""
|
||||
|
||||
def __init__(self, theme: Theme, chase_step_seconds: float = 0.15, chase_fast_step_seconds: float = 0.025,
|
||||
chase_watts: tuple[float, float] = (150.0, 550.0),
|
||||
node_factory: Callable[[], LightingNodeCore] = LightingNodeCore, *,
|
||||
chase_timing: ChaseTiming | None = None):
|
||||
"""The side chase runs at `chase_step_seconds` per LED at or below the first
|
||||
`chase_watts` total system power, speeding up to `chase_fast_step_seconds` at the second."""
|
||||
self._owns_chase_timing = chase_timing is None
|
||||
self._chase_timing = (chase_timing if chase_timing is not None
|
||||
else ChaseTiming(chase_step_seconds, chase_fast_step_seconds, chase_watts))
|
||||
self.theme = theme
|
||||
self.chase_step_seconds = chase_step_seconds
|
||||
self.chase_fast_step_seconds = chase_fast_step_seconds
|
||||
self.chase_watts = chase_watts
|
||||
self.node: LightingNodeCore | None = None
|
||||
self.status = "off"
|
||||
self._node_factory = node_factory
|
||||
self._retry_at = 0.0
|
||||
self._last_error: str | None = None
|
||||
self._pattern: str | None = None
|
||||
self._last_chase_step: int | None = None
|
||||
self._last_frame_time = -math.inf
|
||||
self._cpu_temp: float | None = None
|
||||
self._gpu_temp: float | None = None
|
||||
self._power: float | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
with self._lock:
|
||||
self._cpu_temp = cpu_temp
|
||||
self._gpu_temp = gpu_temp
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
with self._lock:
|
||||
self._power = total_watts
|
||||
self._chase_timing.set_power(total_watts)
|
||||
|
||||
def chase_rate(self, total_watts: float | None) -> float:
|
||||
"""LEDs per second for a given total system power (idle pace when unknown)."""
|
||||
return self._chase_timing.rate_for(total_watts)
|
||||
|
||||
def run(self, stop: threading.Event, temperature_enabled: threading.Event,
|
||||
side_chase_enabled: threading.Event) -> None:
|
||||
"""Own all Lighting Node access on one worker, independent of LCD and sensor timing."""
|
||||
try:
|
||||
while not stop.is_set():
|
||||
with self._lock:
|
||||
cpu_temp, gpu_temp = self._cpu_temp, self._gpu_temp
|
||||
self.update(cpu_temp, temperature_enabled.is_set(), side_chase=side_chase_enabled.is_set(),
|
||||
gpu_temp=gpu_temp)
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def update(self, cpu_temp: float | None, enabled: bool, *, side_chase: bool = False,
|
||||
gpu_temp: float | None = None) -> None:
|
||||
pattern = "side-chase" if side_chase else "temperature" if enabled else None
|
||||
if pattern != self._pattern:
|
||||
self._pattern = pattern
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset()
|
||||
self._last_chase_step = None
|
||||
if pattern is None:
|
||||
self.close()
|
||||
if pattern is None:
|
||||
return
|
||||
if self.node is None:
|
||||
if time.monotonic() < self._retry_at:
|
||||
return
|
||||
try:
|
||||
node = self._node_factory()
|
||||
node.open()
|
||||
except LightingNodeBusy as e:
|
||||
self._fail(e, str(e))
|
||||
return
|
||||
except Exception as e:
|
||||
self._fail(e, "Lighting Node CORE unavailable")
|
||||
return
|
||||
self.node = node
|
||||
self._last_error = None
|
||||
log.info("Lighting Node CORE opened (firmware %s)", node.firmware)
|
||||
try:
|
||||
if pattern == "side-chase":
|
||||
self._apply_side_chase()
|
||||
else:
|
||||
self._apply_temperature(cpu_temp, gpu_temp)
|
||||
self.node.keepalive()
|
||||
except Exception as e:
|
||||
self._fail(e, "Lighting Node CORE connection lost")
|
||||
|
||||
def close(self) -> None:
|
||||
"""Hand the fans back to the node's own effect."""
|
||||
node, self.node = self.node, None
|
||||
self._last_chase_step = None
|
||||
if node is not None:
|
||||
try:
|
||||
node.close()
|
||||
except Exception:
|
||||
log.exception("Couldn't release the Lighting Node CORE")
|
||||
self._set_status("off")
|
||||
|
||||
def _apply_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
"""Colour each side's three fans by its own part's temperature, like the LCD gauges."""
|
||||
assert self.node is not None
|
||||
if cpu_temp is None and gpu_temp is None:
|
||||
self._set_status("Temperature lighting waiting for temperatures")
|
||||
return
|
||||
# A side whose sensor is unavailable borrows the other side's reading.
|
||||
cpu = cpu_temp if cpu_temp is not None else gpu_temp
|
||||
gpu = gpu_temp if gpu_temp is not None else cpu_temp
|
||||
th = self.theme
|
||||
gpu_color = th.level_color(gpu, th.temp_warn, th.temp_hot)
|
||||
cpu_color = th.level_color(cpu, th.temp_warn, th.temp_hot)
|
||||
self.node.show(0, [gpu_color] * _LEDS_PER_SIDE + [cpu_color] * (MAX_LEDS - _LEDS_PER_SIDE))
|
||||
self._set_status(f"Temperature lighting active (GPU {gpu:.0f} \u00b0C, CPU {cpu:.0f} \u00b0C)")
|
||||
|
||||
def _apply_side_chase(self) -> None:
|
||||
assert self.node is not None
|
||||
with self._lock:
|
||||
power = self._power
|
||||
now = time.monotonic()
|
||||
step = self._chase_timing.step(now)
|
||||
if step != self._last_chase_step and now - self._last_frame_time >= MIN_CHASE_FRAME_SECONDS:
|
||||
self.node.show(0, side_chase_frame(step))
|
||||
self._last_chase_step = step
|
||||
self._last_frame_time = now
|
||||
watts = "" if power is None else f" at {power:.0f} W"
|
||||
self._set_status(f"Red side chase active ({1000 / self._chase_timing.rate:.0f} ms/LED{watts})")
|
||||
|
||||
def _fail(self, error: Exception, status: str) -> None:
|
||||
node, self.node = self.node, None
|
||||
if node is not None:
|
||||
try:
|
||||
node.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._last_chase_step = None
|
||||
self._retry_at = time.monotonic() + _RETRY_SECONDS
|
||||
self._set_status(status)
|
||||
message = str(error) or type(error).__name__
|
||||
if message != self._last_error:
|
||||
log.warning("RGB lighting unavailable: %s", message, exc_info=not isinstance(error, LightingNodeBusy))
|
||||
self._last_error = message
|
||||
|
||||
def _set_status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
self.status = status
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Direct ASUS RTX 4090 lighting through NVIDIA's I2C API (no USB traffic)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable, Protocol
|
||||
|
||||
from kurgan.lighting.case_fans import (
|
||||
CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming,
|
||||
SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color,
|
||||
)
|
||||
from kurgan.telemetry.sensors import _process_names, corsair_software_running
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
Rgb = tuple[int, int, int]
|
||||
_U8, _U32 = ctypes.c_uint8, ctypes.c_uint32
|
||||
_GPU_DEVICE = 0x268410DE
|
||||
_GPU_SUBSYSTEM = 0x89321043
|
||||
_CONTROLLER_ADDRESS = 0x67
|
||||
_FIRMWARE = ("AUMA0-E6K5-0107", "AUMA0-E6K5-1110", "AUMA0-E6K5-1111")
|
||||
|
||||
|
||||
class _I2cInfo(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("version", _U32), ("display_mask", _U32),
|
||||
("ddc", _U8), ("address", _U8),
|
||||
("register", ctypes.POINTER(_U8)), ("register_size", _U32),
|
||||
("data", ctypes.POINTER(_U8)), ("size", _U32),
|
||||
("speed", _U32), ("speed_khz", _U32),
|
||||
("port", _U8), ("port_set", _U32),
|
||||
]
|
||||
|
||||
|
||||
class NvidiaI2c:
|
||||
def __init__(self) -> None:
|
||||
name = "nvapi64.dll" if ctypes.sizeof(ctypes.c_void_p) == 8 else "nvapi.dll"
|
||||
self._dll = ctypes.CDLL(os.path.join(os.environ["SystemRoot"], "System32", name))
|
||||
self._query = self._dll.nvapi_QueryInterface
|
||||
self._query.argtypes = [_U32]
|
||||
self._query.restype = ctypes.c_void_p
|
||||
self._check(self._function(0x0150E828)(), "Initialize")
|
||||
enum = self._function(0xE5AC921F, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_int32))
|
||||
identity = self._function(0x2DDFB66E, ctypes.c_void_p, *([ctypes.POINTER(_U32)] * 4))
|
||||
handles = (ctypes.c_void_p * 64)()
|
||||
count = ctypes.c_int32()
|
||||
self._check(enum(handles, ctypes.byref(count)), "EnumPhysicalGPUs")
|
||||
matches = []
|
||||
for handle in handles[:count.value]:
|
||||
device, subsystem, revision, extended = (_U32() for _ in range(4))
|
||||
self._check(identity(handle, ctypes.byref(device), ctypes.byref(subsystem),
|
||||
ctypes.byref(revision), ctypes.byref(extended)), "GetPCIIdentifiers")
|
||||
if device.value == _GPU_DEVICE and subsystem.value == _GPU_SUBSYSTEM:
|
||||
matches.append(handle)
|
||||
if len(matches) != 1:
|
||||
raise OSError(f"Expected one ASUS RTX 4090 (2684:8932), found {len(matches)}")
|
||||
self._handle = matches[0]
|
||||
arguments = (ctypes.c_void_p, ctypes.POINTER(_I2cInfo), ctypes.POINTER(_U32))
|
||||
self._read = self._function(0x4D7B0709, *arguments)
|
||||
self._write = self._function(0x283AC65A, *arguments)
|
||||
|
||||
def _function(self, identifier: int, *arguments):
|
||||
address = self._query(identifier)
|
||||
if not address:
|
||||
raise OSError(f"NVIDIA API function 0x{identifier:08X} unavailable")
|
||||
return ctypes.CFUNCTYPE(ctypes.c_int32, *arguments)(address)
|
||||
|
||||
@staticmethod
|
||||
def _check(status: int, operation: str) -> None:
|
||||
if status != 0:
|
||||
raise OSError(f"NVIDIA {operation} failed (status {status})")
|
||||
|
||||
def transfer(self, command: int, data: bytes, *, read: bool = False) -> bytes:
|
||||
register = (_U8 * 1)(command)
|
||||
buffer = (_U8 * len(data)).from_buffer_copy(data)
|
||||
info = _I2cInfo()
|
||||
info.version = ctypes.sizeof(_I2cInfo) | (3 << 16)
|
||||
info.address = _CONTROLLER_ADDRESS << 1
|
||||
info.register, info.register_size = register, 1
|
||||
info.data, info.size = buffer, len(data)
|
||||
info.speed = 0xFFFF
|
||||
info.port, info.port_set = 1, 1
|
||||
unknown = _U32()
|
||||
operation = self._read if read else self._write
|
||||
self._check(operation(self._handle, ctypes.byref(info), ctypes.byref(unknown)), "I2C transfer")
|
||||
if info.size != len(data):
|
||||
raise OSError(f"NVIDIA I2C transferred {info.size} bytes; expected {len(data)}")
|
||||
return bytes(buffer)
|
||||
|
||||
|
||||
class AsusGpuLeds:
|
||||
def __init__(self, bus_factory: Callable[[], NvidiaI2c] = NvidiaI2c) -> None:
|
||||
self._factory = bus_factory
|
||||
self._bus: NvidiaI2c | None = None
|
||||
self.led_count = 0
|
||||
self._original_direct = 0
|
||||
self._original_colors: tuple[Rgb, ...] = ()
|
||||
self._shown: tuple[Rgb, ...] | None = None
|
||||
self._claimed = False
|
||||
|
||||
def _select(self, register: int) -> None:
|
||||
assert self._bus is not None
|
||||
self._bus.transfer(0, register.to_bytes(2, "big"))
|
||||
|
||||
def _read_register(self, register: int) -> int:
|
||||
self._select(register)
|
||||
assert self._bus is not None
|
||||
return self._bus.transfer(0x81, bytes(1), read=True)[0]
|
||||
|
||||
def _write_register(self, register: int, value: int) -> None:
|
||||
self._select(register)
|
||||
assert self._bus is not None
|
||||
self._bus.transfer(1, bytes((value,)))
|
||||
|
||||
def open(self) -> None:
|
||||
if any("lightingservice" in name or "armoury" in name or "aura" in name
|
||||
for name in _process_names()):
|
||||
raise OSError("GPU lighting busy: exit ASUS lighting software")
|
||||
if corsair_software_running("ASUS ROG STRIX GeForce RTX 4090 Gaming OC", fan_tools=False):
|
||||
raise OSError("GPU lighting busy: exit other RGB software")
|
||||
self._bus = self._factory()
|
||||
version = bytes(self._read_register(0x1000 + i) for i in range(16)).split(b"\0", 1)[0]
|
||||
if version.decode("ascii", errors="replace") not in _FIRMWARE:
|
||||
raise OSError(f"Unsupported GPU LED firmware: {version!r}")
|
||||
self.led_count = self._read_register(0x1C03)
|
||||
if not 1 <= self.led_count <= 32:
|
||||
raise OSError(f"Unexpected GPU LED count: {self.led_count}")
|
||||
self._original_direct = self._read_register(0x8020)
|
||||
if self._original_direct not in (0, 1):
|
||||
raise OSError(f"Unexpected GPU direct-mode state: {self._original_direct}")
|
||||
raw = [self._read_register(0x8100 + i) for i in range(self.led_count * 3)]
|
||||
self._original_colors = tuple((raw[i], raw[i + 2], raw[i + 1])
|
||||
for i in range(0, len(raw), 3))
|
||||
log.info("GPU lighting identified: %s, %d LEDs", version.decode("ascii"), self.led_count)
|
||||
|
||||
def _write_colors(self, colors: tuple[Rgb, ...], previous: tuple[Rgb, ...] | None) -> None:
|
||||
assert self._bus is not None
|
||||
for led, (red, green, blue) in enumerate(colors):
|
||||
if previous is not None and colors[led] == previous[led]:
|
||||
continue
|
||||
self._select(0x8100 + led * 3)
|
||||
self._bus.transfer(3, bytes((3, red, blue, green)))
|
||||
|
||||
def show_frame(self, colors: tuple[Rgb, ...]) -> None:
|
||||
if len(colors) != self.led_count or any(
|
||||
len(color) != 3 or any(type(value) is not int or not 0 <= value <= 255 for value in color)
|
||||
for color in colors):
|
||||
raise ValueError("GPU frame must contain one valid RGB triplet per LED")
|
||||
self._claimed = True
|
||||
self._write_colors(colors, self._shown)
|
||||
if self._shown is None:
|
||||
self._write_register(0x8020, 1)
|
||||
self._write_register(0x80A0, 1)
|
||||
self._shown = colors
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
if self._claimed:
|
||||
try:
|
||||
self._write_colors(self._original_colors, None)
|
||||
finally:
|
||||
self._write_register(0x8020, self._original_direct)
|
||||
self._write_register(0x80A0, 1)
|
||||
finally:
|
||||
self._bus = None
|
||||
self._shown = None
|
||||
self._claimed = False
|
||||
|
||||
|
||||
def gpu_chase_frame(phase: float, led_count: int) -> tuple[Rgb, ...]:
|
||||
if led_count < 1:
|
||||
raise ValueError("GPU must have at least one LED")
|
||||
if led_count == 1:
|
||||
return (side_chase_color(1),)
|
||||
route = tuple(range(led_count - 1, -1, -1)) + tuple(range(1, led_count - 1))
|
||||
step = math.floor((phase - SIDE_CHASE_BOTTOM_STEP) * len(route) / SIDE_CHASE_CYCLE_STEPS)
|
||||
colors = [side_chase_color(0)] * led_count
|
||||
for age in range(min(4, led_count - 1), -1, -1):
|
||||
colors[route[(step - age) % len(route)]] = side_chase_color((5 - age) / 5)
|
||||
return tuple(colors)
|
||||
|
||||
|
||||
class _GpuDriver(Protocol):
|
||||
led_count: int
|
||||
def open(self) -> None: ...
|
||||
def show_frame(self, colors: tuple[Rgb, ...]) -> None: ...
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
class GpuLighting:
|
||||
def __init__(self, chase_timing: ChaseTiming,
|
||||
driver_factory: Callable[[], _GpuDriver] = AsusGpuLeds) -> None:
|
||||
self.status = "off"
|
||||
self._clock = chase_timing
|
||||
self._factory = driver_factory
|
||||
self._driver: _GpuDriver | None = None
|
||||
self._retry_at = 0.0
|
||||
self._last_frame_at = -math.inf
|
||||
self._last_frame: tuple[Rgb, ...] | None = None
|
||||
|
||||
def _status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
log.info("GPU lighting: %s", status)
|
||||
self.status = status
|
||||
|
||||
def close(self) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
self._last_frame = None
|
||||
self._last_frame_at = -math.inf
|
||||
if driver is not None:
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't restore GPU lighting state")
|
||||
|
||||
def update(self, enabled: bool) -> None:
|
||||
if not enabled:
|
||||
self.close()
|
||||
self._status("off")
|
||||
return
|
||||
now = time.monotonic()
|
||||
if self._driver is None and now < self._retry_at:
|
||||
return
|
||||
try:
|
||||
if self._driver is None:
|
||||
self._driver = self._factory()
|
||||
self._driver.open()
|
||||
phase, _ = self._clock.sample(now)
|
||||
frame = gpu_chase_frame(phase, self._driver.led_count)
|
||||
if frame != self._last_frame and now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS:
|
||||
self._driver.show_frame(frame)
|
||||
self._last_frame, self._last_frame_at = frame, now
|
||||
self._status(f"Red chase active ({self._driver.led_count} LEDs)")
|
||||
except OSError as error:
|
||||
log.warning("GPU lighting unavailable: %s", error)
|
||||
self.close()
|
||||
self._retry_at = now + 10
|
||||
self._status(f"unavailable: {error}")
|
||||
|
||||
def run(self, stop: threading.Event, enabled: threading.Event) -> None:
|
||||
try:
|
||||
while not stop.is_set():
|
||||
self.update(enabled.is_set())
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
except Exception:
|
||||
log.exception("GPU lighting worker failed")
|
||||
self._status("worker stopped; check dashboard.log")
|
||||
finally:
|
||||
self.close()
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Corsair Lighting Node CORE (1B1C:0C1A) driven directly over Windows HID.
|
||||
|
||||
Each command is a 64-byte output report answered by a 16-byte input report whose first
|
||||
byte is 0 on success. LED colours go 50 at a time, one packet per colour channel, and only
|
||||
appear after a commit. The node returns to its stored hardware effect if it hears nothing
|
||||
for about 20 s in software mode, so `keepalive()` re-commits every few seconds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import time
|
||||
|
||||
from kurgan.telemetry.sensors import corsair_software_running
|
||||
from kurgan.hardware.hid import HidChannel, hid_device_paths
|
||||
|
||||
VID, PID = 0x1B1C, 0x0C1A
|
||||
OP_FIRMWARE, OP_DIRECT, OP_COMMIT, OP_PORT_STATE = 0x02, 0x32, 0x33, 0x38
|
||||
PORT_HARDWARE, PORT_SOFTWARE = 0x01, 0x02
|
||||
LEDS_PER_PACKET = 50
|
||||
MAX_LEDS = 204
|
||||
KEEPALIVE_SECONDS = 5.0
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_k32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
|
||||
_k32.CreateMutexW.restype = ctypes.c_void_p
|
||||
_k32.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
_ERROR_ALREADY_EXISTS = 183
|
||||
|
||||
|
||||
class LightingNodeBusy(OSError):
|
||||
pass
|
||||
|
||||
|
||||
def direct_packets(channel: int, colors: list[tuple[int, int, int]],
|
||||
previous: list[tuple[int, int, int]] | None = None) -> list[bytes]:
|
||||
"""Direct-colour packets for `colors`, skipping chunks whose colour channel is unchanged."""
|
||||
packets = []
|
||||
for start in range(0, len(colors), LEDS_PER_PACKET):
|
||||
chunk = colors[start:start + LEDS_PER_PACKET]
|
||||
old = None if previous is None else previous[start:start + LEDS_PER_PACKET]
|
||||
for component in range(3):
|
||||
values = bytes(color[component] for color in chunk)
|
||||
if old is not None and values == bytes(color[component] for color in old):
|
||||
continue
|
||||
packets.append(bytes((OP_DIRECT, channel, start, len(chunk), component)) + values)
|
||||
return packets
|
||||
|
||||
|
||||
class LightingNodeCore:
|
||||
"""Open with `with LightingNodeCore() as node:` and call `show()` or `keepalive()` regularly."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ch: HidChannel | None = None
|
||||
self.firmware = ""
|
||||
self._mutex: int | None = None
|
||||
self._software: set[int] = set()
|
||||
self._shown: dict[int, list[tuple[int, int, int]]] = {}
|
||||
self._last_commit = 0.0
|
||||
|
||||
def __enter__(self) -> "LightingNodeCore":
|
||||
self.open()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def open(self) -> None:
|
||||
if self.ch is not None:
|
||||
return
|
||||
if corsair_software_running("Corsair Lighting Node Core", fan_tools=False):
|
||||
raise LightingNodeBusy("Lighting Node CORE busy: exit iCUE, or disable OpenRGB's "
|
||||
"Corsair Lighting Node Core detector")
|
||||
ctypes.set_last_error(0)
|
||||
mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdLightingNode")
|
||||
if not mutex or ctypes.get_last_error() == _ERROR_ALREADY_EXISTS:
|
||||
if mutex:
|
||||
_k32.CloseHandle(mutex)
|
||||
raise LightingNodeBusy("Lighting Node CORE is in use by another dashboard process")
|
||||
self._mutex = mutex
|
||||
try:
|
||||
paths = hid_device_paths(VID, PID)
|
||||
if len(paths) != 1:
|
||||
raise OSError(f"Expected one Lighting Node CORE, found {len(paths)}")
|
||||
self.ch = HidChannel(paths[0], 64)
|
||||
reply = self._cmd(OP_FIRMWARE)
|
||||
self.firmware = ".".join(str(b) for b in reply[2:5])
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
if self.ch is not None:
|
||||
try:
|
||||
self.release()
|
||||
except OSError:
|
||||
pass
|
||||
self.ch.close()
|
||||
self.ch = None
|
||||
if self._mutex is not None:
|
||||
_k32.CloseHandle(self._mutex)
|
||||
self._mutex = None
|
||||
|
||||
def show(self, channel: int, colors: list[tuple[int, int, int]]) -> None:
|
||||
"""Display `colors` on header `channel` (0 or 1), sending only what changed."""
|
||||
if channel not in (0, 1) or not 0 < len(colors) <= MAX_LEDS:
|
||||
raise ValueError("Channel must be 0 or 1 with 1-204 LEDs")
|
||||
if channel not in self._software:
|
||||
self._cmd(OP_PORT_STATE, channel, PORT_SOFTWARE)
|
||||
self._software.add(channel)
|
||||
self._shown.pop(channel, None)
|
||||
previous = self._shown.get(channel)
|
||||
if previous is not None and len(previous) != len(colors):
|
||||
previous = None
|
||||
packets = direct_packets(channel, colors, previous)
|
||||
for packet in packets:
|
||||
self._cmd(*packet)
|
||||
if packets:
|
||||
self._commit()
|
||||
self._shown[channel] = list(colors)
|
||||
|
||||
def keepalive(self) -> None:
|
||||
if self._software and time.monotonic() - self._last_commit >= KEEPALIVE_SECONDS:
|
||||
self._commit()
|
||||
|
||||
def release(self) -> None:
|
||||
"""Hand every header back to the node's stored hardware effect."""
|
||||
for channel in sorted(self._software):
|
||||
self._cmd(OP_PORT_STATE, channel, PORT_HARDWARE)
|
||||
self._software.clear()
|
||||
self._shown.clear()
|
||||
|
||||
def _commit(self) -> None:
|
||||
self._cmd(OP_COMMIT, 0xFF)
|
||||
self._last_commit = time.monotonic()
|
||||
|
||||
def _cmd(self, *payload: int) -> bytes:
|
||||
ch = self.ch
|
||||
if ch is None:
|
||||
raise OSError("Lighting Node CORE is not open")
|
||||
ch.drain()
|
||||
ch.send(bytes(payload))
|
||||
reply = ch.read(300)
|
||||
if not reply or len(reply) < 2 or reply[1] != 0: # [report id, status, ...]
|
||||
raise OSError(f"Lighting Node CORE didn't accept command 0x{payload[0]:02X}")
|
||||
return reply
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Direct, temporary RGB control for Corsair Dominator Platinum DDR5 memory."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from typing import Callable, Generator, Protocol, Sequence
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.case_fans import (
|
||||
CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming,
|
||||
SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color,
|
||||
)
|
||||
from kurgan.telemetry.sensors import corsair_software_running
|
||||
|
||||
from kurgan.hardware import PAWNIO_DIR
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_PAWNIO_DLL = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "PawnIO", "PawnIOLib.dll")
|
||||
_SMBUS_MODULE = os.path.join(PAWNIO_DIR, "SmbusI801.bin")
|
||||
_ADDRESSES = (0x18, 0x19, 0x1A, 0x1B)
|
||||
_LED_COUNT = 12
|
||||
_KEEPALIVE_SECONDS = 5.0
|
||||
_RETRY_SECONDS = 10.0
|
||||
_BLACK = (0, 0, 0)
|
||||
_CELL = ctypes.c_uint64
|
||||
_STATUS_ACCESS_DENIED = 0xC0000022
|
||||
_STATUS_NO_SUCH_DEVICE = 0xC000000E
|
||||
_WAIT_OBJECT_0 = 0
|
||||
_WAIT_ABANDONED = 0x80
|
||||
Rgb = tuple[int, int, int]
|
||||
MemoryFrame = tuple[tuple[Rgb, ...], ...]
|
||||
|
||||
# Identification colours confirmed physical sticks 1-4 as addresses 0x18-0x1B.
|
||||
_CHASE_ROUTE = tuple((stick, led)
|
||||
for stick, inward in ((3, True), (2, False), (1, True),
|
||||
(0, False), (1, True), (2, False))
|
||||
for led in (range(6) if inward else range(5, -1, -1)))
|
||||
_CHASE_BOTTOM_STEP = 5
|
||||
|
||||
|
||||
def _solid_frame(color: Rgb) -> MemoryFrame:
|
||||
return ((color,) * _LED_COUNT,) * len(_ADDRESSES)
|
||||
|
||||
|
||||
def memory_chase_frame(step: int) -> MemoryFrame:
|
||||
"""Two mirrored heads travel up and down without repeating either end stick."""
|
||||
colors = [[side_chase_color(0)] * _LED_COUNT for _ in _ADDRESSES]
|
||||
for age in range(4, -1, -1):
|
||||
stick, led = _CHASE_ROUTE[(step - age) % len(_CHASE_ROUTE)]
|
||||
colors[stick][led] = colors[stick][_LED_COUNT - 1 - led] = side_chase_color((5 - age) / 5)
|
||||
return tuple(tuple(stick) for stick in colors)
|
||||
|
||||
|
||||
def memory_chase_step(fan_phase: float) -> int:
|
||||
return math.floor(_CHASE_BOTTOM_STEP
|
||||
+ (fan_phase - SIDE_CHASE_BOTTOM_STEP) * len(_CHASE_ROUTE) / SIDE_CHASE_CYCLE_STEPS)
|
||||
|
||||
|
||||
class MemoryLightingBusy(OSError):
|
||||
"""Raised when another RGB application owns Corsair memory lighting."""
|
||||
|
||||
|
||||
class _MemoryLightingDriver(Protocol):
|
||||
def open(self) -> None: ...
|
||||
|
||||
def show(self, color: tuple[int, int, int]) -> None: ...
|
||||
|
||||
def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
def _crc8(data: bytes) -> int:
|
||||
crc = 0
|
||||
for byte in data:
|
||||
crc ^= byte
|
||||
for _ in range(8):
|
||||
crc = ((crc << 1) ^ (0x07 if crc & 0x80 else 0)) & 0xFF
|
||||
return crc
|
||||
|
||||
|
||||
def _rgb_bytes(color: Sequence[object]) -> bytes:
|
||||
channels = [channel for channel in color if isinstance(channel, int) and not isinstance(channel, bool)]
|
||||
if (len(color) != 3 or len(channels) != 3
|
||||
or any(not 0 <= channel <= 255 for channel in channels)):
|
||||
raise ValueError("RGB channels must be integers from 0 to 255")
|
||||
return bytes(channels)
|
||||
|
||||
|
||||
def _led_packet(colors: Sequence[Sequence[object]]) -> bytes:
|
||||
if len(colors) != _LED_COUNT:
|
||||
raise ValueError("Each RAM stick requires exactly 12 LED colours")
|
||||
payload = bytes((_LED_COUNT,)) + b"".join(_rgb_bytes(color) for color in colors)
|
||||
return payload + bytes((_crc8(payload),))
|
||||
|
||||
|
||||
def _check_ntstatus(operation: str, status: int) -> None:
|
||||
if status < 0:
|
||||
value = status & 0xFFFFFFFF
|
||||
if value == _STATUS_ACCESS_DENIED:
|
||||
raise OSError(f"{operation}: PawnIO access denied; run the dashboard as administrator")
|
||||
if value == _STATUS_NO_SUCH_DEVICE:
|
||||
raise OSError(f"{operation}: no response from the RAM lighting controller")
|
||||
raise OSError(f"{operation}: NTSTATUS 0x{value:08X}")
|
||||
|
||||
|
||||
class PawnIoSmbus:
|
||||
"""Minimal, synchronized access to the four supported Corsair DDR5 RGB controllers."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._dll = None
|
||||
self._handle = wt.HANDLE()
|
||||
self._mutex = None
|
||||
self._kernel32 = None
|
||||
self._last_packets: dict[int, bytes] = {}
|
||||
|
||||
def open(self) -> None:
|
||||
if self._handle.value:
|
||||
return
|
||||
if not hasattr(ctypes, "WinDLL"):
|
||||
raise OSError("Corsair RAM lighting requires Windows and PawnIO")
|
||||
if corsair_software_running("Corsair DRAM", fan_tools=False):
|
||||
raise MemoryLightingBusy("RAM lighting busy: exit iCUE or disable OpenRGB's Corsair DRAM detector")
|
||||
|
||||
try:
|
||||
dll = ctypes.WinDLL(_PAWNIO_DLL, use_last_error=True)
|
||||
dll.pawnio_open_nt.argtypes = [ctypes.POINTER(wt.HANDLE)]
|
||||
dll.pawnio_load_nt.argtypes = [wt.HANDLE, ctypes.c_char_p, ctypes.c_size_t]
|
||||
dll.pawnio_execute_nt.argtypes = [
|
||||
wt.HANDLE, ctypes.c_char_p, ctypes.POINTER(_CELL), ctypes.c_size_t,
|
||||
ctypes.POINTER(_CELL), ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t),
|
||||
]
|
||||
dll.pawnio_execute_nt.restype = ctypes.c_int32
|
||||
dll.pawnio_close_nt.argtypes = [wt.HANDLE]
|
||||
|
||||
handle = wt.HANDLE()
|
||||
_check_ntstatus("Opening PawnIO", dll.pawnio_open_nt(ctypes.byref(handle)))
|
||||
self._dll, self._handle = dll, handle
|
||||
with open(_SMBUS_MODULE, "rb") as module_file:
|
||||
module = module_file.read()
|
||||
_check_ntstatus("Loading the PawnIO I801 SMBus module",
|
||||
dll.pawnio_load_nt(handle, module, len(module)))
|
||||
|
||||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR]
|
||||
k32.CreateMutexW.restype = wt.HANDLE
|
||||
k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||
k32.WaitForSingleObject.restype = wt.DWORD
|
||||
k32.ReleaseMutex.argtypes = [wt.HANDLE]
|
||||
k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
self._kernel32 = k32
|
||||
self._mutex = k32.CreateMutexW(None, False, r"Global\Access_SMBUS.HTP.Method")
|
||||
if not self._mutex:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
with self._bus():
|
||||
_, _, pci_ids = self._execute(b"ioctl_identity", count=3)
|
||||
if pci_ids & 0xFFFF != 0x8086:
|
||||
raise OSError(f"Expected an Intel SMBus controller, found PCI IDs 0x{pci_ids:016X}")
|
||||
self._verify_controllers()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
self._last_packets.clear()
|
||||
if self._mutex is not None:
|
||||
if self._kernel32 is None:
|
||||
raise OSError("Cannot close SMBus mutex: kernel32 was not initialized")
|
||||
if not self._kernel32.CloseHandle(self._mutex):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
self._mutex = None
|
||||
if self._handle.value and self._dll is not None:
|
||||
handle, self._handle = self._handle, wt.HANDLE()
|
||||
dll, self._dll = self._dll, None
|
||||
_check_ntstatus("Closing PawnIO", dll.pawnio_close_nt(handle))
|
||||
|
||||
def show(self, color: tuple[int, int, int]) -> None:
|
||||
self.show_frame(_solid_frame(color), force=True)
|
||||
|
||||
def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None:
|
||||
if len(colors) != len(_ADDRESSES):
|
||||
raise ValueError("RAM frames require exactly four sticks in physical top-to-bottom order")
|
||||
packets = tuple(_led_packet(stick) for stick in colors)
|
||||
with self._bus():
|
||||
for address, packet in zip(_ADDRESSES, packets):
|
||||
if not force and self._last_packets.get(address) == packet:
|
||||
continue
|
||||
self._write_block(address, 0x31, packet[:32])
|
||||
time.sleep(0.001)
|
||||
self._write_block(address, 0x32, packet[32:])
|
||||
self._last_packets[address] = packet
|
||||
|
||||
@contextmanager
|
||||
def _bus(self) -> Generator[None, None, None]:
|
||||
if self._mutex is None or self._kernel32 is None:
|
||||
raise OSError("PawnIO SMBus is not open")
|
||||
result = self._kernel32.WaitForSingleObject(self._mutex, 500)
|
||||
if result == _WAIT_ABANDONED:
|
||||
self._kernel32.ReleaseMutex(self._mutex)
|
||||
raise OSError("The previous SMBus owner exited without releasing the bus")
|
||||
if result != _WAIT_OBJECT_0:
|
||||
raise OSError(f"Could not acquire the SMBus mutex (wait result 0x{result:08X})")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not self._kernel32.ReleaseMutex(self._mutex):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
|
||||
def _execute(self, operation: bytes, args: tuple[int, ...] = (), count: int = 0) -> tuple[int, ...]:
|
||||
if self._dll is None or not self._handle.value:
|
||||
raise OSError("PawnIO SMBus is not open")
|
||||
in_buffer = (_CELL * len(args))(*args)
|
||||
out_buffer = (_CELL * count)()
|
||||
written = ctypes.c_size_t()
|
||||
status = self._dll.pawnio_execute_nt(
|
||||
self._handle, operation, in_buffer, len(in_buffer), out_buffer, len(out_buffer),
|
||||
ctypes.byref(written),
|
||||
)
|
||||
_check_ntstatus(operation.decode(), status)
|
||||
if written.value != count:
|
||||
raise OSError(f"{operation.decode()}: expected {count} output cells, got {written.value}")
|
||||
return tuple(out_buffer)
|
||||
|
||||
def _read_byte(self, address: int, register: int) -> int:
|
||||
return self._execute(b"ioctl_smbus_xfer", (address, 1, register, 2), 1)[0]
|
||||
|
||||
def _write_byte(self, address: int, register: int, value: int) -> None:
|
||||
self._execute(b"ioctl_smbus_xfer", (address, 0, register, 2, value))
|
||||
|
||||
def _write_block(self, address: int, register: int, data: bytes) -> None:
|
||||
if not 0 < len(data) <= 32:
|
||||
raise ValueError("SMBus block data must contain 1 to 32 bytes")
|
||||
packed = (bytes((len(data),)) + data).ljust(40, b"\x00")
|
||||
self._execute(b"ioctl_smbus_xfer",
|
||||
(address, 0, register, 5, *struct.unpack("<5Q", packed)))
|
||||
|
||||
def _read_buffer(self, address: int, selector: int, index: int, length: int) -> bytes:
|
||||
self._write_byte(address, selector, index)
|
||||
self._write_byte(address, 0x21, 0)
|
||||
data = bytes(self._read_byte(address, 0x40) for _ in range(length))
|
||||
actual = self._read_byte(address, 0x42)
|
||||
expected = _crc8(data)
|
||||
if actual != expected:
|
||||
raise OSError(f"RAM controller 0x{address:02X} buffer CRC mismatch "
|
||||
f"(0x{actual:02X} != 0x{expected:02X})")
|
||||
return data
|
||||
|
||||
def _verify_controllers(self) -> None:
|
||||
for address in _ADDRESSES:
|
||||
signature = self._read_byte(address, 0x43)
|
||||
revision = self._read_byte(address, 0x44)
|
||||
if signature not in (0x1A, 0x1B, 0x1C) or revision not in (1, 3, 4):
|
||||
raise OSError(f"Unrecognized RAM lighting controller at 0x{address:02X}")
|
||||
info = self._read_buffer(address, 0x61, 0, 32)
|
||||
vendor = int.from_bytes(info[0:2], "little")
|
||||
product = int.from_bytes(info[2:4], "little")
|
||||
protocol = info[28]
|
||||
if (vendor, product, protocol) != (0x1B1C, 0x0601, 4):
|
||||
raise OSError(f"Unsupported RAM at 0x{address:02X}: "
|
||||
f"{vendor:04X}:{product:04X}, RGB protocol {protocol}")
|
||||
log.info("Corsair Dominator Platinum DDR5 detected at SMBus address 0x%02X", address)
|
||||
|
||||
|
||||
class MemoryLighting:
|
||||
"""Run temperature colours or the mirrored RAM chase; disabled mode holds black."""
|
||||
|
||||
def __init__(self, theme: Theme, driver_factory: Callable[[], _MemoryLightingDriver] = PawnIoSmbus,
|
||||
chase_timing: ChaseTiming | None = None):
|
||||
if not (math.isfinite(theme.temp_warn) and math.isfinite(theme.temp_hot)
|
||||
and theme.temp_hot > theme.temp_warn):
|
||||
raise ValueError("RAM temperature range must be finite and increasing")
|
||||
self.theme = theme
|
||||
self.status = "off"
|
||||
self._driver_factory = driver_factory
|
||||
self._driver: _MemoryLightingDriver | None = None
|
||||
self._retry_at = 0.0
|
||||
self._last_error: str | None = None
|
||||
self._last_frame: MemoryFrame | None = None
|
||||
self._last_frame_at = -math.inf
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._touched = False
|
||||
self._temperatures: tuple[float | None, float | None] = (None, None)
|
||||
self._power: float | None = None
|
||||
self._pattern: str | None = None
|
||||
self._owns_chase_timing = chase_timing is None
|
||||
self._chase_timing = chase_timing if chase_timing is not None else ChaseTiming()
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
|
||||
def run(self, stop: threading.Event, enabled: threading.Event,
|
||||
side_chase: threading.Event | None = None) -> None:
|
||||
try:
|
||||
while not stop.is_set():
|
||||
cpu_temp, gpu_temp = self._temperatures
|
||||
self.update(cpu_temp, enabled.is_set(), gpu_temp=gpu_temp,
|
||||
side_chase=side_chase.is_set() if side_chase is not None else False)
|
||||
stop.wait(CHASE_POLL_SECONDS)
|
||||
except Exception:
|
||||
log.exception("RAM lighting worker failed")
|
||||
self._set_status("RAM lighting worker stopped; check dashboard.log")
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None:
|
||||
self._temperatures = (cpu_temp, gpu_temp)
|
||||
|
||||
def set_power(self, total_watts: float | None) -> None:
|
||||
self._power = total_watts
|
||||
self._chase_timing.set_power(total_watts)
|
||||
|
||||
def update(self, cpu_temp: float | None, enabled: bool, *, gpu_temp: float | None = None,
|
||||
side_chase: bool = False) -> None:
|
||||
now = time.monotonic()
|
||||
pattern = "chase" if side_chase else "temperature" if enabled else None
|
||||
if pattern != self._pattern:
|
||||
self._pattern = pattern
|
||||
if self._owns_chase_timing:
|
||||
self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
self._last_frame_at = -math.inf
|
||||
readings = [(temp, source) for temp, source in ((cpu_temp, "CPU"), (gpu_temp, "GPU"))
|
||||
if temp is not None and math.isfinite(temp)]
|
||||
reading = max(readings, key=lambda item: item[0]) if readings else None
|
||||
color = None
|
||||
if reading is not None:
|
||||
strength = min(1.0, max(0.0, (reading[0] - self.theme.temp_warn)
|
||||
/ (self.theme.temp_hot - self.theme.temp_warn)))
|
||||
color = side_chase_color(strength)
|
||||
|
||||
if side_chase:
|
||||
phase, rate = self._chase_timing.sample(now)
|
||||
target = memory_chase_frame(memory_chase_step(phase))
|
||||
elif enabled and color is None:
|
||||
if self._driver is None and not self._touched:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
return
|
||||
target = self._last_frame
|
||||
if target is None:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
return
|
||||
elif enabled:
|
||||
assert color is not None
|
||||
target = _solid_frame(color)
|
||||
else:
|
||||
target = _solid_frame(_BLACK)
|
||||
|
||||
if self._driver is None:
|
||||
if now < self._retry_at:
|
||||
return
|
||||
try:
|
||||
driver = self._driver_factory()
|
||||
driver.open()
|
||||
except OSError as error:
|
||||
self._fail(error)
|
||||
return
|
||||
self._driver = driver
|
||||
self._last_error = None
|
||||
log.info("RAM lighting SMBus opened")
|
||||
|
||||
assert target is not None
|
||||
keepalive = now - self._last_keepalive_at >= _KEEPALIVE_SECONDS
|
||||
if ((target != self._last_frame or keepalive)
|
||||
and (not side_chase or now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS)):
|
||||
try:
|
||||
self._driver.show_frame(target, force=keepalive)
|
||||
except OSError as error:
|
||||
self._fail(error)
|
||||
return
|
||||
self._last_frame = target
|
||||
self._last_frame_at = now
|
||||
if keepalive:
|
||||
self._last_keepalive_at = now
|
||||
self._touched = True
|
||||
|
||||
if side_chase:
|
||||
watts = "" if self._power is None else f" at {self._power:.0f} W"
|
||||
self._set_status(f"RAM red side chase active ({SIDE_CHASE_CYCLE_STEPS / rate:.1f} s/cycle{watts})")
|
||||
elif enabled and color is None:
|
||||
self._set_status("RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
elif enabled:
|
||||
assert reading is not None
|
||||
self._set_status(f"RAM temperature lighting active ({reading[1]} {reading[0]:.0f} \u00b0C)")
|
||||
else:
|
||||
self._set_status("RAM lighting off")
|
||||
|
||||
def close(self) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
if driver is not None:
|
||||
if self._touched:
|
||||
try:
|
||||
driver.show(_BLACK)
|
||||
except OSError:
|
||||
log.exception("Couldn't leave RAM lighting dark")
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't release the RAM lighting SMBus")
|
||||
self._last_frame = None
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._set_status("off")
|
||||
|
||||
def _fail(self, error: OSError) -> None:
|
||||
driver, self._driver = self._driver, None
|
||||
if driver is not None:
|
||||
try:
|
||||
driver.close()
|
||||
except OSError:
|
||||
log.exception("Couldn't close the failed RAM lighting SMBus")
|
||||
self._last_frame = None
|
||||
self._last_keepalive_at = -math.inf
|
||||
self._retry_at = time.monotonic() + _RETRY_SECONDS
|
||||
message = str(error) or type(error).__name__
|
||||
self._set_status(message)
|
||||
if message != self._last_error:
|
||||
log.warning("RAM lighting unavailable: %s", message, exc_info=not isinstance(error, MemoryLightingBusy))
|
||||
self._last_error = message
|
||||
|
||||
def _set_status(self, status: str) -> None:
|
||||
if status != self.status:
|
||||
self.status = status
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Lighting service: one worker per device, one mode per zone, saved in settings.json.
|
||||
|
||||
Zones and their modes (see kurgan.settings.LIGHTING_MODES):
|
||||
case_fans Lighting Node CORE QL120 LEDs: off (hardware effect), temperature, chase
|
||||
memory Dominator DDR5: off (held dark while running), temperature, chase
|
||||
gpu ASUS RTX 4090 LED row: off (its own effect), chase
|
||||
|
||||
The three chases share one power-paced clock, so they stay in step.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting
|
||||
from kurgan.lighting.gpu import GpuLighting
|
||||
from kurgan.lighting.memory import MemoryLighting
|
||||
from kurgan.settings import LIGHTING_MODES, Settings
|
||||
from kurgan.theme import Theme
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
ZONE_LABELS = {"case_fans": "Case fan LEDs", "memory": "RAM", "gpu": "GPU"}
|
||||
MODE_LABELS = {"off": "Off", "temperature": "Temperature", "chase": "Red side chase"}
|
||||
|
||||
|
||||
class LightingService:
|
||||
def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float],
|
||||
overrides: dict[str, str] | None = None, *, rgb=None, memory=None, gpu=None):
|
||||
"""chase: (idle s/LED, full-power s/LED, idle watts, full watts).
|
||||
overrides: modes for this run only (CLI flags), not saved."""
|
||||
self._settings = settings
|
||||
self._lock = threading.Lock()
|
||||
self._events = {zone: {mode: threading.Event() for mode in modes if mode != "off"}
|
||||
for zone, modes in LIGHTING_MODES.items()}
|
||||
self._overridden = set(overrides or ())
|
||||
modes = settings.section("lighting")
|
||||
modes.update(overrides or {})
|
||||
self._modes: dict[str, str] = {}
|
||||
for zone, mode in modes.items():
|
||||
self._apply(zone, mode)
|
||||
step, fast, idle_w, full_w = chase
|
||||
self.timing = ChaseTiming(step, fast, (idle_w, full_w))
|
||||
self.timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
self.rgb = rgb or RGBLighting(theme, step, fast, (idle_w, full_w), chase_timing=self.timing)
|
||||
self.memory = memory or MemoryLighting(theme, chase_timing=self.timing)
|
||||
self.gpu = gpu or GpuLighting(self.timing)
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._power: float | None = None
|
||||
|
||||
def _apply(self, zone: str, mode: str) -> None:
|
||||
events = self._events[zone]
|
||||
# Clear the old pattern before setting the new one, as the tray always did.
|
||||
for name, event in events.items():
|
||||
if name != mode:
|
||||
event.clear()
|
||||
if mode != "off":
|
||||
events[mode].set()
|
||||
self._modes[zone] = mode
|
||||
|
||||
def start(self, stop: threading.Event) -> None:
|
||||
e = self._events
|
||||
for name, target, args in (
|
||||
("case-fan-lighting", self.rgb.run, (stop, e["case_fans"]["temperature"], e["case_fans"]["chase"])),
|
||||
("memory-lighting", self.memory.run, (stop, e["memory"]["temperature"], e["memory"]["chase"])),
|
||||
("gpu-lighting", self.gpu.run, (stop, e["gpu"]["chase"]))):
|
||||
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
|
||||
thread.start()
|
||||
self._threads.append(thread)
|
||||
|
||||
def join(self) -> None:
|
||||
for thread in self._threads:
|
||||
thread.join()
|
||||
|
||||
def on_telemetry(self, cpu_temp: float | None, gpu_temp: float | None, total_watts: float | None) -> None:
|
||||
self._power = total_watts
|
||||
self.rgb.set_temperature(cpu_temp, gpu_temp)
|
||||
self.rgb.set_power(total_watts)
|
||||
self.memory.set_temperature(cpu_temp, gpu_temp)
|
||||
self.memory.set_power(total_watts)
|
||||
|
||||
def mode(self, zone: str) -> str:
|
||||
return self._modes[zone]
|
||||
|
||||
def set_mode(self, zone: str, mode: str) -> None:
|
||||
"""Save first, then switch, so a failed save leaves the lighting as it was."""
|
||||
if zone not in LIGHTING_MODES or mode not in LIGHTING_MODES[zone]:
|
||||
raise ValueError(f"Unknown lighting {zone!r} mode {mode!r}")
|
||||
with self._lock:
|
||||
self._settings.update("lighting", **{zone: mode})
|
||||
self._overridden.discard(zone)
|
||||
self._apply(zone, mode)
|
||||
log.info("%s lighting: %s", ZONE_LABELS[zone], mode)
|
||||
|
||||
def statuses(self) -> dict[str, str]:
|
||||
return {"case_fans": self.rgb.status, "memory": self.memory.status, "gpu": self.gpu.status}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
statuses = self.statuses()
|
||||
# The eased rate once a chase is running; the target rate for the current power until then.
|
||||
rate = self.timing.rate or self.timing.rate_for(self._power)
|
||||
chasing = "chase" in self._modes.values()
|
||||
return {"chase_ms_per_led": round(1000 / rate) if chasing else None,
|
||||
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": self._modes[zone],
|
||||
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in modes],
|
||||
"status": statuses[zone], "this_run_only": zone in self._overridden}
|
||||
for zone, modes in LIGHTING_MODES.items()]}
|
||||
Reference in new issue
Block a user