Files
the_kurgan/kurgan/lighting/service.py
T
paulandClaude Opus 5.5 eb771656fb Privilege split 6/11: the app reads and drives the hardware through the service
- kurgan/hw/client.py: HardwareClient polls the service's state once a second
  on its own thread, reconnecting (and greeting again) whenever the pipe
  breaks, and sends the app's chase clock with each poll. Profile and RAM
  lighting changes are sent at once: bad values are ValueError before anything
  is sent; an unreachable or refusing service is HardwareUnavailable. A state
  that stops arriving (5 s) or a service loop that stops publishing (15 s)
  counts as unavailable. PipeTransport for the real pipe, LocalTransport (same
  encoding and checks, no pipe) for --demo and tests.
- Telemetry: the CPU package temperature and power (CpuSensors(package=...))
  and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come
  from the service; the app opens neither PawnIO nor the Commander PRO.
  "hardware service" is its own health source, and while it's down the
  missing CPU temperature isn't reported a second time.
- The fan UI, profile buttons and fan history come from the service's state;
  the RAM lighting zone goes through it (LightingService(ram=...)), and the
  case fan and GPU zones stay local. The alert monitor balloons "Hardware
  service unavailable"; the header shows a hardware service pill instead of
  the admin-rights one (and warns if the app itself runs elevated); the tray
  lines read the service's fans. POSTs answer 503 while it's unavailable.
- Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the
  service owns those now.
- settings.json: cooling and lighting.memory are legacy. Old files keep them
  (still validated), nothing reads them, and defaults no longer add them.
- --demo runs the real HardwareService in-process on the demo fakes, with its
  settings in demo-hw-settings.json, through the same client.
- --preview reads the CPU temperature and fan power from the service too.
- Tests: 13 for the client (including a real pipe end to end); the alert,
  lighting, settings and web tests follow the new shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:41:51 +13:00

123 lines
5.9 KiB
Python

"""Lighting service: one worker per device, one mode per zone.
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 case fan and GPU zones run here and are saved in settings.json. The RAM is on the SMBus,
which needs PawnIO and so admin rights: the hardware service drives it and keeps its mode in
hw-settings.json; this service only shows it and asks for changes (kurgan.hw.client.RamLighting).
The three chases share one power-paced clock, so they stay in step: the RAM's in the hardware
service is kept in step by sending it this clock once a second (chase_clock).
"""
from __future__ import annotations
import logging
import threading
import time
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting
from kurgan.lighting.gpu import GpuLighting
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"}
REMOTE_ZONES = ("memory",) # driven by the hardware service
LOCAL_ZONES = tuple(zone for zone in LIGHTING_MODES if zone not in REMOTE_ZONES)
class LightingService:
def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float],
overrides: dict[str, str] | None = None, *, ram, rgb=None, gpu=None):
"""chase: (idle s/LED, full-power s/LED, idle watts, full watts).
overrides: case fan and GPU modes for this run only (CLI flags), not saved.
ram: the RAM zone in the hardware service (mode, status, set_mode)."""
self._settings = settings
self._lock = threading.Lock()
self._events = {zone: {mode: threading.Event() for mode in LIGHTING_MODES[zone] if mode != "off"}
for zone in LOCAL_ZONES}
self._overridden = set(overrides or ())
modes = {zone: mode for zone, mode in settings.section("lighting").items() if zone in LOCAL_ZONES}
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.gpu = gpu or GpuLighting(self.timing)
self.ram = ram
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"])),
("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) # sets the shared clock's pace
def chase_clock(self) -> dict:
"""The shared chase clock now, as the hardware service's ram_chase takes it."""
phase, rate = self.timing.sample(time.monotonic())
return {"phase": phase, "rate": rate, "power": self._power}
def mode(self, zone: str) -> str | None:
return self.ram.mode if zone in REMOTE_ZONES else 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}")
if zone in REMOTE_ZONES:
self.ram.set_mode(mode) # the hardware service saves it
else:
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.ram.status, "gpu": self.gpu.status}
def snapshot(self) -> dict:
statuses = self.statuses()
modes = {**self._modes, "memory": self.ram.mode}
# 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 modes.values()
return {"chase_ms_per_led": round(1000 / rate) if chasing else None,
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": modes[zone],
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in zone_modes],
"status": statuses[zone], "this_run_only": zone in self._overridden}
for zone, zone_modes in LIGHTING_MODES.items()]}