Add Art-Net BCC145 controller with web UI and MediaPipe pointing.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jimmyandCursor committed 2026-10-07 22:42:52 +13:00
1 parent 6dde628e00
commit a0e205d463
19 files changed
+3334

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
.venv/
__pycache__/
*.pyc
.pytest_cache/
.local/
models/*.task
.env
+24
View File
@@ -0,0 +1,24 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
fastapi = "==0.115.6"
uvicorn = {extras = ["standard"], version = "==0.34.0"}
pydantic = "==2.10.4"
stupidartnet = "==1.6.0"
mediapipe = "*"
opencv-python = "*"
numpy = "*"
[dev-packages]
pytest = "*"
[scripts]
server = "python src/server.py"
point = "python src/point.py"
test = "pytest"
[requires]
python_version = "3.12"
Generated
+1390
View File
File diff suppressed because it is too large. Load diff
+59
View File
@@ -1,2 +1,61 @@
# flowforum # flowforum
Art-Net control for eight beamZ BCC145 parcans — web UI and MediaPipe pointing.
Uses the **8 Channel** map from `~/projects/qlcplus/fixtures/beamZ-BCC145.qxf`
and the stage patch from `flow_forum.qxw`:
| CH | Name |
|----|--------|
| 1 | Dimmer |
| 2 | Strobe |
| 3 | Red |
| 4 | Green |
| 5 | Blue |
| 6 | White |
| 7 | Macro |
| 8 | Speed |
Fixture starts (1-based DMX): **88, 96, 104, 112, 120, 128, 136, 144**.
Default Art-Net target: `dmx-gateway.local` universe 0.
## Setup
```bash
pipenv install --dev
```
## Web controller
```bash
pipenv run server
```
Open http://localhost:8080
## Point at a light
Camera sits in the middle of the row of 4 (`#3–#6`) and **faces the performer**
(+Y / audience). Stage map: `stage/map.json`.
```bash
pipenv run point
```
Point with index finger extended (other fingers curled). Aimed can goes white.
`b` blackout · `q` quit. Hand model downloads to `models/` on first run.
## Tests
```bash
pipenv run test
```
## Env
- `ARTNET_IP` — destination host (default `dmx-gateway.local`)
- `ARTNET_UNIVERSE` — Art-Net universe (default `0`)
- `PORT` — HTTP port (default `8080`)
- `RELOAD` — auto-reload web UI (default `1`; set `0` for show use)
Stop QLC+ (or any other Art-Net source) on the same universe while using this.
+3
View File
@@ -0,0 +1,3 @@
[pytest]
pythonpath = src
testpaths = tests
+80
View File
@@ -0,0 +1,80 @@
"""Steady Art-Net refresh.
StupidArtnet.start() spawns a new thread every frame (flickers).
This keeps one thread, monotonic timing, and locked full-frame snapshots
so UI updates never tear mid-packet.
"""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
from stupidArtnet import StupidArtnet
class ArtNetRefresh:
def __init__(self, artnet: StupidArtnet):
self.artnet = artnet
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread: threading.Thread | None = None
def update(self, fn: Callable[[StupidArtnet], None]) -> None:
"""Apply buffer/config changes atomically vs the sender."""
with self._lock:
fn(self.artnet)
def start(self) -> None:
if self._thread and self._thread.is_alive():
return
self._stop.clear()
self._thread = threading.Thread(target=self._loop, name="artnet-refresh", daemon=True)
self._thread.start()
def _send_snapshot(self) -> None:
with self._lock:
self.artnet.packet_header[12] = self.artnet.sequence & 0xFF
packet = bytes(self.artnet.packet_header) + bytes(self.artnet.buffer)
dest = (self.artnet.target_ip, self.artnet.port)
self.artnet.sequence = (self.artnet.sequence + 1) % 256
try:
self.artnet.socket_client.sendto(packet, dest)
except OSError:
pass
def _loop(self) -> None:
period = 1.0 / max(1.0, float(self.artnet.fps))
next_t = time.monotonic()
while not self._stop.is_set():
self._send_snapshot()
next_t += period
delay = next_t - time.monotonic()
if delay < 0:
# Fell behind: skip catch-up bursts (those look like flicker).
next_t = time.monotonic()
delay = 0.0
if self._stop.wait(delay):
break
def is_running(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def stop(self, *, blackout: bool = True) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=1.0)
self._thread = None
if blackout:
with self._lock:
self.artnet.buffer[:] = b"\x00" * len(self.artnet.buffer)
self.artnet.packet_header[12] = self.artnet.sequence & 0xFF
packet = bytes(self.artnet.packet_header) + bytes(self.artnet.buffer)
dest = (self.artnet.target_ip, self.artnet.port)
try:
# A few zeros so the gateway latches blackout.
for _ in range(3):
self.artnet.socket_client.sendto(packet, dest)
except OSError:
pass
+190
View File
@@ -0,0 +1,190 @@
"""beamZ BCC145 — 8 Channel mode (from QLC+ fixture definition).
Channel order (relative to fixture start, 1-based DMX):
Dimmer, Strobe, Red, Green, Blue, White, Macro, Speed
Stage patch (flow_forum.qxw): 8 fixtures starting at DMX 88,
stride 8 → 88, 96, …, 144.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from stupidArtnet import StupidArtnet
CHANNELS = 8
# 1-based DMX start of BCC145 #1 in flow_forum / xchc shows
DEFAULT_START_1 = 88
DEFAULT_COUNT = 8
DEFAULT_STRIDE = 8
MACRO_LABELS: list[tuple[int, int, str]] = [
(0, 50, "RGBW mix"),
(51, 100, "Fixed colour"),
(101, 150, "Colour jump"),
(151, 200, "Colour pulse"),
(201, 250, "Colour gradient"),
(251, 253, "Sound 1"),
(254, 255, "Sound 2"),
]
PRESETS: dict[str, tuple[int, int, int, int]] = {
"Red": (255, 0, 0, 0),
"Orange": (255, 127, 0, 0),
"Yellow": (255, 255, 0, 0),
"Green": (0, 255, 0, 0),
"Cyan": (0, 255, 255, 0),
"Blue": (0, 0, 255, 0),
"Violet": (127, 0, 255, 0),
"Magenta": (255, 0, 255, 0),
"White": (0, 0, 0, 255),
"Warm": (255, 140, 40, 80),
"Cool": (180, 200, 255, 120),
}
@dataclass
class FixtureState:
dimmer: int = 0
strobe: int = 0
red: int = 0
green: int = 0
blue: int = 0
white: int = 0
macro: int = 0
speed: int = 0
enabled: bool = True
def channel_bytes(self) -> list[int]:
if not self.enabled:
return [0] * CHANNELS
return [
self.dimmer,
self.strobe,
self.red,
self.green,
self.blue,
self.white,
self.macro,
self.speed,
]
def as_dict(self) -> dict:
return {
"dimmer": self.dimmer,
"strobe": self.strobe,
"red": self.red,
"green": self.green,
"blue": self.blue,
"white": self.white,
"macro": self.macro,
"speed": self.speed,
"enabled": self.enabled,
}
@dataclass
class Rig:
"""Eight BCC145 parcans on one Art-Net universe."""
start_1: int = DEFAULT_START_1
count: int = DEFAULT_COUNT
stride: int = DEFAULT_STRIDE
fixtures: list[FixtureState] = field(default_factory=list)
def __post_init__(self) -> None:
if not self.fixtures:
self.fixtures = [FixtureState() for _ in range(self.count)]
def address_1(self, index: int) -> int:
"""1-based DMX start (what fixtures display as e.g. A088)."""
return self.start_1 + index * self.stride
def apply(self, artnet: StupidArtnet) -> None:
for i, fx in enumerate(self.fixtures):
start = self.address_1(i)
for offset, value in enumerate(fx.channel_bytes()):
artnet.set_single_value(start + offset, value)
def enable_all(self) -> None:
for fx in self.fixtures:
fx.enabled = True
def set_all(
self,
*,
dimmer: int | None = None,
strobe: int | None = None,
red: int | None = None,
green: int | None = None,
blue: int | None = None,
white: int | None = None,
macro: int | None = None,
speed: int | None = None,
only_enabled: bool = True,
) -> None:
for fx in self.fixtures:
if only_enabled and not fx.enabled:
continue
if dimmer is not None:
fx.dimmer = dimmer
if strobe is not None:
fx.strobe = strobe
if red is not None:
fx.red = red
if green is not None:
fx.green = green
if blue is not None:
fx.blue = blue
if white is not None:
fx.white = white
if macro is not None:
fx.macro = macro
if speed is not None:
fx.speed = speed
def blackout(self) -> None:
for fx in self.fixtures:
fx.dimmer = 0
fx.strobe = 0
fx.red = 0
fx.green = 0
fx.blue = 0
fx.white = 0
fx.macro = 0
fx.speed = 0
def status(self) -> dict:
return {
"start_1": self.start_1,
"count": self.count,
"stride": self.stride,
"mode": "8 Channel",
"channels": [
"Dimmer",
"Strobe",
"Red",
"Green",
"Blue",
"White",
"Macro",
"Speed",
],
"macros": [
{"min": a, "max": b, "label": label} for a, b, label in MACRO_LABELS
],
"presets": {
k: {"r": v[0], "g": v[1], "b": v[2], "w": v[3]} for k, v in PRESETS.items()
},
"fixtures": [
{
"id": i,
"name": f"#{i + 1}",
"address_1": self.address_1(i),
**fx.as_dict(),
}
for i, fx in enumerate(self.fixtures)
],
}
+66
View File
@@ -0,0 +1,66 @@
"""Light a single BCC145 from the pointing controller."""
from __future__ import annotations
import os
from stupidArtnet import StupidArtnet
from artnet_refresh import ArtNetRefresh
from bcc145 import PRESETS, Rig
DEFAULT_IP = os.environ.get("ARTNET_IP", "dmx-gateway.local")
DEFAULT_UNIVERSE = int(os.environ.get("ARTNET_UNIVERSE", "0"))
class CanLights:
def __init__(
self,
host: str = DEFAULT_IP,
universe: int = DEFAULT_UNIVERSE,
colour: str = "White",
):
self.artnet = StupidArtnet(
target_ip=host,
universe=universe,
packet_size=512,
fps=40,
)
self.refresh = ArtNetRefresh(self.artnet)
self.rig = Rig()
self.rgbw = PRESETS.get(colour, PRESETS["White"])
self._on: int | None = None
self.refresh.start()
self.blackout()
def blackout(self) -> None:
self.rig.blackout()
self.rig.enable_all()
self.refresh.update(self.rig.apply)
self._on = None
def light_only(self, index: int) -> None:
"""Turn on a single can (0–7); others off."""
if index == self._on:
return
if not 0 <= index < len(self.rig.fixtures):
return
r, g, b, w = self.rgbw
for i, fx in enumerate(self.rig.fixtures):
on = i == index
fx.enabled = True
fx.dimmer = 255 if on else 0
fx.strobe = 0
fx.red = r if on else 0
fx.green = g if on else 0
fx.blue = b if on else 0
fx.white = w if on else 0
fx.macro = 0
fx.speed = 0
self.refresh.update(self.rig.apply)
self._on = index
def close(self) -> None:
self.refresh.stop(blackout=True)
self.artnet.close()
self._on = None
+60
View File
@@ -0,0 +1,60 @@
"""Dev live-reload: watch static files and nudge connected browsers via SSE."""
from __future__ import annotations
import asyncio
import threading
from pathlib import Path
from watchfiles import watch
class LiveReload:
def __init__(self, paths: list[Path]):
self.paths = [str(p) for p in paths]
self._loop: asyncio.AbstractEventLoop | None = None
self._queues: list[asyncio.Queue[str]] = []
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread: threading.Thread | None = None
def start(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._stop.clear()
self._thread = threading.Thread(target=self._watch, name="live-reload", daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=2.0)
self._thread = None
with self._lock:
for q in self._queues:
q.put_nowait("reload")
self._queues.clear()
def subscribe(self) -> asyncio.Queue[str]:
q: asyncio.Queue[str] = asyncio.Queue()
with self._lock:
self._queues.append(q)
return q
def unsubscribe(self, q: asyncio.Queue[str]) -> None:
with self._lock:
if q in self._queues:
self._queues.remove(q)
def _notify(self) -> None:
with self._lock:
queues = list(self._queues)
for q in queues:
try:
q.put_nowait("reload")
except Exception:
pass
def _watch(self) -> None:
for _changes in watch(*self.paths, stop_event=self._stop, debounce=300, step=200):
if self._loop is not None:
self._loop.call_soon_threadsafe(self._notify)
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
"""Point at a BCC145 — MediaPipe hand aiming + Art-Net.
Camera is centred on the row of 4 (#3–#6) and faces the performer
(toward +Y / audience). Point with your index finger; that can lights.
"""
from __future__ import annotations
import time
import urllib.request
from pathlib import Path
import cv2
import mediapipe as mp
import numpy as np
from can_lights import CanLights
from stage_layout import load_cans, pick_can
BaseOptions = mp.tasks.BaseOptions
HandLandmarker = mp.tasks.vision.HandLandmarker
HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode
mp_drawing = mp.tasks.vision.drawing_utils
mp_drawing_styles = mp.tasks.vision.drawing_styles
mp_hands = mp.tasks.vision.HandLandmarksConnections
WRIST = 0
INDEX_MCP = 5
INDEX_TIP = 8
MIDDLE_TIP = 12
RING_TIP = 16
PINKY_TIP = 20
ROOT = Path(__file__).resolve().parent.parent
HAND_MODEL_PATH = ROOT / "models" / "hand_landmarker.task"
HAND_MODEL_URL = (
"https://storage.googleapis.com/mediapipe-models/"
"hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task"
)
WINDOW_NAME = "flowforum-point"
CAMERA_WIDTH = 1920
CAMERA_HEIGHT = 1080
HOLD_NEED = 4
def ensure_model(path: Path, url: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
return
print(f"Downloading {path.name}...")
urllib.request.urlretrieve(url, path)
def is_pointing(hand) -> bool:
"""Index extended; middle/ring/pinky curled back toward wrist."""
wrist = hand[WRIST]
index_tip = hand[INDEX_TIP]
index_mcp = hand[INDEX_MCP]
def dist(a, b) -> float:
return float(np.hypot(a.x - b.x, a.y - b.y))
if dist(index_tip, index_mcp) < 0.06:
return False
index_reach = dist(index_tip, wrist)
for tip_i in (MIDDLE_TIP, RING_TIP, PINKY_TIP):
if dist(hand[tip_i], wrist) > index_reach * 0.85:
return False
return True
def enter_fullscreen() -> None:
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
cv2.imshow(WINDOW_NAME, np.zeros((2, 2, 3), dtype=np.uint8))
cv2.waitKey(1)
cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
cv2.waitKey(1)
def draw_stage_overlay(rgb: np.ndarray, cans, active_index: int | None) -> None:
h, w = rgb.shape[:2]
for can in cans:
x = int((1.0 - can.u) * w)
y = int(can.v * h)
on = can.index == active_index
color = (0, 255, 128) if on else (80, 80, 80)
cv2.circle(rgb, (x, y), 22 if on else 14, color, -1)
cv2.putText(
rgb,
can.label,
(x - 12, y + 5),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 0) if on else (200, 200, 200),
1,
cv2.LINE_AA,
)
def main() -> None:
ensure_model(HAND_MODEL_PATH, HAND_MODEL_URL)
cans = load_cans()
lights = CanLights(colour="White")
enter_fullscreen()
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)
hand_options = HandLandmarkerOptions(
base_options=BaseOptions(model_asset_path=str(HAND_MODEL_PATH)),
running_mode=VisionRunningMode.VIDEO,
num_hands=2,
min_hand_detection_confidence=0.5,
min_tracking_confidence=0.5,
)
active: int | None = None
hold_index: int | None = None
hold_frames = 0
try:
with HandLandmarker.create_from_options(hand_options) as hand_landmarker:
start = time.monotonic()
last_timestamp_ms = -1
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
continue
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
timestamp_ms = int((time.monotonic() - start) * 1000)
if timestamp_ms <= last_timestamp_ms:
timestamp_ms = last_timestamp_ms + 1
last_timestamp_ms = timestamp_ms
hand_results = hand_landmarker.detect_for_video(mp_image, timestamp_ms)
aimed: int | None = None
if hand_results.hand_landmarks:
for hand_landmarks in hand_results.hand_landmarks:
mp_drawing.draw_landmarks(
rgb,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style(),
)
if not is_pointing(hand_landmarks):
continue
mcp = hand_landmarks[INDEX_MCP]
tip = hand_landmarks[INDEX_TIP]
can = pick_can((mcp.x, mcp.y), (tip.x, tip.y), cans)
if can is None:
continue
aimed = can.index
h, w = rgb.shape[:2]
p0 = (int(mcp.x * w), int(mcp.y * h))
p1 = (int(tip.x * w), int(tip.y * h))
extend = np.array([tip.x - mcp.x, tip.y - mcp.y], dtype=float)
n = float(np.linalg.norm(extend))
if n > 1e-3:
extend /= n
p2 = (
int((tip.x + extend[0] * 0.45) * w),
int((tip.y + extend[1] * 0.45) * h),
)
cv2.line(rgb, p0, p2, (0, 255, 255), 3)
cv2.circle(rgb, p1, 12, (255, 80, 0), -1)
break
if aimed is not None:
if aimed == hold_index:
hold_frames += 1
else:
hold_index = aimed
hold_frames = 1
if hold_frames >= HOLD_NEED and aimed != active:
lights.light_only(aimed)
active = aimed
print(f"ON {cans[aimed].label}", flush=True)
else:
hold_index = None
hold_frames = 0
draw_stage_overlay(rgb, cans, active)
label = cans[active].label if active is not None else "—"
cv2.putText(
rgb,
f"point → {label} [q] quit [b] blackout",
(40, 60),
cv2.FONT_HERSHEY_SIMPLEX,
1.0,
(240, 240, 240),
2,
cv2.LINE_AA,
)
display = cv2.flip(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR), 1)
cv2.imshow(WINDOW_NAME, display)
cv2.setWindowProperty(
WINDOW_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN
)
key = cv2.waitKey(5) & 0xFF
if key == ord("q"):
break
if key == ord("b"):
lights.blackout()
active = None
print("blackout", flush=True)
finally:
lights.close()
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""Flow Forum — web controller for beamZ BCC145 parcans over Art-Net."""
from __future__ import annotations
import asyncio
import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from stupidArtnet import StupidArtnet
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from artnet_refresh import ArtNetRefresh
from bcc145 import PRESETS, Rig
from live_reload import LiveReload
ROOT = Path(__file__).resolve().parent
STATIC = ROOT / "static"
DEFAULT_IP = os.environ.get("ARTNET_IP", "dmx-gateway.local")
DEFAULT_UNIVERSE = int(os.environ.get("ARTNET_UNIVERSE", "0"))
RELOAD = os.environ.get("RELOAD", "1").lower() not in ("0", "false", "no")
class ConfigBody(BaseModel):
ip: str | None = None
universe: int | None = Field(default=None, ge=0, le=32767)
start_1: int | None = Field(default=None, ge=1, le=512, description="1-based DMX start of #1")
class MasterBody(BaseModel):
dimmer: int | None = Field(default=None, ge=0, le=255)
strobe: int | None = Field(default=None, ge=0, le=255)
red: int | None = Field(default=None, ge=0, le=255)
green: int | None = Field(default=None, ge=0, le=255)
blue: int | None = Field(default=None, ge=0, le=255)
white: int | None = Field(default=None, ge=0, le=255)
macro: int | None = Field(default=None, ge=0, le=255)
speed: int | None = Field(default=None, ge=0, le=255)
class FixtureBody(MasterBody):
enabled: bool | None = None
class PresetBody(BaseModel):
name: str
dimmer: int | None = Field(default=255, ge=0, le=255)
class SelectBody(BaseModel):
enabled: list[bool]
class NoCacheStaticMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next) -> Response:
response = await call_next(request)
path = request.url.path
if path == "/" or path.startswith("/static/"):
response.headers["Cache-Control"] = "no-store, max-age=0"
return response
artnet: StupidArtnet
refresh: ArtNetRefresh
rig: Rig
live_reload: LiveReload | None = None
def push() -> None:
refresh.update(rig.apply)
@asynccontextmanager
async def lifespan(_app: FastAPI):
global artnet, refresh, rig, live_reload
artnet = StupidArtnet(
target_ip=DEFAULT_IP,
universe=DEFAULT_UNIVERSE,
packet_size=512,
fps=40,
)
refresh = ArtNetRefresh(artnet)
refresh.start()
rig = Rig()
push()
if RELOAD:
live_reload = LiveReload([STATIC])
live_reload.start(asyncio.get_running_loop())
else:
live_reload = None
yield
if live_reload is not None:
live_reload.stop()
live_reload = None
refresh.stop(blackout=True)
artnet.close()
app = FastAPI(title="Flow Forum BCC145", lifespan=lifespan)
app.add_middleware(NoCacheStaticMiddleware)
app.mount("/static", StaticFiles(directory=STATIC), name="static")
@app.get("/")
def index():
return FileResponse(STATIC / "index.html")
@app.get("/api/dev/events")
async def dev_events():
"""SSE: frontend changes + reconnect-after-backend-reload → browser refresh."""
if not RELOAD or live_reload is None:
raise HTTPException(404, "live reload disabled")
queue = live_reload.subscribe()
async def event_stream():
try:
yield "data: connected\n\n"
while True:
try:
msg = await asyncio.wait_for(queue.get(), timeout=20.0)
yield f"data: {msg}\n\n"
except asyncio.TimeoutError:
yield ": keepalive\n\n"
finally:
live_reload.unsubscribe(queue)
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-store",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@app.get("/api/state")
def get_state():
return {
"ip": artnet.target_ip,
"universe": artnet.universe,
"streaming": refresh.is_running(),
"reload": RELOAD,
**rig.status(),
}
@app.post("/api/config")
def set_config(body: ConfigBody):
if body.start_1 is not None:
rig.start_1 = body.start_1
def configure(a: StupidArtnet) -> None:
if body.ip is not None:
a.target_ip = body.ip
if body.universe is not None:
a.set_universe(body.universe)
refresh.update(configure)
push()
return get_state()
@app.post("/api/master")
def set_master(body: MasterBody):
rig.set_all(**body.model_dump(exclude_none=True))
push()
return get_state()
@app.post("/api/fixture/{index}")
def set_fixture(index: int, body: FixtureBody):
if not 0 <= index < len(rig.fixtures):
raise HTTPException(404, "fixture not found")
fx = rig.fixtures[index]
data = body.model_dump(exclude_none=True)
for key, val in data.items():
setattr(fx, key, val)
push()
return get_state()
@app.post("/api/select")
def set_select(body: SelectBody):
if len(body.enabled) != len(rig.fixtures):
raise HTTPException(400, f"expected {len(rig.fixtures)} flags")
for fx, en in zip(rig.fixtures, body.enabled):
fx.enabled = en
push()
return get_state()
@app.post("/api/preset")
def set_preset(body: PresetBody):
if body.name not in PRESETS:
raise HTTPException(404, f"unknown preset {body.name!r}")
r, g, b, w = PRESETS[body.name]
dim = 255 if body.dimmer is None else body.dimmer
rig.enable_all()
rig.set_all(
dimmer=dim,
strobe=0,
red=r,
green=g,
blue=b,
white=w,
macro=0,
speed=0,
only_enabled=False,
)
push()
return get_state()
@app.post("/api/blackout")
def blackout():
rig.blackout()
push()
return get_state()
@app.post("/api/full")
def full_on():
"""All fixtures: dimmer full, white open (safe open look)."""
rig.enable_all()
rig.set_all(
dimmer=255,
strobe=0,
red=0,
green=0,
blue=0,
white=255,
macro=0,
speed=0,
only_enabled=False,
)
push()
return get_state()
if __name__ == "__main__":
import sys
import uvicorn
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
uvicorn.run(
"server:app",
host=os.environ.get("HOST", "0.0.0.0"),
port=int(os.environ.get("PORT", "8080")),
reload=RELOAD,
# Python only — static is live-reloaded in-browser via SSE (no Art-Net blip)
reload_dirs=[str(ROOT)],
reload_includes=["*.py"],
reload_excludes=["*.pyc", "static/*"],
)
+113
View File
@@ -0,0 +1,113 @@
"""XCHC stage layout for pointing.
QLC+ map (metres): Y=0 at row of 4, +Y toward audience, X=0 centre.
Camera is in the middle of the row of 4 (#3–#6) and faces the performer
(looks +Y, toward the audience). The performer faces the camera.
AUDIENCE (+Y) ← performer stands this side, faces CAM
#1 · · #8
#2 · · #7
M1 M2
#3 #4 [CAM] #5 #6 ← row of 4 (y=0); CAM looks up this page
Image (unmirrored): left = stage −X (#1–#4), right = stage +X (#5–#8).
Performer's left = stage +X = image right.
"""
from __future__ import annotations
import json
import math
from dataclasses import dataclass
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
MAP_PATH = ROOT / "stage" / "map.json"
# Middle of #3–#6; facing performer / audience (+Y)
CAMERA_X = 0.0
CAMERA_Y = 0.0
CAMERA_LOOKS = "+Y"
HFOV_RAD = math.radians(140.0)
@dataclass(frozen=True)
class Can:
index: int # 0–7 → BCC145 #1–#8
label: str
x: float
y: float
u: float # normalized image x (0=left/−X, 1=right/+X)
v: float # normalized image y (0=top/toward audience, 1=bottom/near cam)
def _project(fx: float, fy: float) -> tuple[float, float]:
"""Stage metres → camera image UV (CAM at origin looking +Y at performer)."""
dx = fx - CAMERA_X
dy = fy - CAMERA_Y
bearing = math.atan2(dx, max(dy, 0.05))
bearing_u = 0.5 + bearing / HFOV_RAD
lateral_u = 0.5 + (dx / 3.5) * 0.48
w = min(1.0, max(dy, 0.0) / 1.2)
u = (1.0 - w) * lateral_u + w * bearing_u
v = 0.78 - 0.28 * (dy / 2.4)
return (min(1.0, max(0.0, u)), min(1.0, max(0.0, v)))
def load_cans(map_path: Path = MAP_PATH) -> list[Can]:
data = json.loads(map_path.read_text())
cans: list[Can] = []
for _key, fx in data["fixtures"].items():
if fx.get("kind") != "can":
continue
label = fx["label"]
index = int(label.lstrip("#")) - 1
u, v = _project(fx["x"], fx["y"])
cans.append(Can(index=index, label=label, x=fx["x"], y=fx["y"], u=u, v=v))
cans.sort(key=lambda c: c.index)
return cans
def pick_can(
mcp_uv: tuple[float, float],
tip_uv: tuple[float, float],
cans: list[Can],
*,
max_angle_deg: float = 28.0,
) -> Can | None:
"""Pick the can the index finger points at (camera UV, unmirrored)."""
mcp = np.array(mcp_uv, dtype=float)
tip = np.array(tip_uv, dtype=float)
direction = tip - mcp
norm = float(np.linalg.norm(direction))
if norm < 0.02:
return None
direction /= norm
max_angle = math.radians(max_angle_deg)
best: Can | None = None
best_score = float("inf")
for can in cans:
pos = np.array([can.u, can.v], dtype=float)
to_can = pos - tip
along = float(np.dot(to_can, direction))
if along < -0.02:
continue
perp = float(np.linalg.norm(to_can - along * direction))
angle = math.atan2(perp, max(along, 1e-6))
if angle > max_angle:
continue
score = angle * 2.0 + perp + max(0.0, -along)
if score < best_score:
best_score = score
best = can
if best is not None:
return best
tip_x, tip_y = tip_uv
return min(cans, key=lambda c: (c.u - tip_x) ** 2 + (c.v - tip_y) ** 2)
+261
View File
@@ -0,0 +1,261 @@
(() => {
const $ = (sel) => document.querySelector(sel);
const state = {
fixtures: [],
macros: [],
presets: {},
debounce: null,
};
const masterKeys = [
"dimmer",
"strobe",
"red",
"green",
"blue",
"white",
"macro",
"speed",
];
async function api(path, body) {
const opts = body === undefined
? {}
: {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
};
const res = await fetch(path, opts);
if (!res.ok) {
const text = await res.text();
throw new Error(text || res.statusText);
}
return res.json();
}
function clamp(n) {
return Math.max(0, Math.min(255, n | 0));
}
function mixPreview(fx) {
const d = (fx.dimmer ?? 255) / 255;
const r = Math.round((fx.red || 0) * d);
const g = Math.round((fx.green || 0) * d);
const b = Math.round((fx.blue || 0) * d);
const w = Math.round((fx.white || 0) * d);
// Approximate white LED contribution
const rr = Math.min(255, r + Math.round(w * 0.95));
const gg = Math.min(255, g + Math.round(w * 0.92));
const bb = Math.min(255, b + Math.round(w * 0.88));
return `rgb(${rr}, ${gg}, ${bb})`;
}
function macroLabel(value) {
for (const m of state.macros) {
if (value >= m.min && value <= m.max) return `${value} · ${m.label}`;
}
return String(value);
}
function selectedFixtures() {
return state.fixtures.filter((f) => f.enabled);
}
function syncMasterFromSelection() {
const sel = selectedFixtures();
const hint = $("#selection-hint");
if (!sel.length) {
hint.textContent = "(none selected)";
return;
}
hint.textContent =
sel.length === state.fixtures.length
? "(all)"
: `(${sel.map((f) => f.name).join(" ")})`;
const src = sel[0];
for (const key of masterKeys) {
const input = $(`#m-${key}`);
if (!input) continue;
const same = sel.every((f) => f[key] === src[key]);
input.value = same ? src[key] : src[key];
input.nextElementSibling.textContent = same ? src[key] : "—";
}
$("#macro-label").textContent = macroLabel(src.macro);
$("#master-swatch").style.background = mixPreview(src);
const hex = rgbToHex(src.red, src.green, src.blue);
if (hex) $("#color").value = hex;
}
function rgbToHex(r, g, b) {
const h = (n) => clamp(n).toString(16).padStart(2, "0");
return `#${h(r)}${h(g)}${h(b)}`;
}
function hexToRgb(hex) {
const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!m) return null;
return {
red: parseInt(m[1], 16),
green: parseInt(m[2], 16),
blue: parseInt(m[3], 16),
};
}
function renderFixtures() {
const grid = $("#fixture-grid");
grid.innerHTML = "";
for (const fx of state.fixtures) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `fixture${fx.enabled ? " on" : ""}`;
btn.innerHTML = `
<div class="name">${fx.name}</div>
<div class="addr">DMX ${fx.address_1}</div>
<div class="lamp" style="background:${fx.enabled ? mixPreview(fx) : "#222"}"></div>
`;
btn.addEventListener("click", async () => {
const enabled = state.fixtures.map((f) =>
f.id === fx.id ? !f.enabled : f.enabled
);
applyState(await api("/api/select", { enabled }));
});
grid.appendChild(btn);
}
}
function renderPresets() {
const box = $("#presets");
box.innerHTML = "";
for (const name of Object.keys(state.presets)) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "btn";
btn.textContent = name;
const p = state.presets[name];
btn.style.boxShadow = `inset 0 -3px 0 rgb(${p.r},${p.g},${p.b})`;
btn.addEventListener("click", async () => {
applyState(await api("/api/preset", { name }));
});
box.appendChild(btn);
}
}
function applyState(data) {
state.fixtures = data.fixtures;
state.macros = data.macros || [];
state.presets = data.presets || {};
$("#ip").value = data.ip;
$("#universe").value = data.universe;
$("#start").value = data.start_1;
const stream = $("#stream-status");
if (data.streaming) {
stream.textContent = `live → ${data.ip} / uni ${data.universe}`;
stream.classList.add("live");
} else {
stream.textContent = "not streaming";
stream.classList.remove("live");
}
if (!$("#presets").children.length) renderPresets();
renderFixtures();
syncMasterFromSelection();
}
function queueMaster(partial) {
clearTimeout(state.debounce);
state.debounce = setTimeout(async () => {
applyState(await api("/api/master", partial));
}, 40);
}
function bindMasterSliders() {
for (const key of masterKeys) {
const input = $(`#m-${key}`);
input.addEventListener("input", () => {
const value = clamp(input.value);
input.nextElementSibling.textContent = value;
if (key === "macro") $("#macro-label").textContent = macroLabel(value);
const patch = { [key]: value };
// live swatch for colour channels
if (["dimmer", "red", "green", "blue", "white"].includes(key)) {
const preview = {
dimmer: clamp($("#m-dimmer").value),
red: clamp($("#m-red").value),
green: clamp($("#m-green").value),
blue: clamp($("#m-blue").value),
white: clamp($("#m-white").value),
};
$("#master-swatch").style.background = mixPreview(preview);
}
queueMaster(patch);
});
}
$("#color").addEventListener("input", (e) => {
const rgb = hexToRgb(e.target.value);
if (!rgb) return;
$("#m-red").value = rgb.red;
$("#m-green").value = rgb.green;
$("#m-blue").value = rgb.blue;
$("#m-red").nextElementSibling.textContent = rgb.red;
$("#m-green").nextElementSibling.textContent = rgb.green;
$("#m-blue").nextElementSibling.textContent = rgb.blue;
$("#master-swatch").style.background = mixPreview({
dimmer: clamp($("#m-dimmer").value),
...rgb,
white: clamp($("#m-white").value),
});
queueMaster(rgb);
});
}
function bindActions() {
$("#apply-config").addEventListener("click", async () => {
applyState(
await api("/api/config", {
ip: $("#ip").value.trim(),
universe: Number($("#universe").value),
start_1: Number($("#start").value),
})
);
});
$("#blackout").addEventListener("click", async () => {
applyState(await api("/api/blackout"));
});
$("#full").addEventListener("click", async () => {
applyState(await api("/api/full"));
});
$("#all-on").addEventListener("click", async () => {
applyState(
await api("/api/select", {
enabled: state.fixtures.map(() => true),
})
);
});
$("#all-off").addEventListener("click", async () => {
applyState(
await api("/api/select", {
enabled: state.fixtures.map(() => false),
})
);
});
}
async function boot() {
bindMasterSliders();
bindActions();
applyState(await api("/api/state"));
renderPresets();
}
boot().catch((err) => {
console.error(err);
alert(`Failed to load controller: ${err.message}`);
});
})();
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flow Forum — BCC145</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Outfit:wght@400;600;700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<div class="app">
<header class="top">
<div class="brand">
<p class="brand-name">Flow Forum</p>
<p class="brand-sub">beamZ BCC145 · 8ch · <span id="stream-status">…</span></p>
</div>
<div class="link">
<label>Art-Net IP
<input id="ip" type="text" spellcheck="false" />
</label>
<label>Uni
<input id="universe" type="number" min="0" max="32767" />
</label>
<label>DMX #1
<input id="start" type="number" min="1" max="505" title="1-based start address of fixture #1" />
</label>
<button type="button" id="apply-config" class="btn">Apply</button>
</div>
</header>
<section class="strip">
<button type="button" id="blackout" class="btn danger">Blackout</button>
<button type="button" id="full" class="btn">Open white</button>
<div id="presets" class="presets"></div>
</section>
<section class="master">
<h2>Master <span id="selection-hint"></span></h2>
<div class="sliders">
<label class="slider dim">Dimmer <input id="m-dimmer" type="range" min="0" max="255" /><output></output></label>
<label class="slider strobe">Strobe <input id="m-strobe" type="range" min="0" max="255" /><output></output></label>
<label class="slider red">Red <input id="m-red" type="range" min="0" max="255" /><output></output></label>
<label class="slider green">Green <input id="m-green" type="range" min="0" max="255" /><output></output></label>
<label class="slider blue">Blue <input id="m-blue" type="range" min="0" max="255" /><output></output></label>
<label class="slider white">White <input id="m-white" type="range" min="0" max="255" /><output></output></label>
<label class="slider macro">Macro <input id="m-macro" type="range" min="0" max="255" /><output></output></label>
<label class="slider speed">Speed <input id="m-speed" type="range" min="0" max="255" /><output></output></label>
</div>
<p id="macro-label" class="macro-label"></p>
<div class="swatch-row">
<div id="master-swatch" class="swatch"></div>
<input id="color" type="color" value="#ffffff" title="RGB colour" />
</div>
</section>
<section class="fixtures">
<div class="fixtures-head">
<h2>Cans</h2>
<div class="fixture-actions">
<button type="button" id="all-on" class="btn ghost">All</button>
<button type="button" id="all-off" class="btn ghost">None</button>
</div>
</div>
<div id="fixture-grid" class="fixture-grid"></div>
</section>
</div>
<script src="/static/app.js"></script>
<script src="/static/live-reload.js"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
/* Dev live-reload client: static file changes + backend restart. */
(() => {
let hadConnection = false;
function connect() {
const es = new EventSource("/api/dev/events");
es.onopen = () => {
if (hadConnection) {
location.reload();
return;
}
hadConnection = true;
};
es.onmessage = (ev) => {
if (ev.data === "reload") location.reload();
};
es.onerror = () => {
es.close();
setTimeout(connect, 600);
};
}
fetch("/api/state")
.then((r) => r.json())
.then((s) => {
if (s.reload) connect();
})
.catch(() => {});
})();
+352
View File
@@ -0,0 +1,352 @@
:root {
--bg0: #e8e2d6;
--bg1: #f4efe6;
--ink: #1a1c1e;
--muted: #5c5f66;
--line: #c9c2b4;
--panel: #fffdf8;
--accent: #c45c26;
--accent-ink: #fff8f2;
--live: #2f6b4f;
--danger: #9b2c2c;
--red: #c0392b;
--green: #2d6a4f;
--blue: #1d4e89;
--white: #8a8578;
--mono: "IBM Plex Mono", ui-monospace, monospace;
--sans: "Outfit", system-ui, sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background:
radial-gradient(1200px 600px at 10% -10%, #f7e8d4 0%, transparent 55%),
radial-gradient(900px 500px at 100% 0%, #d9e4df 0%, transparent 50%),
var(--bg0);
color: var(--ink);
font-family: var(--sans);
}
.app {
max-width: 1100px;
margin: 0 auto;
padding: 1.25rem 1.25rem 3rem;
display: grid;
gap: 1.25rem;
}
.top {
display: flex;
flex-wrap: wrap;
gap: 1rem 1.5rem;
align-items: end;
justify-content: space-between;
border-bottom: 1px solid var(--line);
padding-bottom: 1rem;
}
.brand-name {
margin: 0;
font-size: clamp(2rem, 5vw, 2.75rem);
font-weight: 700;
letter-spacing: -0.03em;
line-height: 1;
}
.brand-sub {
margin: 0.25rem 0 0;
color: var(--muted);
font-family: var(--mono);
font-size: 0.8rem;
}
#stream-status.live {
color: var(--live);
}
.link {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
align-items: end;
}
.link label {
display: grid;
gap: 0.2rem;
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--muted);
}
.link input {
font-family: var(--mono);
font-size: 0.9rem;
padding: 0.45rem 0.55rem;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel);
color: var(--ink);
min-width: 0;
}
#ip {
width: 9.5rem;
}
#universe,
#start {
width: 4.5rem;
}
.btn {
font-family: var(--sans);
font-weight: 600;
font-size: 0.9rem;
border: 1px solid var(--ink);
background: var(--ink);
color: var(--bg1);
border-radius: 6px;
padding: 0.5rem 0.85rem;
cursor: pointer;
}
.btn:hover {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-ink);
}
.btn.ghost {
background: transparent;
color: var(--ink);
}
.btn.ghost:hover {
background: var(--ink);
color: var(--bg1);
}
.btn.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
}
.btn.danger:hover {
filter: brightness(1.08);
}
.btn.active {
background: var(--live);
border-color: var(--live);
color: #fff;
}
.strip {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.presets .btn {
background: var(--panel);
color: var(--ink);
border-color: var(--line);
padding: 0.4rem 0.65rem;
font-size: 0.8rem;
}
.presets .btn:hover {
border-color: var(--ink);
background: var(--ink);
color: var(--bg1);
}
.master,
.fixtures {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
padding: 1rem 1.1rem 1.2rem;
}
h2 {
margin: 0 0 0.85rem;
font-size: 1rem;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted);
font-weight: 600;
}
#selection-hint {
font-family: var(--mono);
font-size: 0.75rem;
text-transform: none;
letter-spacing: 0;
}
.sliders {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 0.75rem 1rem;
}
.slider {
display: grid;
gap: 0.35rem;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--muted);
}
.slider output {
font-family: var(--mono);
color: var(--ink);
font-size: 0.85rem;
}
.slider input[type="range"] {
width: 100%;
accent-color: var(--ink);
}
.slider.red input {
accent-color: var(--red);
}
.slider.green input {
accent-color: var(--green);
}
.slider.blue input {
accent-color: var(--blue);
}
.slider.white input {
accent-color: var(--white);
}
.slider.dim input {
accent-color: var(--accent);
}
.macro-label {
margin: 0.75rem 0 0;
font-family: var(--mono);
font-size: 0.8rem;
color: var(--muted);
min-height: 1.2em;
}
.swatch-row {
display: flex;
gap: 0.75rem;
align-items: center;
margin-top: 1rem;
}
.swatch {
width: 3rem;
height: 3rem;
border-radius: 8px;
border: 1px solid var(--line);
background: #000;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.15);
}
#color {
width: 3rem;
height: 3rem;
padding: 0;
border: 1px solid var(--line);
border-radius: 8px;
background: transparent;
cursor: pointer;
}
.fixtures-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}
.fixtures-head h2 {
margin: 0;
}
.fixture-actions {
display: flex;
gap: 0.4rem;
}
.fixture-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 0.65rem;
margin-top: 0.85rem;
}
.fixture {
border: 1px solid var(--line);
border-radius: 10px;
padding: 0.7rem;
background: var(--bg1);
cursor: pointer;
text-align: left;
font: inherit;
color: inherit;
transition: border-color 120ms ease, transform 120ms ease;
}
.fixture:hover {
border-color: var(--ink);
}
.fixture.on {
border-color: var(--live);
box-shadow: 0 0 0 1px var(--live);
}
.fixture .name {
font-weight: 700;
font-size: 1.05rem;
}
.fixture .addr {
font-family: var(--mono);
font-size: 0.7rem;
color: var(--muted);
margin-top: 0.15rem;
}
.fixture .lamp {
margin-top: 0.55rem;
height: 1.4rem;
border-radius: 4px;
border: 1px solid var(--line);
background: #111;
}
@media (max-width: 640px) {
.top {
align-items: start;
}
.link {
width: 100%;
}
}
+67
View File
@@ -0,0 +1,67 @@
{
"units": "metres",
"building_width": 7.0,
"origin": "Y=0 at row of 4; +Y toward audience; X=0 centre",
"fixtures": {
"#1": {
"x": -3.5,
"y": 2.4,
"label": "#1",
"kind": "can"
},
"#2": {
"x": -3.5,
"y": 1.2,
"label": "#2",
"kind": "can"
},
"#3": {
"x": -1.8,
"y": 0.0,
"label": "#3",
"kind": "can"
},
"#4": {
"x": -0.6,
"y": 0.0,
"label": "#4",
"kind": "can"
},
"#5": {
"x": 0.6,
"y": 0.0,
"label": "#5",
"kind": "can"
},
"#6": {
"x": 1.8,
"y": 0.0,
"label": "#6",
"kind": "can"
},
"#7": {
"x": 3.5,
"y": 1.2,
"label": "#7",
"kind": "can"
},
"#8": {
"x": 3.5,
"y": 2.4,
"label": "#8",
"kind": "can"
},
"M1": {
"x": -0.3,
"y": 1.1,
"label": "M1",
"kind": "mover"
},
"M2": {
"x": 0.3,
"y": 1.1,
"label": "M2",
"kind": "mover"
}
}
}
+44
View File
@@ -0,0 +1,44 @@
"""Live Art-Net smoke test against dmx-gateway.local.
Sets DMX 88 (dimmer) and 90 (red) on BCC145 #1 — stop QLC+ output first.
"""
from __future__ import annotations
import os
import time
from stupidArtnet import StupidArtnet
from artnet_refresh import ArtNetRefresh
TARGET = os.environ.get("ARTNET_IP", "dmx-gateway.local")
UNIVERSE = int(os.environ.get("ARTNET_UNIVERSE", "0"))
HOLD_S = float(os.environ.get("ARTNET_TEST_HOLD", "3"))
def test_set_channels_88_and_90_to_255():
artnet = StupidArtnet(
target_ip=TARGET,
universe=UNIVERSE,
packet_size=512,
fps=40,
)
refresh = ArtNetRefresh(artnet)
def set_red(a: StupidArtnet) -> None:
a.set_single_value(88, 255) # dimmer
a.set_single_value(89, 0) # strobe off
a.set_single_value(90, 255) # red
refresh.update(set_red)
assert artnet.buffer[87] == 255
assert artnet.buffer[88] == 0
assert artnet.buffer[89] == 255
refresh.start()
try:
time.sleep(HOLD_S)
finally:
refresh.stop(blackout=True)
artnet.close()
+24
View File
@@ -0,0 +1,24 @@
"""Stage layout / pointing unit tests (no camera)."""
from stage_layout import load_cans, pick_can
def test_load_eight_cans():
cans = load_cans()
assert len(cans) == 8
assert [c.label for c in cans] == [f"#{i}" for i in range(1, 9)]
def test_pick_upper_left_is_wall_can():
cans = load_cans()
hit = pick_can((0.35, 0.55), (0.18, 0.32), cans)
assert hit is not None
assert hit.label in {"#1", "#2"}
def test_pick_bottom_row():
cans = load_cans()
left = pick_can((0.40, 0.70), (0.28, 0.78), cans)
right = pick_can((0.60, 0.70), (0.72, 0.78), cans)
assert left is not None and left.index <= 3
assert right is not None and right.index >= 4