Files
led-controller/stubs/_simlink_proc.py
T
jimmyandClaude Haiku 5.5 4d8aeb5df8 feat: simulator bridge, rig seed and web UI (in progress)
Work in progress from the same tree as the controller's sequences-v2 changes.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 14:10:55 +13:00

112 lines
2.5 KiB
Python

"""CPython link between one simulated led-driver process and ``bridge_sim.py``.
Frames on the multiprocessing connection (first byte is the kind):
- driver -> bridge: ``H`` + index (once), ``P`` + RGB bytes, ``T`` + dest_mac(6) + packet
- bridge -> driver: ``R`` + src_mac(6) + packet
"""
import threading
import time
from collections import deque
from multiprocessing.connection import Client
_conn = None
_rx = deque()
_rx_cond = threading.Condition()
_tx_lock = threading.Lock()
_px_period = 1 / 30.0
_last_px = 0.0
_pixels = None
_pixels_dirty = False
def connect(address, authkey, index, fps=30):
global _conn, _px_period
_px_period = 1.0 / max(1.0, float(fps))
_conn = Client(address, authkey=authkey)
_conn.send_bytes(b"H" + bytes([index]))
threading.Thread(target=_reader, daemon=True).start()
def _reader():
import os
while True:
try:
frame = _conn.recv_bytes()
except (EOFError, OSError):
os._exit(0) # bridge gone: power off
if frame[:1] == b"R" and len(frame) >= 7:
with _rx_cond:
_rx.append((frame[1:7], frame[7:]))
_rx_cond.notify()
def connected():
return _conn is not None
def real_sleep(seconds):
if seconds > 0:
time.sleep(seconds)
def recv_nowait():
with _rx_cond:
if _rx:
return _rx.popleft()
return (None, None)
def recv(timeout_ms=0):
with _rx_cond:
if not _rx and timeout_ms:
_rx_cond.wait(None if timeout_ms < 0 else timeout_ms / 1000.0)
if _rx:
return _rx.popleft()
return (None, None)
def pending():
return len(_rx)
def send_tx(dest_mac, packet):
with _tx_lock:
_conn.send_bytes(b"T" + bytes(dest_mac) + bytes(packet))
def _send_pixels():
global _pixels_dirty, _last_px
_pixels_dirty = False
_last_px = time.monotonic()
with _tx_lock:
_conn.send_bytes(b"P" + _pixels)
def push_pixels(buf):
global _pixels, _pixels_dirty
data = bytearray(len(buf) * 3)
j = 0
for r, g, b in buf:
data[j] = r
data[j + 1] = g
data[j + 2] = b
j += 3
_pixels = bytes(data)
_pixels_dirty = True
if time.monotonic() - _last_px >= _px_period:
_send_pixels()
def start_new_thread(fn, args, kwargs=None):
t = threading.Thread(target=fn, args=tuple(args), kwargs=kwargs or {}, daemon=True)
t.start()
return t.ident
def on_feed():
if _pixels_dirty and time.monotonic() - _last_px >= _px_period:
_send_pixels()