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,179 @@
|
||||
"""Driver for the Thermaltake 3.9" bar LCD (USB 264A:233D, 480x128) on Windows.
|
||||
|
||||
Talks to the panel through the stock Windows HID driver using only ctypes.
|
||||
|
||||
Protocol (as documented by the ttlcd, thermaltaked and Tower-500-LCD-Controller
|
||||
projects):
|
||||
* Interface 0 (MI_00) is the command channel: 440-byte reports.
|
||||
handshake : 85, 87, 85, 87, 84, 81 each as [op, 01, 00, 80], each acknowledged
|
||||
brightness : [12, 01, 00, 80, percent]
|
||||
heartbeat : [82, 01, 00, 80] (every ~2 s)
|
||||
* Interface 1 (MI_01) is the frame channel: 1024-byte reports carrying a
|
||||
baseline JPEG split into 1020-byte chunks.
|
||||
first packet : [08, packet_count, 00, 80] + data
|
||||
next packets : [08, index, 00, 00] + data
|
||||
One acknowledgement arrives after the whole frame.
|
||||
* No report IDs are used, so every write is prefixed with a 0x00 byte.
|
||||
* If no frame arrives for a few seconds the panel goes back to its own screen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import threading
|
||||
|
||||
from kurgan.hardware.hid import HidChannel, HidError, hid_device_paths
|
||||
|
||||
VENDOR_ID = 0x264A
|
||||
PRODUCT_ID = 0x233D
|
||||
WIDTH = 480
|
||||
HEIGHT = 128
|
||||
|
||||
COMMAND_SIZE = 440
|
||||
FRAME_PACKET_SIZE = 1024
|
||||
FRAME_DATA_SIZE = FRAME_PACKET_SIZE - 4
|
||||
MAX_FRAME_PACKETS = 255
|
||||
|
||||
HANDSHAKE_OPCODES = (0x85, 0x87, 0x85, 0x87, 0x84, 0x81)
|
||||
OP_HEARTBEAT = 0x82
|
||||
OP_BRIGHTNESS = 0x12
|
||||
OP_FRAME = 0x08
|
||||
|
||||
REPLY_TIMEOUT_MS = 2000
|
||||
|
||||
|
||||
# The panel's own errors share the HID layer's exception, so callers catch one type.
|
||||
LcdError = HidError
|
||||
|
||||
|
||||
class LcdNotFound(LcdError):
|
||||
pass
|
||||
|
||||
|
||||
def find_interfaces() -> dict[int, str]:
|
||||
"""Return {interface_number: device_path} for the panel's HID interfaces."""
|
||||
found: dict[int, str] = {}
|
||||
for path in hid_device_paths(VENDOR_ID, PRODUCT_ID):
|
||||
low = path.lower()
|
||||
if "&mi_00" in low:
|
||||
found[0] = path
|
||||
elif "&mi_01" in low:
|
||||
found[1] = path
|
||||
return found
|
||||
|
||||
|
||||
def _command(*prefix: int) -> bytes:
|
||||
return bytes(prefix).ljust(COMMAND_SIZE, b"\x00")
|
||||
|
||||
|
||||
def frame_packets(jpeg: bytes) -> list[bytes]:
|
||||
if not (jpeg[:2] == b"\xff\xd8" and jpeg[-2:] == b"\xff\xd9"):
|
||||
raise LcdError("Frame is not a complete JPEG")
|
||||
count = math.ceil(len(jpeg) / FRAME_DATA_SIZE)
|
||||
if not 1 <= count <= MAX_FRAME_PACKETS:
|
||||
raise LcdError(f"JPEG too large ({len(jpeg)} bytes)")
|
||||
packets = []
|
||||
for index in range(count):
|
||||
chunk = jpeg[index * FRAME_DATA_SIZE:(index + 1) * FRAME_DATA_SIZE]
|
||||
header = bytes((OP_FRAME, count, 0x00, 0x80)) if index == 0 else bytes((OP_FRAME, index, 0x00, 0x00))
|
||||
packets.append((header + chunk).ljust(FRAME_PACKET_SIZE, b"\x00"))
|
||||
return packets
|
||||
|
||||
|
||||
class ThermaltakeLcd:
|
||||
"""Open with `with ThermaltakeLcd() as lcd:` then call send_jpeg() at least every 2 s."""
|
||||
|
||||
def __init__(self, brightness: int = 100):
|
||||
self.brightness = max(0, min(100, int(brightness)))
|
||||
self.command: HidChannel | None = None
|
||||
self.frame: HidChannel | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def open(self) -> None:
|
||||
paths = find_interfaces()
|
||||
if 0 not in paths or 1 not in paths:
|
||||
raise LcdNotFound("Thermaltake 3.9\" LCD (264A:233D) not found")
|
||||
self.command = HidChannel(paths[0], COMMAND_SIZE)
|
||||
try:
|
||||
self.frame = HidChannel(paths[1], FRAME_PACKET_SIZE)
|
||||
self._handshake()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
for ch in (self.frame, self.command):
|
||||
if ch is not None:
|
||||
ch.close()
|
||||
self.frame = self.command = None
|
||||
|
||||
def __enter__(self) -> "ThermaltakeLcd":
|
||||
self.open()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def _handshake(self) -> None:
|
||||
assert self.command and self.frame
|
||||
self.frame.drain()
|
||||
self.command.drain()
|
||||
with self._lock:
|
||||
for op in HANDSHAKE_OPCODES:
|
||||
self.command.send(_command(op, 0x01, 0x00, 0x80))
|
||||
if self.command.read(REPLY_TIMEOUT_MS) is None:
|
||||
raise LcdError(f"No reply to handshake opcode 0x{op:02X}")
|
||||
self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness))
|
||||
|
||||
def set_brightness(self, percent: int) -> None:
|
||||
self.brightness = max(0, min(100, int(percent)))
|
||||
with self._lock:
|
||||
self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness))
|
||||
|
||||
def heartbeat(self) -> None:
|
||||
with self._lock:
|
||||
self.command.drain()
|
||||
self.command.send(_command(OP_HEARTBEAT, 0x01, 0x00, 0x80))
|
||||
|
||||
def send_jpeg(self, jpeg: bytes) -> bool:
|
||||
"""Send one JPEG frame. Returns True if the panel acknowledged it."""
|
||||
packets = frame_packets(jpeg)
|
||||
self.frame.drain()
|
||||
for packet in packets:
|
||||
self.frame.send(packet)
|
||||
return self.frame.read(REPLY_TIMEOUT_MS) is not None
|
||||
|
||||
|
||||
def encode_jpeg(image, quality: int = 90) -> bytes:
|
||||
"""Encode a 480x128 PIL image as a baseline JPEG the panel accepts."""
|
||||
import io
|
||||
|
||||
if image.size != (WIDTH, HEIGHT):
|
||||
raise ValueError(f"Frame must be {WIDTH}x{HEIGHT}, got {image.size}")
|
||||
out = io.BytesIO()
|
||||
image.convert("RGB").save(out, format="JPEG", quality=quality, optimize=True,
|
||||
progressive=False, subsampling=0)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Quick hardware test: draws a test card for a few seconds.
|
||||
import time
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
print("Interfaces:", find_interfaces())
|
||||
with ThermaltakeLcd() as lcd:
|
||||
print(f"Handshake OK. Report lengths: cmd out={lcd.command.output_len} in={lcd.command.input_len}, "
|
||||
f"frame out={lcd.frame.output_len} in={lcd.frame.input_len}")
|
||||
for i in range(8):
|
||||
img = Image.new("RGB", (WIDTH, HEIGHT), (10, 10, 14))
|
||||
d = ImageDraw.Draw(img)
|
||||
for x, col in enumerate([(220, 30, 40), (40, 200, 60), (40, 90, 230), (240, 240, 240)]):
|
||||
d.rectangle([x * 120, 0, x * 120 + 119, 30], fill=col)
|
||||
d.rectangle([0, 0, WIDTH - 1, HEIGHT - 1], outline=(255, 255, 0))
|
||||
d.text((10, 50), f"LEFT test frame {i + 1}/8", fill=(255, 255, 255), font_size=24)
|
||||
d.text((400, 100), "RIGHT", fill=(255, 255, 255), font_size=16)
|
||||
ack = lcd.send_jpeg(encode_jpeg(img))
|
||||
print(f"frame {i + 1}: ack={ack}")
|
||||
lcd.heartbeat()
|
||||
time.sleep(1)
|
||||
Reference in new issue
Block a user