Files
qlcplus/scripts/position_movers.py
T

998 lines
32 KiB
Python

#!/usr/bin/env python3
"""Web page to aim the two cabaret movers and save pan/tilt positions.
Drives the Small Eye 7 heads over Art-Net while the sliders move, then
writes named looks to a JSON file. Stop QLC+ Art-Net output first so the
two sources do not fight. Ctrl+C blackout.
pipenv run positions
open http://127.0.0.1:8765
Saved file (default shows/mover_positions.json):
{
"positions": {
"wall": {
"m1": {"pan": 179, "tilt": 36},
"m2": {"pan": 179, "tilt": 36}
}
}
}
"""
from __future__ import annotations
import argparse
import ipaddress
import json
import socket
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from cabaret_movers import (
DEFAULT_NODE,
FOCUS_DEFAULT,
M1_ADDR,
M2_ADDR,
PALETTE,
POSITIONS,
ArtNetSender,
Mover,
clamp,
discover_artnet_nodes,
)
# Aiming colours. White is listed first because it shows the beam clearly.
COLORS: dict[str, tuple[int, int, int]] = {"white": (255, 255, 255), **PALETTE}
COLOR_NAMES = ("white", "amber", "red", "orange", "yellow", "green", "blue", "pink", "purple")
PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mover positions</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0;
font: 16px/1.4 system-ui, sans-serif;
background: #12141a;
color: #eee;
}
main { max-width: 34rem; margin: 0 auto; padding: 1.25rem 1.25rem 3rem; }
h1 { font-size: 1.35rem; font-weight: 650; margin: 0 0 0.2rem; }
h2 { font-size: 0.95rem; font-weight: 600; margin: 1.4rem 0 0.2rem; color: #bbb; }
.meta, .hint { color: #8e98a8; font-size: 0.85rem; }
.meta { margin: 0 0 1rem; word-break: break-all; }
.targets, .colors { display: flex; gap: 0.5rem; margin: 0.4rem 0 0.6rem; }
.colors { flex-wrap: wrap; }
button, input[type="text"], input[type="number"], select { font: inherit; color: inherit; }
.device { display: flex; gap: 0.5rem; margin: 0 0 1rem; }
.device select, .device button, .colors button {
border: 1px solid #3a4050;
background: #1c2030;
border-radius: 8px;
padding: 0.55rem 0.75rem;
cursor: pointer;
}
.device select { flex: 1; min-width: 0; }
.colors button {
display: flex;
align-items: center;
gap: 0.4rem;
border-radius: 999px;
padding: 0.28rem 0.7rem 0.28rem 0.3rem;
}
.swatch {
width: 1.15rem;
height: 1.15rem;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.45);
}
.colors button.active { border-color: #f0a030; box-shadow: 0 0 0 1px #f0a030; }
.section { margin: 0.9rem 0 0.15rem; color: #bbb; font-size: 0.95rem; }
.targets button, .add, .del {
border: 1px solid #3a4050;
background: #1c2030;
border-radius: 8px;
padding: 0.6rem 0.9rem;
cursor: pointer;
}
.targets button { flex: 1; }
.targets button.active {
background: #f0a030;
border-color: #f0a030;
color: #1a1206;
font-weight: 650;
}
.slider { margin: 0.85rem 0; }
.slider .top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.15rem;
}
input[type="number"] {
width: 4.5rem;
text-align: right;
background: #1c2030;
border: 1px solid #3a4050;
border-radius: 6px;
padding: 0.2rem 0.4rem;
}
input[type="range"] {
width: 100%;
height: 2rem;
accent-color: #f0a030;
cursor: pointer;
}
.save { display: flex; gap: 0.5rem; margin-top: 1.1rem; }
.save input[type="text"] {
flex: 1;
min-width: 0;
background: #1c2030;
border: 1px solid #3a4050;
border-radius: 8px;
padding: 0.6rem 0.75rem;
}
.add {
background: #f0a030;
border-color: #f0a030;
color: #1a1206;
font-weight: 650;
white-space: nowrap;
}
.add:disabled { opacity: 0.45; cursor: default; }
.status { min-height: 1.3rem; margin: 0.6rem 0 0; color: #f0a030; }
ul { list-style: none; padding: 0; margin: 0; }
li {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.35rem 0;
border-bottom: 1px solid #262b38;
}
li .name {
flex: 1;
text-align: left;
background: none;
border: 0;
padding: 0.35rem 0;
cursor: pointer;
font: inherit;
color: inherit;
}
li .name:hover { color: #f0a030; }
li .nums {
color: #8e98a8;
font-variant-numeric: tabular-nums;
font-size: 0.82rem;
white-space: nowrap;
}
.del { padding: 0.3rem 0.55rem; color: #e07a7a; }
.empty { color: #8e98a8; margin: 0.4rem 0 0; }
</style>
</head>
<body>
<main>
<h1>Mover positions</h1>
<p class="meta" id="meta">Connecting…</p>
<div class="section">Art-Net to DMX</div>
<div class="device">
<select id="node" aria-label="Art-Net to DMX device"></select>
<button type="button" id="refresh-nodes">Refresh</button>
</div>
<p class="hint">Both movers share this DMX output.</p>
<div class="targets" id="targets">
<button type="button" data-target="m1">M1</button>
<button type="button" data-target="m2">M2</button>
<button type="button" data-target="both" class="active">Both</button>
</div>
<p class="hint" id="differ" hidden>M1 and M2 are aimed differently. Moving a slider sets both.</p>
<div class="section">Color <span class="hint" id="color-note"></span></div>
<div class="colors" id="colors"></div>
<div class="slider">
<div class="top"><span>Pan</span>
<input id="pan-num" type="number" min="0" max="255" value="128" inputmode="numeric">
</div>
<input id="pan" type="range" min="0" max="255" value="128">
</div>
<div class="slider">
<div class="top"><span>Tilt</span>
<input id="tilt-num" type="number" min="0" max="255" value="128" inputmode="numeric">
</div>
<input id="tilt" type="range" min="0" max="255" value="128">
</div>
<div class="slider">
<div class="top"><span>Dimmer</span>
<input id="dim-num" type="number" min="0" max="255" value="255" inputmode="numeric">
</div>
<input id="dim" type="range" min="0" max="255" value="255">
</div>
<form class="save" id="save-form">
<input id="name" type="text" placeholder="Position name" maxlength="48" autocomplete="off">
<button class="add" id="add" type="submit" disabled>Add position</button>
</form>
<p class="status" id="status"></p>
<h2>Saved</h2>
<p class="empty" id="empty">Aim the beam, name it, then add the position.</p>
<ul id="list"></ul>
<p class="hint">Arrow keys nudge pan and tilt. Shift moves by 10. Up sends the beam toward tilt 0.</p>
</main>
<script>
const pan = document.getElementById("pan");
const tilt = document.getElementById("tilt");
const dim = document.getElementById("dim");
const panNum = document.getElementById("pan-num");
const tiltNum = document.getElementById("tilt-num");
const dimNum = document.getElementById("dim-num");
const nameInput = document.getElementById("name");
const addBtn = document.getElementById("add");
const statusEl = document.getElementById("status");
const listEl = document.getElementById("list");
const emptyEl = document.getElementById("empty");
const differEl = document.getElementById("differ");
const nodeSel = document.getElementById("node");
const colorBox = document.getElementById("colors");
const colorNote = document.getElementById("color-note");
const refreshBtn = document.getElementById("refresh-nodes");
let state = null;
let target = "both";
let mute = false;
let aimBody = null;
let aiming = false;
function clampByte(value) {
const n = Math.round(Number(value));
if (Number.isNaN(n)) return 0;
return Math.max(0, Math.min(255, n));
}
function source() {
return target === "m2" ? state.m2 : state.m1;
}
function applySliders() {
mute = true;
const src = source();
pan.value = panNum.value = src.pan;
tilt.value = tiltNum.value = src.tilt;
dim.value = dimNum.value = state.dimmer;
mute = false;
const differ = state.m1.pan !== state.m2.pan || state.m1.tilt !== state.m2.tilt;
differEl.hidden = !(target === "both" && differ);
}
function renderList() {
listEl.replaceChildren();
const positions = state.positions || [];
emptyEl.hidden = positions.length > 0;
for (const pos of positions) {
const li = document.createElement("li");
const btn = document.createElement("button");
btn.type = "button";
btn.className = "name";
btn.textContent = pos.name;
btn.addEventListener("click", () => recall(pos.name));
const nums = document.createElement("span");
nums.className = "nums";
nums.textContent = "M1 " + pos.m1.pan + "/" + pos.m1.tilt + " M2 " + pos.m2.pan + "/" + pos.m2.tilt;
const del = document.createElement("button");
del.type = "button";
del.className = "del";
del.textContent = "Remove";
del.addEventListener("click", () => removePosition(pos.name));
li.append(btn, nums, del);
listEl.append(li);
}
}
function renderNodes() {
const ips = (state.nodes || []).map((node) => node.ip + "=" + node.name + "=" + (node.universe || "")).join("|");
if (nodeSel.dataset.ips !== ips) {
nodeSel.dataset.ips = ips;
nodeSel.replaceChildren();
for (const node of state.nodes || []) {
const opt = document.createElement("option");
opt.value = node.ip;
const bits = [];
if (node.name) bits.push(node.name);
bits.push(node.ip);
if (node.universe != null && node.universe !== "") bits.push("universe " + node.universe);
opt.textContent = bits.join(" ");
nodeSel.append(opt);
}
}
if (nodeSel.value !== state.artnet) nodeSel.value = state.artnet;
}
function renderColors() {
const chosen = target === "m2" ? state.color.m2 : state.color.m1;
const mixed = target === "both" && state.color.m1 !== state.color.m2;
colorNote.textContent = mixed ? "M1 " + state.color.m1 + " · M2 " + state.color.m2 : chosen;
colorBox.replaceChildren();
for (const color of state.colors || []) {
const btn = document.createElement("button");
btn.type = "button";
btn.classList.toggle("active", !mixed && color.name === chosen);
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.background = "rgb(" + color.rgb.join(",") + ")";
btn.append(swatch, document.createTextNode(color.name));
btn.addEventListener("click", () => setColor(color.name));
colorBox.append(btn);
}
}
function showState(next) {
state = next;
document.getElementById("meta").textContent = state.file;
renderNodes();
renderColors();
applySliders();
renderList();
}
async function postJSON(url, body) {
const res = await fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body || {}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || "Request failed");
return data;
}
async function setColor(name) {
try {
const data = await postJSON("/api/color", {target, color: name});
showState(data);
statusEl.textContent = name.charAt(0).toUpperCase() + name.slice(1) + " on";
} catch (err) {
statusEl.textContent = err.message || "Can't reach the position server";
}
}
async function queueAim() {
if (mute || !state) return;
const panV = clampByte(pan.value);
const tiltV = clampByte(tilt.value);
const dimV = clampByte(dim.value);
panNum.value = panV;
tiltNum.value = tiltV;
dimNum.value = dimV;
if (target === "both" || target === "m1") state.m1 = {pan: panV, tilt: tiltV};
if (target === "both" || target === "m2") state.m2 = {pan: panV, tilt: tiltV};
state.dimmer = dimV;
differEl.hidden = true;
aimBody = {target, pan: panV, tilt: tiltV, dimmer: dimV};
if (aiming) return;
aiming = true;
try {
while (aimBody) {
const body = aimBody;
aimBody = null;
const res = await fetch("/api/aim", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
});
if (!res.ok) statusEl.textContent = "Aim failed";
}
} catch (err) {
statusEl.textContent = "Can't reach the position server";
} finally {
aiming = false;
}
}
function bindPair(range, number) {
range.addEventListener("input", () => {
number.value = range.value;
queueAim();
});
number.addEventListener("input", () => {
range.value = clampByte(number.value);
queueAim();
});
}
bindPair(pan, panNum);
bindPair(tilt, tiltNum);
bindPair(dim, dimNum);
document.getElementById("targets").addEventListener("click", (ev) => {
const btn = ev.target.closest("button");
if (!btn || !state) return;
target = btn.dataset.target;
for (const el of document.querySelectorAll("#targets button")) {
el.classList.toggle("active", el === btn);
}
applySliders();
renderColors();
});
nodeSel.addEventListener("change", async () => {
const ip = nodeSel.value;
if (!state || ip === state.artnet) return;
nodeSel.disabled = true;
try {
const data = await postJSON("/api/node", {ip});
showState(data);
statusEl.textContent = "Art-Net " + ip;
} catch (err) {
statusEl.textContent = err.message || "Could not change Art-Net device";
nodeSel.value = state.artnet;
} finally {
nodeSel.disabled = false;
}
});
refreshBtn.addEventListener("click", async () => {
refreshBtn.disabled = true;
refreshBtn.textContent = "Looking…";
try {
const data = await postJSON("/api/nodes", {});
showState(data);
const count = (state.nodes || []).length;
statusEl.textContent = count + " Art-Net device" + (count === 1 ? "" : "s");
} catch (err) {
statusEl.textContent = err.message || "Could not look for Art-Net devices";
} finally {
refreshBtn.disabled = false;
refreshBtn.textContent = "Refresh";
}
});
nameInput.addEventListener("input", () => {
addBtn.disabled = !nameInput.value.trim();
});
document.getElementById("save-form").addEventListener("submit", async (ev) => {
ev.preventDefault();
const name = nameInput.value.trim();
if (!name) return;
addBtn.disabled = true;
try {
const res = await fetch("/api/positions", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({name}),
});
const data = await res.json();
if (!res.ok) {
statusEl.textContent = data.error || "Could not save";
addBtn.disabled = !nameInput.value.trim();
return;
}
showState(data);
nameInput.value = "";
statusEl.textContent = "Saved " + data.saved;
} catch (err) {
statusEl.textContent = "Can't reach the position server";
addBtn.disabled = !nameInput.value.trim();
}
});
async function recall(name) {
try {
const res = await fetch("/api/recall", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({name}),
});
const data = await res.json();
if (!res.ok) {
statusEl.textContent = data.error || "Could not recall";
return;
}
showState(data);
statusEl.textContent = "Recalled " + name;
} catch (err) {
statusEl.textContent = "Can't reach the position server";
}
}
async function removePosition(name) {
try {
const res = await fetch("/api/delete", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({name}),
});
const data = await res.json();
if (!res.ok) {
statusEl.textContent = data.error || "Could not remove";
return;
}
showState(data);
statusEl.textContent = "Removed " + name;
} catch (err) {
statusEl.textContent = "Can't reach the position server";
}
}
document.addEventListener("keydown", (ev) => {
if (!state || ev.target === nameInput) return;
const step = ev.shiftKey ? 10 : 1;
let handled = true;
if (ev.key === "ArrowLeft") pan.value = clampByte(Number(pan.value) - step);
else if (ev.key === "ArrowRight") pan.value = clampByte(Number(pan.value) + step);
else if (ev.key === "ArrowUp") tilt.value = clampByte(Number(tilt.value) - step);
else if (ev.key === "ArrowDown") tilt.value = clampByte(Number(tilt.value) + step);
else handled = false;
if (!handled) return;
ev.preventDefault();
queueAim();
});
fetch("/api/state").then((res) => res.json()).then(showState).catch(() => {
document.getElementById("meta").textContent = "Can't reach the position server";
});
</script>
</body>
</html>
"""
def read_positions(path: Path) -> dict[str, dict]:
if not path.exists():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise SystemExit(f"{path} is not valid JSON: {exc}") from exc
raw = data.get("positions", data) if isinstance(data, dict) else None
if not isinstance(raw, dict):
raise SystemExit(f"{path} must contain a positions object")
out: dict[str, dict] = {}
for name, entry in raw.items():
if not isinstance(entry, dict) or "m1" not in entry or "m2" not in entry:
raise SystemExit(f"{path}: position {name!r} needs m1 and m2 pan/tilt")
out[str(name)] = {"m1": point(entry["m1"]), "m2": point(entry["m2"])}
return out
def point(entry) -> dict[str, int]:
if isinstance(entry, (list, tuple)) and len(entry) == 2:
pan, tilt = entry
elif isinstance(entry, dict) and "pan" in entry and "tilt" in entry:
pan, tilt = entry["pan"], entry["tilt"]
else:
raise SystemExit("each mover needs pan and tilt")
return {"pan": clamp(pan), "tilt": clamp(tilt)}
def write_positions(path: Path, positions: dict[str, dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
text = json.dumps({"positions": positions}, indent=2) + "\n"
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(text, encoding="utf-8")
tmp.replace(path)
def position_list(positions: dict[str, dict]) -> list[dict]:
return [{"name": name, "m1": entry["m1"], "m2": entry["m2"]} for name, entry in positions.items()]
def clean_name(value) -> str:
name = " ".join(str(value).split())
if not name:
raise ValueError("Enter a position name")
if len(name) > 48:
raise ValueError("Name must be 48 characters or fewer")
return name
class Store:
def __init__(self, path: Path):
self.path = path
self._lock = threading.Lock()
self.positions = read_positions(path)
def snapshot(self) -> list[dict]:
with self._lock:
return position_list(self.positions)
def upsert(self, name: str, m1: dict, m2: dict) -> None:
with self._lock:
self.positions[name] = {
"m1": {"pan": m1["pan"], "tilt": m1["tilt"]},
"m2": {"pan": m2["pan"], "tilt": m2["tilt"]},
}
write_positions(self.path, self.positions)
def get(self, name: str) -> dict | None:
with self._lock:
entry = self.positions.get(name)
if entry is None:
return None
return {"m1": dict(entry["m1"]), "m2": dict(entry["m2"])}
def delete(self, name: str) -> bool:
with self._lock:
if name not in self.positions:
return False
del self.positions[name]
write_positions(self.path, self.positions)
return True
def clean_ip(value) -> str:
text = str(value).strip()
try:
addr = ipaddress.ip_address(text)
except ValueError as exc:
raise ValueError("Enter an Art-Net address") from exc
if not isinstance(addr, ipaddress.IPv4Address):
raise ValueError("Art-Net needs an IPv4 address")
return str(addr)
def clean_color(value) -> str:
name = str(value).strip().lower()
if name not in COLORS:
raise ValueError("Unknown color")
return name
GATEWAY_HOST = "dmx-gateway.local"
def lookup_gateway() -> dict[str, str] | None:
"""The LuxDMX Art-Net to DMX box at dmx-gateway.local, if it answers."""
ip = ""
name = GATEWAY_HOST
universe = ""
try:
with urllib.request.urlopen(f"http://{GATEWAY_HOST}/info.json", timeout=1.5) as res:
info = json.loads(res.read().decode("utf-8"))
if isinstance(info, dict):
ip = str(info.get("ip") or "")
host = str(info.get("hostname") or "dmx-gateway").strip()
name = host if "." in host else f"{host}.local"
for output in info.get("outputs") or []:
if isinstance(output, dict) and output.get("en"):
universe = str(int(output.get("uni", 0)))
break
except (OSError, json.JSONDecodeError, ValueError, TypeError):
pass
if not ip:
try:
ip = socket.getaddrinfo(GATEWAY_HOST, 6454, socket.AF_INET, socket.SOCK_DGRAM)[0][4][0]
except OSError:
return None
try:
ip = str(ipaddress.IPv4Address(ip))
except ValueError:
return None
node = {"ip": ip, "name": name}
if universe != "":
node["universe"] = universe
return node
def pin_gateway(nodes: list[dict[str, str]]) -> list[dict[str, str]]:
gateway = lookup_gateway()
if gateway is None:
return nodes
rest = [
node
for node in nodes
if node["ip"] != gateway["ip"] and node.get("name") != "no reply"
]
return [gateway] + rest
def include_ip(nodes: list[dict[str, str]], ip: str) -> list[dict[str, str]]:
kept = [node for node in nodes if node.get("name") != "no reply" or node["ip"] == ip]
if any(node["ip"] == ip for node in kept):
return kept
return [{"ip": ip, "name": ""}] + kept
class Rig:
def __init__(self, movers: dict[str, Mover]):
self.movers = movers
down_m1, down_m2 = POSITIONS["down"]
self.pan = {"m1": down_m1[0], "m2": down_m2[0]}
self.tilt = {"m1": down_m1[1], "m2": down_m2[1]}
self.color = {"m1": "white", "m2": "white"}
self.dimmer = 255
self._lock = threading.Lock()
self.push()
def push(self):
with self._lock:
self._push_locked()
def _push_locked(self):
for key, mover in self.movers.items():
mover.apply(
pan=self.pan[key],
tilt=self.tilt[key],
rgb=COLORS[self.color[key]],
dimmer=self.dimmer,
focus=FOCUS_DEFAULT,
speed=0,
)
def set_color(self, target: str, name: str):
if target not in ("m1", "m2", "both"):
raise ValueError("target must be m1, m2, or both")
name = clean_color(name)
with self._lock:
keys = ("m1", "m2") if target == "both" else (target,)
for key in keys:
self.color[key] = name
if self.dimmer == 0:
self.dimmer = 255
self._push_locked()
def update(self, *, target: str, pan: int, tilt: int, dimmer: int):
if target not in ("m1", "m2", "both"):
raise ValueError("target must be m1, m2, or both")
with self._lock:
keys = ("m1", "m2") if target == "both" else (target,)
for key in keys:
self.pan[key] = clamp(pan)
self.tilt[key] = clamp(tilt)
self.dimmer = clamp(dimmer)
self._push_locked()
def recall(self, entry: dict):
with self._lock:
self.pan["m1"] = entry["m1"]["pan"]
self.tilt["m1"] = entry["m1"]["tilt"]
self.pan["m2"] = entry["m2"]["pan"]
self.tilt["m2"] = entry["m2"]["tilt"]
self._push_locked()
def live(self) -> dict:
with self._lock:
return {
"m1": {"pan": self.pan["m1"], "tilt": self.tilt["m1"]},
"m2": {"pan": self.pan["m2"], "tilt": self.tilt["m2"]},
"color": {"m1": self.color["m1"], "m2": self.color["m2"]},
"dimmer": self.dimmer,
}
class App:
def __init__(
self,
rig: Rig,
store: Store,
sender: ArtNetSender,
nodes: list[dict[str, str]],
universe: int,
):
self.rig = rig
self.store = store
self.sender = sender
self.nodes = nodes
self.universe = universe
self._lock = threading.Lock()
def state(self, *, saved: str | None = None) -> dict:
payload = self.rig.live()
artnet = self.sender.destination()
with self._lock:
payload["nodes"] = [dict(node) for node in self.nodes]
payload["artnet"] = artnet
payload["colors"] = [{"name": name, "rgb": list(COLORS[name])} for name in COLOR_NAMES]
payload["file"] = str(self.store.path)
payload["positions"] = self.store.snapshot()
if saved is not None:
payload["saved"] = saved
return payload
def _universe_for(self, ip: str) -> int:
match = next((node for node in self.nodes if node["ip"] == ip), None)
if match and match.get("universe", "") != "":
return int(match["universe"])
return self.universe
def select_node(self, ip: str):
ip = clean_ip(ip)
with self._lock:
nodes = include_ip(self.nodes, ip)
nodes = pin_gateway(nodes)
with self._lock:
self.nodes = nodes
universe = self._universe_for(ip)
label = next((node["name"] for node in self.nodes if node["ip"] == ip and node.get("name")), "")
self.sender.set_dest(ip)
self.sender.set_universe(universe)
self.rig.push()
print(f"Art-Net → {ip} {label} universe {universe}".rstrip(), flush=True)
def refresh_nodes(self):
found = pin_gateway(discover_artnet_nodes())
current = self.sender.destination()
with self._lock:
self.nodes = include_ip(found, current)
def make_handler(app: App):
class Handler(BaseHTTPRequestHandler):
def log_request(self, code="-", size="-"):
if str(code).startswith("2"):
return
super().log_request(code, size)
def _body(self) -> dict:
length = int(self.headers.get("Content-Length", "0") or 0)
raw = self.rfile.read(length) if length else b"{}"
data = json.loads(raw.decode("utf-8") or "{}")
if not isinstance(data, dict):
raise ValueError("JSON object required")
return data
def _send(self, code: int, payload, content_type: str):
if isinstance(payload, str):
raw = payload.encode("utf-8")
else:
raw = json.dumps(payload).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _json(self, code: int, payload: dict):
self._send(code, payload, "application/json")
def _error(self, code: int, message: str):
self._json(code, {"error": message})
def do_GET(self):
path = urlparse(self.path).path
if path == "/":
self._send(200, PAGE, "text/html; charset=utf-8")
return
if path == "/api/state":
self._json(200, app.state())
return
if path == "/favicon.ico":
self.send_response(204)
self.end_headers()
return
self._error(404, "Not found")
def do_POST(self):
path = urlparse(self.path).path
try:
data = self._body()
except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
self._error(400, "Need a JSON object")
return
try:
if path == "/api/aim":
app.rig.update(
target=str(data.get("target", "both")),
pan=data["pan"],
tilt=data["tilt"],
dimmer=data.get("dimmer", app.rig.dimmer),
)
self._json(200, {"ok": True})
return
if path == "/api/color":
app.rig.set_color(str(data.get("target", "both")), data.get("color", ""))
self._json(200, app.state())
return
if path == "/api/node":
app.select_node(data.get("ip", ""))
self._json(200, app.state())
return
if path == "/api/nodes":
app.refresh_nodes()
self._json(200, app.state())
return
if path == "/api/positions":
name = clean_name(data.get("name", ""))
live = app.rig.live()
app.store.upsert(name, live["m1"], live["m2"])
self._json(200, app.state(saved=name))
return
if path == "/api/recall":
name = clean_name(data.get("name", ""))
entry = app.store.get(name)
if entry is None:
self._error(404, f"No position named {name}")
return
app.rig.recall(entry)
self._json(200, app.state())
return
if path == "/api/delete":
name = clean_name(data.get("name", ""))
if not app.store.delete(name):
self._error(404, f"No position named {name}")
return
self._json(200, app.state())
return
except KeyError:
self._error(400, "Need pan and tilt")
return
except ValueError as exc:
self._error(400, str(exc))
return
except OSError as exc:
self._error(500, f"Could not write positions: {exc}")
return
self._error(404, "Not found")
return Handler
def parse_args():
root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--host", default="127.0.0.1", help="Web bind address")
parser.add_argument("--port", type=int, default=8765)
parser.add_argument(
"--file",
type=Path,
default=root / "shows" / "mover_positions.json",
help="JSON file for saved positions",
)
parser.add_argument("--ip", default=None, help=f"Art-Net destination (default: poll, else {DEFAULT_NODE})")
parser.add_argument("--universe", type=int, default=0)
parser.add_argument("--address", type=int, default=M1_ADDR, help="M1 DMX start, 1-based")
parser.add_argument("--address2", type=int, default=M2_ADDR, help="M2 DMX start, 1-based")
return parser.parse_args()
def main():
args = parse_args()
store = Store(args.file)
nodes = pin_gateway(discover_artnet_nodes())
if args.ip:
ip = clean_ip(args.ip)
nodes = include_ip(nodes, ip)
else:
ip = nodes[0]["ip"]
universe = args.universe
chosen = next((node for node in nodes if node["ip"] == ip), None)
if chosen and chosen.get("universe", "") != "" and args.universe == 0:
universe = int(chosen["universe"])
name = chosen["name"] if chosen and chosen.get("name") else ""
print(f"Art-Net → {ip} {name} universe {universe}".replace(" ", " ").strip(), flush=True)
for node in nodes:
label = f" {node['ip']}"
if node["name"]:
label += f" {node['name']}"
print(label, flush=True)
print(f"Positions → {args.file}", flush=True)
print("Stop QLC+ Art-Net output first. Ctrl+C blackout.", flush=True)
sender = ArtNetSender(ip, universe=universe)
rig = Rig(
{
"m1": Mover(sender, args.address, "M1"),
"m2": Mover(sender, args.address2, "M2"),
}
)
app = App(rig, store, sender, nodes, args.universe)
httpd = ThreadingHTTPServer((args.host, args.port), make_handler(app))
url_host = "127.0.0.1" if args.host in ("0.0.0.0", "::") else args.host
print(f"Open http://{url_host}:{args.port}", flush=True)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nstopped")
finally:
httpd.server_close()
sender.close()
if __name__ == "__main__":
main()