From 1a4e51e449e2c836f3d31adb3094a954581d4f03 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Wed, 21 Oct 2026 15:53:22 +1300 Subject: [PATCH] Aim the cabaret movers from a page and keep the named positions. Co-authored-by: Cursor --- scripts/position_movers.py | 997 +++++++++++++++++++++++++++++++++++++ shows/mover_positions.json | 44 ++ 2 files changed, 1041 insertions(+) create mode 100644 scripts/position_movers.py create mode 100644 shows/mover_positions.json diff --git a/scripts/position_movers.py b/scripts/position_movers.py new file mode 100644 index 0000000..a6ceb48 --- /dev/null +++ b/scripts/position_movers.py @@ -0,0 +1,997 @@ +#!/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 = """ + + + + +Mover positions + + + +
+

Mover positions

+

Connecting…

+
Art-Net to DMX
+
+ + +
+

Both movers share this DMX output.

+
+ + + +
+ +
Color
+
+
+
Pan + +
+ +
+
+
Tilt + +
+ +
+
+
Dimmer + +
+ +
+
+ + +
+

+

Saved

+

Aim the beam, name it, then add the position.

+
    +

    Arrow keys nudge pan and tilt. Shift moves by 10. Up sends the beam toward tilt 0.

    +
    + + + +""" + + +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() diff --git a/shows/mover_positions.json b/shows/mover_positions.json new file mode 100644 index 0000000..42ee4f8 --- /dev/null +++ b/shows/mover_positions.json @@ -0,0 +1,44 @@ +{ + "positions": { + "Down": { + "m1": { + "pan": 133, + "tilt": 113 + }, + "m2": { + "pan": 133, + "tilt": 113 + } + }, + "Back Middle": { + "m1": { + "pan": 85, + "tilt": 221 + }, + "m2": { + "pan": 85, + "tilt": 221 + } + }, + "Back Thirds": { + "m1": { + "pan": 94, + "tilt": 221 + }, + "m2": { + "pan": 94, + "tilt": 221 + } + }, + "Back Out": { + "m1": { + "pan": 101, + "tilt": 221 + }, + "m2": { + "pan": 101, + "tilt": 221 + } + } + } +}