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