"""DMX bridges (main/bridge_dmx.c, main/res_dmx.c): universes with Art-Net, sACN and USB-DMX outputs, and fixtures that are led-drivers of their own (fixture-driver/, one led-fixture process each). make desktop build-desktop/led-controller --db /tmp/dmx-db --port 8091 & python3 -m pytest test/api/test_dmx_bridge.py --host localhost:8091 The tests that run a bridge need the controller on this machine (outputs are aimed at sockets and a pty here) and a host build (GET /settings/bridge says supported). """ import os import socket import struct import subprocess import time from urllib.parse import urlparse import pytest from helpers import new_id, unique HZ = 40 def wait_for(fn, timeout=8.0, step=0.1): end = time.time() + timeout while time.time() < end: v = fn() if v: return v time.sleep(step) return fn() @pytest.fixture(scope="module") def local(c, base_url): if urlparse(base_url).hostname not in ("localhost", "127.0.0.1"): pytest.skip("the controller is not on this machine") if not c.get("/settings/bridge").json().get("supported"): pytest.skip("bridges are not supported on this build") @pytest.fixture(scope="module") def can_def(c): """The seeded 8-channel can: Dimmer, Strobe, Red, Green, Blue, White, Macro, Speed""" defs = c.get("/dmx-definitions").json() for did, d in defs.items(): if d["name"] == "beamZ BCC145": return did r = c.post("/dmx-definitions", json={"name": "beamZ BCC145", "channels": ["Dimmer", "Strobe", "Red", "Green", "Blue", "White", "Macro", "Speed"]}) assert r.status_code == 201, r.text return new_id(r) @pytest.fixture def rgb_def(c): r = c.post("/dmx-definitions", json={"name": unique("pytest-rgb"), "channels": ["Red", "Green", "Blue", "Macro"], "defaults": {"Macro": 7}}) assert r.status_code == 201, r.text did = new_id(r) yield did c.delete(f"/dmx-definitions/{did}") @pytest.fixture def running(c, local): """Start a DMX bridge record (its id); afterwards the bridge list is put back and the record deleted.""" before = [b["addr"] for b in c.get("/settings/bridge").json()["bridges"]] made = [] def start(body): r = c.post("/dmx-bridges", json=body) assert r.status_code == 201, r.text bid = new_id(r) made.append(bid) r = c.put("/settings/bridge", json={"bridges": before + [f"dmx:{bid}"]}) assert r.status_code == 200, r.text return c.get(f"/dmx-bridges/{bid}").json() yield start c.put("/settings/bridge", json={"bridges": before}) for bid in made: c.delete(f"/dmx-bridges/{bid}") def udp_socket(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("127.0.0.1", 0)) s.settimeout(0.5) return s def drain(s): s.setblocking(False) try: while True: s.recv(2048) except BlockingIOError: pass s.settimeout(0.5) def bridge_status(c, bid): for b in c.get("/settings/bridge").json()["bridges"]: if b["addr"] == f"dmx:{bid}": return b return None def artnet(pkt): """(universe, 512 channels) of an ArtDmx packet""" assert pkt[:8] == b"Art-Net\0" and pkt[8:10] == b"\x00\x50" uni = pkt[14] | (pkt[15] << 8) n = (pkt[16] << 8) | pkt[17] return uni, pkt[18:18 + n] def sacn(pkt): assert pkt[4:16] == b"ASC-E1.17\0\0\0" uni = struct.unpack(">H", pkt[113:115])[0] assert pkt[125] == 0 # start code return uni, pkt[126:] def play(c, profile, macs, colour): """A zone over a group of these MACs plays a solid colour; returns a cleanup function.""" gid = new_id(c.post("/groups", json={"name": unique("pytest-dmx"), "devices": macs})) zid = new_id(c.post("/zones", json={"name": unique("pytest-dmx"), "group_ids": [gid]})) r = c.post("/presets", json={"name": unique("pytest-dmx"), "brightness": 255, "colors": [colour], "pattern": "on"}) assert r.status_code == 201, r.text pid = new_id(r) assert c.post(f"/zones/{zid}/play", json={"preset_id": pid}).status_code == 200 def done(): c.post(f"/zones/{zid}/stop") c.delete(f"/zones/{zid}") c.delete(f"/groups/{gid}") c.delete(f"/presets/{pid}") return done # --- definitions -------------------------------------------------------------------------------------------------- def test_presets_seeded(c, can_def): d = c.get(f"/dmx-definitions/{can_def}").json() assert d["channels"][:3] == ["Dimmer", "Strobe", "Red"] def test_definition_needs_channels(c): r = c.post("/dmx-definitions", json={"name": unique("pytest"), "channels": []}) assert r.status_code == 400 r = c.post("/dmx-definitions", json={"name": unique("pytest"), "channels": ["Red"], "defaults": {"Red": 300}}) assert r.status_code == 400 def test_definition_in_use_is_kept(c, rgb_def): r = c.post("/dmx-bridges", json={"name": unique("pytest"), "universes": [ {"fixtures": [{"name": "a", "definition": rgb_def, "address": 1}]}]}) assert r.status_code == 201, r.text bid = new_id(r) try: assert c.delete(f"/dmx-definitions/{rgb_def}").status_code == 409 # Growing it past channel 512 for a fixture at 1 is fine; at 510 it is not c.put(f"/dmx-bridges/{bid}", json={"universes": [{"fixtures": [ {"name": "a", "definition": rgb_def, "address": 509}]}]}) assert c.put(f"/dmx-definitions/{rgb_def}", json={"channels": ["Red", "Green", "Blue", "White", "X"]} ).status_code == 400 finally: c.delete(f"/dmx-bridges/{bid}") # --- bridge records ---------------------------------------------------------------------------------------------- @pytest.mark.parametrize("universe, error", [ ({"fixtures": [{"name": "a", "definition": "D", "address": 1}, {"name": "b", "definition": "D", "address": 8}]}, "already used"), ({"fixtures": [{"name": "a", "definition": "D", "address": 506}]}, "pass channel 512"), ({"fixtures": [{"name": "a", "definition": "D", "address": 1, "mac": "ffffffffffff"}]}, "unicast"), ({"fixtures": [{"name": "a", "definition": "D", "address": 1, "mac": "0211"}]}, "12 hex"), ({"fixtures": [{"name": "a", "definition": "nope", "address": 1}]}, "no such DMX definition"), ({"outputs": [{"type": "sacn", "universe": 0}]}, "sACN universe"), ({"outputs": [{"type": "dmx_serial"}]}, "serial_port"), ({"outputs": [{"type": "kinet"}]}, "artnet, sacn, dmx_serial or sim"), ({"outputs": [{"type": "sim", "universe": 40000}]}, "Simulator universe"), ]) def test_bridge_validation(c, can_def, universe, error): for f in universe.get("fixtures", []): f["definition"] = can_def if f["definition"] == "D" else f["definition"] r = c.post("/dmx-bridges", json={"name": unique("pytest"), "universes": [universe]}) assert r.status_code == 400 assert error in r.json()["error"] def test_macs_generated_and_unique(c, can_def): body = {"name": unique("pytest"), "universes": [{"fixtures": [ {"name": "a", "definition": can_def, "address": 1}, {"name": "b", "definition": can_def, "address": 9}]}]} r = c.post("/dmx-bridges", json=body) assert r.status_code == 201, r.text bid = new_id(r) try: fx = r.json()["universes"][0]["fixtures"] macs = [f["mac"] for f in fx] assert len(set(macs)) == 2 and all(len(m) == 12 and int(m[:2], 16) & 3 == 2 for m in macs) # Another bridge cannot take one of them r = c.post("/dmx-bridges", json={"name": unique("pytest"), "universes": [{"fixtures": [ {"name": "c", "definition": can_def, "address": 1, "mac": macs[0]}]}]}) assert r.status_code == 400 and "already used" in r.json()["error"] # An edited MAC is kept, ids stay fx[0]["mac"] = "02:00:00:00:00:42" r = c.put(f"/dmx-bridges/{bid}", json={"universes": [{"fixtures": fx}]}) assert r.status_code == 200, r.text got = r.json()["universes"][0]["fixtures"] assert got[0]["mac"] == "020000000042" and [f["id"] for f in got] == [f["id"] for f in fx] finally: c.delete(f"/dmx-bridges/{bid}") def test_unknown_bridge_id_refused(c, local): r = c.put("/settings/bridge", json={"bridges": ["dmx:does-not-exist"]}) assert r.status_code == 400 # --- running bridges --------------------------------------------------------------------------------------------- def test_fixtures_are_drivers(c, can_def, running): s = udp_socket() rec = running({"name": unique("pytest"), "universes": [{"number": 3, "outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}, {"name": unique("can"), "definition": can_def, "address": 9}]}]}) bid = rec["id"] macs = [f["mac"] for f in rec["universes"][0]["fixtures"]] devs = wait_for(lambda: (lambda d: d if all(m in d for m in macs) else None)(c.get("/devices").json())) assert devs, "the fixtures did not register" for m in macs: assert devs[m]["dmx_fixture"] is True and devs[m]["bridge"] == f"dmx:{bid}" st = wait_for(lambda: (lambda b: b if b and b["status"]["linked"] else None)(bridge_status(c, bid))) assert st["kind"] == "dmx" and st["status"]["running"] == 2 and st["status"]["hz"] == HZ # 40 frames a second, to universe 3 drain(s) t0, n = time.time(), 0 while time.time() - t0 < 2.0: try: uni, data = artnet(s.recv(2048)) assert uni == 3 and len(data) == 512 n += 1 except socket.timeout: pass assert abs(n / 2.0 - HZ) <= 3, f"{n / 2.0} frames a second" def test_preset_colour_reaches_channels(c, profile, can_def, rgb_def, running): s = udp_socket() rec = running({"name": unique("pytest"), "universes": [{"number": 0, "outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}, {"name": unique("rgb"), "definition": rgb_def, "address": 101}]}]}) can, rgb = rec["universes"][0]["fixtures"] assert wait_for(lambda: all(f["mac"] in c.get("/devices").json() for f in (can, rgb))) done = play(c, profile, [can["mac"], rgb["mac"]], "#ff0000") try: def red(): drain(s) _, d = artnet(s.recv(2048)) return d if d[2] == 255 and d[100] == 255 else None d = wait_for(red) assert d, "the fixtures did not turn red" # Can at 1: Dimmer 255, Strobe 0 (open), Red 255, Green, Blue, White 0, Macro, Speed 0 assert list(d[0:8]) == [255, 0, 255, 0, 0, 0, 0, 0] # RGB at 101: red, then the Macro default assert list(d[100:104]) == [255, 0, 0, 7] # Nothing else is lit assert not any(d[8:100]) and not any(d[104:]) finally: done() def test_white_takes_the_common_part(c, profile, can_def, running): s = udp_socket() rec = running({"name": unique("pytest"), "universes": [{"outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) mac = rec["universes"][0]["fixtures"][0]["mac"] assert wait_for(lambda: mac in c.get("/devices").json()) done = play(c, profile, [mac], "#ffff80") try: def lit(): drain(s) _, d = artnet(s.recv(2048)) return d if d[5] else None d = wait_for(lit) assert d and list(d[2:6]) == [255 - d[5], 255 - d[5], 0, d[5]] finally: done() def test_dimmer_channel_carries_the_brightness(c, profile, can_def, running): """The can's Dimmer is the fixture's brightness (half here), and its colour is not scaled a second time.""" s = udp_socket() rec = running({"name": unique("pytest"), "universes": [{"outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) mac = rec["universes"][0]["fixtures"][0]["mac"] assert wait_for(lambda: mac in c.get("/devices").json()) assert c.put(f"/devices/{mac}", json={"output_brightness": 128}).status_code == 200 assert c.post(f"/devices/{mac}/brightness", json={}).status_code == 200 done = play(c, profile, [mac], "#ff0000") try: def dimmed(): drain(s) _, d = artnet(s.recv(2048)) return d if d[0] == 128 and d[2] == 255 else None d = wait_for(dimmed) assert d, "the Dimmer channel did not follow the fixture brightness" finally: done() def test_sim_output_reaches_the_rig(c, profile, can_def, running): """A Simulator output hands the universe to the rig page's receiver inside the controller: no UDP.""" if c.get("/sim/api/dmx").status_code != 200: pytest.skip("no simulated rig here") uni = 4321 # no Art-Net sender on this machine uses it def channels(): a = c.get("/sim/api/dmx?data=1").json().get("artnet", {}) u = a.get("universes", {}).get(str(uni)) return a.get("local_packets", 0), bytes.fromhex(u["data"]) if u and "data" in u else b"" before, _ = channels() rec = running({"name": unique("pytest"), "universes": [{"number": uni, "outputs": [{"type": "sim"}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 21}]}]}) out = rec["universes"][0]["outputs"][0] assert out["type"] == "sim" and out["host"] == "" and out["port"] is None mac = rec["universes"][0]["fixtures"][0]["mac"] assert wait_for(lambda: mac in c.get("/devices").json()) done = play(c, profile, [mac], "#ff0000") try: def red(): n, d = channels() return (n, d) if len(d) == 512 and d[20] == 255 and d[22] == 255 else None got = wait_for(red) assert got, f"the rig did not get the red can: {channels()[1][16:32].hex()} {c.get('/devices').json().get(mac)}" n, d = got assert n > before assert list(d[20:28]) == [255, 0, 255, 0, 0, 0, 0, 0] and not any(d[:20]) and not any(d[28:]) finally: done() def test_sacn_unicast(c, can_def, running): s = udp_socket() running({"name": unique("pytest"), "universes": [{"number": 7, "outputs": [ {"type": "sacn", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) def first(): try: return sacn(s.recv(2048)) except socket.timeout: return None got = wait_for(first) assert got, "no sACN packet" uni, data = got assert uni == 7 and len(data) == 512 def test_output_universe_override(c, can_def, running): s = udp_socket() running({"name": unique("pytest"), "universes": [{"number": 2, "outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1], "universe": 300}], "fixtures": []}]}) def first(): try: return artnet(s.recv(2048)) except socket.timeout: return None got = wait_for(first) assert got and got[0] == 300 def test_enttec_pro_on_a_pty(c, can_def, running): master, slave = os.openpty() path = os.ttyname(slave) os.set_blocking(master, False) running({"name": unique("pytest"), "universes": [{"outputs": [ {"type": "dmx_serial", "serial_port": path, "dmx_mode": "enttec_pro"}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) # Frames before the fixture's driver is up have it dark: wait for one with its dimmer at 255 buf, frame = b"", None end = time.time() + 8 while time.time() < end and frame is None: try: buf += os.read(master, 65536) except BlockingIOError: time.sleep(0.05) i = buf.rfind(b"\x7e\x06\x01\x02", 0, max(0, len(buf) - 517)) # label 6, 513 bytes if i >= 0: f = buf[i:i + 518] assert f[4] == 0 and f[-1] == 0xE7 frame = f if f[5] == 255 else None buf = buf[i + 518:] os.close(master) os.close(slave) assert frame, "no Enttec frame with the can's dimmer up" def test_fixture_restarts_after_it_stops(c, can_def, running): s = udp_socket() rec = running({"name": unique("pytest"), "universes": [{"outputs": [ {"type": "artnet", "host": "127.0.0.1", "port": s.getsockname()[1]}], "fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) bid, mac = rec["id"], rec["universes"][0]["fixtures"][0]["mac"] assert wait_for(lambda: mac in c.get("/devices").json()), "the fixture did not register" pids = wait_for(lambda: subprocess.run(["pgrep", "-f", f"led-fixture {mac}"], capture_output=True, text=True ).stdout.split()) assert pids, "no led-fixture process" subprocess.run(["kill", "-9", *pids]) assert wait_for(lambda: not bridge_status(c, bid)["status"]["linked"], timeout=3) st = wait_for(lambda: (lambda b: b if b["status"]["linked"] else None)(bridge_status(c, bid)), timeout=15) assert st, "the fixture did not come back" new = subprocess.run(["pgrep", "-f", f"led-fixture {mac}"], capture_output=True, text=True).stdout.split() assert new and new != pids assert mac in c.get("/devices").json() def test_deleting_a_running_bridge_stops_it(c, can_def, running): rec = running({"name": unique("pytest"), "universes": [{"fixtures": [ {"name": unique("can"), "definition": can_def, "address": 1}]}]}) bid, mac = rec["id"], rec["universes"][0]["fixtures"][0]["mac"] assert wait_for(lambda: bridge_status(c, bid)) assert c.delete(f"/dmx-bridges/{bid}").status_code == 200 assert bridge_status(c, bid) is None assert f"dmx:{bid}" not in c.get("/settings").json().get("bridges", []) assert wait_for(lambda: not subprocess.run(["pgrep", "-f", f"led-fixture {mac}"], capture_output=True ).stdout.strip(), timeout=5)