Files

429 lines
18 KiB
Python

"""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