Merge dev into main: the pad controller, simulator, Chataigne export and test show.
Keep main's Temple of Techno show over dev's older copy from the first venue workspaces commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
72c227b153
106 files changed
+33054
-420
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# test_small_eye.py is a hands-on Art-Net tester for the real Small Eye
|
||||
# (scripts/shows/figure8_small_eye.py imports from it), not a test module.
|
||||
collect_ignore = ["test_small_eye.py"]
|
||||
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
"""Chataigne export: channel mapping and the project file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts" / "shows"))
|
||||
|
||||
import make_chataigne # noqa: E402
|
||||
|
||||
|
||||
class ChataigneExportTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.show = json.loads((ROOT / "shows" / "test.show.json").read_text())
|
||||
self.stage = json.loads((ROOT / self.show["stage"]).read_text())
|
||||
|
||||
def test_channels_are_one_based_dmx(self) -> None:
|
||||
levels = make_chataigne.absolute_levels(self.show, self.stage, {"#1": {"0": 255, "2": 10}, "M1": {"8": 7}})
|
||||
self.assertEqual(levels, {88: 255, 90: 10, 9: 7})
|
||||
|
||||
def test_groups_hold_pads_and_sliders(self) -> None:
|
||||
groups = make_chataigne.collect(self.show, self.stage)
|
||||
self.assertEqual(list(groups), ["Colour 1", "Colour 2"])
|
||||
cans = groups["Colour 1"]
|
||||
self.assertEqual([p["note"] for p in cans["pads"]][:2], [52, 53])
|
||||
self.assertEqual([s["cc"] for s in cans["sliders"]], [30, 31, 32, 33, 34])
|
||||
self.assertEqual(cans["pads"][0]["fade"], [1000, 1000])
|
||||
|
||||
def test_writes_project_and_script(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
subprocess.run(
|
||||
[sys.executable, str(ROOT / "scripts" / "shows" / "make_chataigne.py"), str(ROOT / "shows" / "test.show.json"), tmp],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
project = json.loads((Path(tmp) / "test.noisette").read_text())
|
||||
script = (Path(tmp) / "test.js").read_text()
|
||||
settings = project["projectSettings"]["containers"]["dashboardSettings"]["parameters"]
|
||||
self.assertIn({"value": True, "controlAddress": "/enableDashboardServer"}, settings)
|
||||
board = project["dashboardManager"]["items"][0]["itemManager"]["items"]
|
||||
targets = [item["controllable"] for item in board]
|
||||
self.assertEqual(len(board), 32 * 2 + 10 + 2)
|
||||
self.assertEqual(len(set(targets)), len(targets))
|
||||
for item in board:
|
||||
self.assertIn(item["controllable"].rsplit("/", 1)[1].removesuffix("Lamp"), script)
|
||||
canvas = project["dashboardManager"]["items"][0]["itemManager"]["parameters"][0]
|
||||
self.assertEqual((canvas["value"], canvas["enabled"]), ([1574.0, 953.0], True))
|
||||
names = [m["niceName"] for m in project["modules"]["items"]]
|
||||
self.assertEqual(names, ["Lights", "Preview", "Pad"])
|
||||
self.assertEqual(project["modules"]["items"][1]["device"]["containers"]["output"]["parameters"][0]["value"], "127.0.0.1")
|
||||
self.assertIn("var GROUPS", script)
|
||||
self.assertNotIn("__DATA__", script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""End to end: virtual pad -> padcontroller -> QLC+ (test show) -> Art-Net -> simulator.
|
||||
|
||||
Needs the rig up (CLAUDE.md): the padcontroller and simulator services, and
|
||||
QLC+ running with shows/test.qxw open. It drives the live simulator, so it only
|
||||
runs when asked:
|
||||
|
||||
PAD_E2E=1 .venv/bin/python -m unittest tests.test_e2e_pad -v
|
||||
|
||||
The helper tests at the bottom run offline every time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from urllib.error import URLError
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from padcontroller.virtualpad import PAD_CHANNEL, VirtualPad, check_test_show, last_workspace, pad_note # noqa: E402
|
||||
|
||||
SIMULATOR = "http://127.0.0.1:8765/api/state"
|
||||
SHOW = ROOT / "shows" / "test.show.json"
|
||||
# Colour 1 (cans) is on notes 52-67; Play shifts them to 68-83, Colour 2 (movers).
|
||||
RED, GREEN, BLUE, MAGENTA = 52, 57, 61, 63
|
||||
RGB = {RED: (255, 0, 0), GREEN: (0, 255, 0), BLUE: (0, 0, 255), MAGENTA: (255, 0, 255)}
|
||||
FADE_TIMEOUT = 4.0 # the colour scenes fade in over 1 s
|
||||
|
||||
|
||||
def state() -> dict:
|
||||
with urlopen(SIMULATOR, timeout=2) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def scene_fixtures(key: str) -> list[str]:
|
||||
"""The fixtures a scene in the test show sets, e.g. colour_1_1 -> ['#1', ..., '#15']."""
|
||||
spec = json.loads(SHOW.read_text())
|
||||
return sorted(next(f for f in spec["functions"] if f["key"] == key)["values"])
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("PAD_E2E") == "1", "set PAD_E2E=1 to drive the live rig")
|
||||
class PadToSimulator(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
check_test_show()
|
||||
try:
|
||||
s = state()
|
||||
except URLError as e:
|
||||
raise AssertionError(f"Simulator not answering on {SIMULATOR}: {e}") from e
|
||||
assert s["age"] < 1.0, f"Simulator has had no Art-Net for {s['age']:.1f} s; is QLC+ running?"
|
||||
cls.pad = VirtualPad()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.pad.close()
|
||||
|
||||
def wait_for(self, fixtures: list[str], rgb: tuple[int, int, int]) -> None:
|
||||
"""Poll the simulator until every fixture shows rgb, or fail with what it shows."""
|
||||
deadline = time.monotonic() + FADE_TIMEOUT
|
||||
while True:
|
||||
got = {k: (v["r"], v["g"], v["b"]) for k, v in state()["fixtures"].items() if k in fixtures}
|
||||
wrong = {k: v for k, v in got.items() if v != rgb}
|
||||
if not wrong and len(got) == len(fixtures):
|
||||
return
|
||||
if time.monotonic() > deadline:
|
||||
missing = sorted(set(fixtures) - set(got))
|
||||
self.fail(f"wanted {rgb} on {fixtures}; wrong: {wrong}; missing: {missing}")
|
||||
time.sleep(0.1)
|
||||
|
||||
def press(self, note: int, play: bool = False) -> None:
|
||||
if play:
|
||||
with self.pad.play():
|
||||
self.pad.press(note, PAD_CHANNEL)
|
||||
else:
|
||||
self.pad.press(note, PAD_CHANNEL)
|
||||
|
||||
# Each test presses two different buttons in the solo frame. A tap on the
|
||||
# button that's already on would turn it off, but the second press is always
|
||||
# a different button, so it always turns on and sets the colour.
|
||||
|
||||
def test_bank2_pads_set_can_colour(self) -> None:
|
||||
cans = scene_fixtures("colour_1_1")
|
||||
self.assertTrue(cans and all(k.startswith("#") for k in cans))
|
||||
self.press(RED)
|
||||
self.press(BLUE)
|
||||
self.wait_for(cans, RGB[BLUE])
|
||||
self.press(GREEN)
|
||||
self.wait_for(cans, RGB[GREEN])
|
||||
|
||||
def test_play_layer_sets_mover_colour(self) -> None:
|
||||
movers = scene_fixtures("colour_2_1")
|
||||
self.assertTrue(movers and all(k.startswith("M") for k in movers))
|
||||
self.press(BLUE, play=True)
|
||||
self.press(MAGENTA, play=True)
|
||||
self.wait_for(movers, RGB[MAGENTA])
|
||||
self.press(BLUE, play=True)
|
||||
self.wait_for(movers, RGB[BLUE])
|
||||
|
||||
|
||||
class Helpers(unittest.TestCase):
|
||||
def test_last_workspace_reads_recent0(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
conf = Path(d) / "qlc.conf"
|
||||
conf.write_text("[workspace]\nrecent0=/x/shows/test.qxw\nrecent1=shows/other.qxw\n")
|
||||
self.assertEqual(last_workspace(conf), Path("/x/shows/test.qxw"))
|
||||
self.assertIsNone(last_workspace(Path(d) / "missing.conf"))
|
||||
|
||||
def test_check_test_show_refuses_other_shows(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
conf = Path(d) / "qlc.conf"
|
||||
conf.write_text(f"[workspace]\nrecent0={ROOT / 'shows' / 'cabaret.qxw'}\n")
|
||||
with self.assertRaises(SystemExit):
|
||||
check_test_show(conf)
|
||||
conf.write_text(f"[workspace]\nrecent0={ROOT / 'shows' / 'test.qxw'}\n")
|
||||
check_test_show(conf)
|
||||
|
||||
def test_pad_note_from_midi_map(self) -> None:
|
||||
self.assertEqual(pad_note(1), (9, 36))
|
||||
with self.assertRaises(SystemExit):
|
||||
pad_note(999)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Scene colours become preset RGB writes, and the codec matches a known message."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("pad_colours", ROOT / "scripts" / "pad" / "pad_colours.py")
|
||||
colours = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
sys.modules["pad_colours"] = colours
|
||||
spec.loader.exec_module(colours)
|
||||
|
||||
|
||||
def test_codec_matches_the_published_write():
|
||||
inner = bytes.fromhex("00592209000005000000800100000178")
|
||||
wire = bytes([0xF0, *colours.encode(inner), 0xF7])
|
||||
assert wire == bytes.fromhex("f000320949000040020000000018000000017001f7")
|
||||
assert colours.decode(wire[1:-1]) == inner
|
||||
|
||||
|
||||
def test_scene_colours_are_stored_on_the_note_36_pads():
|
||||
writes = colours.colour_writes()
|
||||
first = writes[:16]
|
||||
assert [name for name, _addr, _rgb in first] == [
|
||||
"Red",
|
||||
"Green",
|
||||
"Blue",
|
||||
"White",
|
||||
"Yellow",
|
||||
"Cyan",
|
||||
"Magenta",
|
||||
"Orange",
|
||||
"Warm",
|
||||
"Cool",
|
||||
"Pink",
|
||||
"Lime",
|
||||
"Full",
|
||||
"Half",
|
||||
"Dim50",
|
||||
"Black",
|
||||
]
|
||||
assert first[0][1:] == (1048, bytes.fromhex("f00000"))
|
||||
assert first[1][1:] == (1074, bytes.fromhex("00f000"))
|
||||
assert first[2][1:] == (1100, bytes.fromhex("0000f0"))
|
||||
assert first[3][1:] == (1126, bytes.fromhex("f0f0f0"))
|
||||
assert first[15][1:] == (1048 + 15 * 26, b"\x00\x00\x00")
|
||||
assert len(writes) == 16 * len(colours.BANKS)
|
||||
assert {address for _name, address, _rgb in writes if _name == "Red"} == {
|
||||
bank + 4 for bank in colours.BANKS
|
||||
}
|
||||
|
||||
|
||||
def test_xchc_colours_are_stored_on_page_7_for_pad_bank_2():
|
||||
writes = colours.colour_writes(bank=2, colours=colours.xchc_colours())
|
||||
first = [item for item in writes if item[1] < colours.BANKS[1]]
|
||||
assert [name for name, _addr, _rgb in first] == [
|
||||
"Red",
|
||||
"Orange",
|
||||
"Yellow",
|
||||
"Green",
|
||||
"Cyan",
|
||||
"Blue",
|
||||
"Violet",
|
||||
"Magenta",
|
||||
"White",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
]
|
||||
assert first[0][1:] == (3128, bytes.fromhex("f00000"))
|
||||
assert first[1][1:] == (3154, bytes.fromhex("f07800"))
|
||||
assert first[6][1:] == (3128 + 6 * 26, bytes.fromhex("7800f0"))
|
||||
assert first[8][1:] == (3128 + 8 * 26, bytes.fromhex("f0f0f0"))
|
||||
assert first[9][1:] == (3128 + 9 * 26, b"\x00\x00\x00")
|
||||
assert {address for name, address, _rgb in writes if name == "Red"} == {
|
||||
base + 5 * 16 * 26 + 4 for base in colours.BANKS
|
||||
}
|
||||
|
||||
|
||||
def test_save_is_the_empty_write_midi_suite_sends():
|
||||
inner = colours.decode(bytes(colours.save_request()[1:-1]))
|
||||
assert inner[:3] == b"\x00\x59\x22"
|
||||
length = int.from_bytes(inner[3:6], "little")
|
||||
assert inner[6:6 + length] == bytes([5, 0, 0, 0, 0, 0, 0, 0])
|
||||
assert len(colours.save_request()) == 20
|
||||
|
||||
|
||||
def test_private_port_is_not_the_master_or_qlc():
|
||||
names = [
|
||||
"SINCO:SINCO SMC-PAD-Master 20:1",
|
||||
"SINCO:SINCO SMC-PAD-Private 20:0",
|
||||
"qlcplus:__QLC__ 128:0",
|
||||
]
|
||||
assert colours.private_port(names) == "SINCO:SINCO SMC-PAD-Private 20:0"
|
||||
|
||||
|
||||
def test_identify_lights_each_page_in_its_own_colour():
|
||||
factory = (ROOT / "tests" / "data" / "smc_pad_factory.bin").read_bytes()
|
||||
image = colours.identify_image(factory)
|
||||
preset = colours.preset
|
||||
assert len(image) == len(factory)
|
||||
for number in range(preset.PRESET_COUNT):
|
||||
for index in range(preset.PAD_COUNT):
|
||||
at = preset.colour_offset(number, index)
|
||||
_name, red, green, blue = colours.PAGE_COLOURS[index // preset.PAGE_LEN]
|
||||
assert image[at:at + 3] == bytes(map(colours.scale, (red, green, blue)))
|
||||
changed = {at for at in range(len(image)) if image[at] != factory[at]}
|
||||
lamps = {
|
||||
preset.colour_offset(number, index) + step
|
||||
for number in range(preset.PRESET_COUNT)
|
||||
for index in range(preset.PAD_COUNT)
|
||||
for step in range(3)
|
||||
}
|
||||
assert changed <= lamps
|
||||
@@ -0,0 +1,89 @@
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from padcontroller.layer import PlayLayer # noqa: E402
|
||||
|
||||
PLAY_DOWN = [0xB0, 27, 127]
|
||||
PLAY_UP = [0xB0, 27, 0]
|
||||
|
||||
|
||||
class PlayLayerTest(unittest.TestCase):
|
||||
def test_notes_pass_through_when_play_is_up(self):
|
||||
layer = PlayLayer()
|
||||
self.assertEqual(layer.handle([0x99, 52, 100]), [[0x99, 52, 100]])
|
||||
|
||||
def test_play_is_not_passed_on(self):
|
||||
layer = PlayLayer()
|
||||
self.assertEqual(layer.handle(PLAY_DOWN), [])
|
||||
self.assertEqual(layer.handle(PLAY_UP), [])
|
||||
|
||||
def test_bank_2_moves_up_while_play_is_held(self):
|
||||
layer = PlayLayer()
|
||||
layer.handle(PLAY_DOWN)
|
||||
self.assertEqual(layer.handle([0x99, 52, 100]), [[0x99, 68, 100]])
|
||||
self.assertEqual(layer.handle([0x99, 67, 100]), [[0x99, 83, 100]])
|
||||
layer.handle(PLAY_UP)
|
||||
self.assertEqual(layer.handle([0x99, 52, 100]), [[0x99, 52, 100]])
|
||||
|
||||
def test_other_notes_and_ccs_are_left_alone(self):
|
||||
layer = PlayLayer()
|
||||
layer.handle(PLAY_DOWN)
|
||||
self.assertEqual(layer.handle([0x99, 40, 100]), [[0x99, 40, 100]])
|
||||
self.assertEqual(layer.handle([0xB0, 30, 64]), [[0xB0, 30, 64]])
|
||||
|
||||
def test_release_matches_its_press(self):
|
||||
layer = PlayLayer()
|
||||
layer.handle(PLAY_DOWN)
|
||||
layer.handle([0x99, 55, 100])
|
||||
layer.handle(PLAY_UP)
|
||||
self.assertEqual(layer.handle([0x89, 55, 0]), [[0x89, 71, 0]])
|
||||
layer.handle([0x99, 55, 100])
|
||||
layer.handle(PLAY_DOWN)
|
||||
self.assertEqual(layer.handle([0x99, 55, 0]), [[0x99, 55, 0]])
|
||||
|
||||
def test_sound_pad_puts_the_submaster_back_to_full(self):
|
||||
layer = PlayLayer()
|
||||
self.assertEqual(layer.handle([0x99, 36, 100]), [[0x99, 36, 100], [0xB0, 100, 127]])
|
||||
self.assertEqual(layer.handle([0x89, 36, 0]), [[0x89, 36, 0], [0xB0, 100, 127]])
|
||||
self.assertEqual(layer.handle([0x99, 37, 100]), [[0x99, 37, 100]])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class LockedKnobsTest(unittest.TestCase):
|
||||
def test_knobs_are_dropped_until_custom_is_pressed(self):
|
||||
layer = PlayLayer(lock_knobs=True)
|
||||
self.assertEqual(layer.handle([0xB0, 31, 64]), [])
|
||||
layer.handle([0x99, 67, 100])
|
||||
self.assertEqual(layer.handle([0xB0, 31, 64]), [[0xB0, 31, 64]])
|
||||
self.assertEqual(layer.handle([0xB0, 36, 64]), [])
|
||||
|
||||
def test_another_pad_locks_them_again(self):
|
||||
layer = PlayLayer(lock_knobs=True)
|
||||
layer.handle([0x99, 67, 100])
|
||||
layer.handle([0x99, 60, 100])
|
||||
self.assertEqual(layer.handle([0xB0, 31, 64]), [])
|
||||
|
||||
def test_locking_sends_the_sliders_back_to_zero(self):
|
||||
layer = PlayLayer(lock_knobs=True)
|
||||
layer.handle([0x99, 67, 100])
|
||||
sent = layer.handle([0x99, 60, 100])
|
||||
self.assertEqual(sent[0], [0x99, 60, 100])
|
||||
self.assertEqual(sent[1:], [[0xB0, 30 + n, 0] for n in range(5)])
|
||||
self.assertEqual(layer.handle([0x99, 61, 100]), [[0x99, 61, 100]])
|
||||
|
||||
def test_play_layer_unlocks_the_second_set(self):
|
||||
layer = PlayLayer(lock_knobs=True)
|
||||
layer.handle(PLAY_DOWN)
|
||||
layer.handle([0x99, 67, 100])
|
||||
self.assertEqual(layer.handle([0xB0, 36, 64]), [[0xB0, 36, 64]])
|
||||
self.assertEqual(layer.handle([0xB0, 31, 64]), [])
|
||||
|
||||
def test_other_knobs_and_unlocked_mode_are_untouched(self):
|
||||
self.assertEqual(PlayLayer(lock_knobs=True).handle([0xB0, 40, 64]), [[0xB0, 40, 64]])
|
||||
self.assertEqual(PlayLayer().handle([0xB0, 31, 64]), [[0xB0, 31, 64]])
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Preset image round-trip: factory knob and note-36 pad stay put."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from padcontroller.preset import ( # noqa: E402
|
||||
GAP_AT,
|
||||
IMAGE_LEN,
|
||||
KNOB_AT,
|
||||
PAD_AT,
|
||||
PAD_LEN,
|
||||
PRESET_LEN,
|
||||
changed_ranges,
|
||||
pack,
|
||||
scale,
|
||||
unpack,
|
||||
)
|
||||
from padcontroller.sysex import decode, encode # noqa: E402
|
||||
|
||||
FACTORY_KNOB = bytes.fromhex("0002001e007f")
|
||||
|
||||
|
||||
def _image() -> bytearray:
|
||||
raw = bytearray(IMAGE_LEN)
|
||||
raw[KNOB_AT:KNOB_AT + len(FACTORY_KNOB)] = FACTORY_KNOB
|
||||
raw[GAP_AT] = 0x5A
|
||||
# Note 36 is pad record 32: channel 10, note, min and max velocity,
|
||||
# RGB, then Led, as MidiSuite shows PAD1.
|
||||
pad = PAD_AT + 32 * PAD_LEN
|
||||
assert pad == 1044
|
||||
raw[pad:pad + 8] = bytes((0x09, 36, 0, 0x7F, 0xF0, 0x00, 0x00, 0xFF))
|
||||
raw[pad + 8] = 0xAB
|
||||
# Last pad of preset 0 is one byte short of a full record.
|
||||
last = PAD_AT + 127 * PAD_LEN
|
||||
raw[last] = 0x09
|
||||
raw[last + 1] = 67
|
||||
raw[PRESET_LEN - 1] = 0x11
|
||||
# A button with a sysex payload and a flag, matching the factory shape.
|
||||
raw[0:23] = bytes.fromhex("020019007f06f07f7f0601f700000000000000000000ff")
|
||||
return raw
|
||||
|
||||
|
||||
def test_codec_vector_lives_with_the_editor():
|
||||
inner = bytes.fromhex("00592209000005000000800100000178")
|
||||
wire = bytes([0xF0, *encode(inner), 0xF7])
|
||||
assert wire == bytes.fromhex("f000320949000040020000000018000000017001f7")
|
||||
assert decode(wire[1:-1]) == inner
|
||||
|
||||
|
||||
def test_factory_knob_and_note_36_pad():
|
||||
raw = bytes(_image())
|
||||
assert raw[KNOB_AT:KNOB_AT + 6] == FACTORY_KNOB
|
||||
assert raw[1044:1046] == bytes((0x09, 36))
|
||||
assert raw[1048:1051] == bytes.fromhex("f00000")
|
||||
|
||||
doc = unpack(raw)
|
||||
knob = doc["presets"][0]["knobs"][0]
|
||||
assert knob == {"type": 0, "speed": 2, "channel": 1, "number": 30, "left": 0, "right": 127}
|
||||
pad = doc["presets"][0]["pads"][32]
|
||||
assert pad["note"] == 36
|
||||
assert pad["channel"] == 10
|
||||
assert (pad["min"], pad["max"]) == (0, 127)
|
||||
assert pad["rgb"] == [0xF0, 0x00, 0x00]
|
||||
assert pad["led"] == 0xFF
|
||||
assert doc["presets"][0]["gap"] == 0x5A
|
||||
assert doc["presets"][0]["buttons"][0]["name"] == "Left"
|
||||
assert doc["presets"][0]["buttons"][0]["sysex"] == "f07f7f0601f7"
|
||||
assert pack(doc) == raw
|
||||
|
||||
|
||||
def test_an_edit_dirties_only_that_byte():
|
||||
raw = bytes(_image())
|
||||
doc = unpack(raw)
|
||||
doc["presets"][0]["knobs"][0]["number"] = 31
|
||||
edited = pack(doc)
|
||||
assert changed_ranges(raw, edited) == [(KNOB_AT + 3, b"\x1f")]
|
||||
assert edited[GAP_AT] == 0x5A
|
||||
assert edited[1048:1051] == raw[1048:1051]
|
||||
at = KNOB_AT + 3
|
||||
assert edited[:at] + edited[at + 1:] == raw[:at] + raw[at + 1:]
|
||||
|
||||
|
||||
def test_a_colour_is_one_write_like_midisuite(monkeypatch):
|
||||
from padcontroller import device
|
||||
from padcontroller.preset import colour_offset
|
||||
|
||||
# MidiSuite set preset 5 record 21 green with one write to 0x3a46.
|
||||
assert colour_offset(4, 21) == 0x3A46
|
||||
writes = []
|
||||
|
||||
class FakeLink:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(device, "Link", FakeLink)
|
||||
monkeypatch.setattr(device, "_write_checked", lambda link, address, data: writes.append((address, data)))
|
||||
device.write_colour(4, 21, [0, 0xFF, 0])
|
||||
assert writes == [(0x3A46, b"\x00\xff\x00")]
|
||||
|
||||
|
||||
def test_global_block_matches_midisuite():
|
||||
from padcontroller.preset import pack_global, unpack_global
|
||||
|
||||
factory = bytes.fromhex("780032040000020001010000")
|
||||
block = unpack_global(factory)
|
||||
assert (block["tempo"], block["swing"], block["curve"], block["transpose"]) == (120, 50, 2, 0)
|
||||
assert pack_global(block) == factory
|
||||
assert unpack_global(bytes.fromhex("77003204000001f601010400"))["transpose"] == -10
|
||||
block["transpose"] = -10
|
||||
block["tempo"] = 119
|
||||
assert pack_global(block) == bytes.fromhex("770032040000 02f6 01010000".replace(" ", ""))
|
||||
|
||||
|
||||
def test_colour_scale_matches_the_pad_lamps():
|
||||
assert scale(0) == 0
|
||||
assert scale(255) == 0xF0
|
||||
assert scale(127) == 0x78
|
||||
|
||||
|
||||
def test_a_step_is_relative_and_a_ramp_is_absolute():
|
||||
from padcontroller.device import _classify
|
||||
|
||||
assert _classify([]) == "silent"
|
||||
assert _classify([(0, 45, 1), (0, 45, 127)]) == "relative"
|
||||
assert _classify([(0, 45, value) for value in range(10, 20)]) == "absolute"
|
||||
|
||||
|
||||
def test_export_packs_the_image_without_opening_midi():
|
||||
from padcontroller.server import ApiError, Editor
|
||||
|
||||
raw = bytes(_image())
|
||||
assert Editor().exported(unpack(raw)) == raw
|
||||
try:
|
||||
Editor().save({"presets": []})
|
||||
except ApiError as exc:
|
||||
assert "8" in str(exc)
|
||||
else:
|
||||
raise AssertionError("a short preset list should be refused before any MIDI")
|
||||
|
||||
|
||||
def test_last_pad_keeps_its_short_tail():
|
||||
raw = bytes(_image())
|
||||
doc = unpack(raw)
|
||||
tail = doc["presets"][0]["pads"][127]["tail"]
|
||||
assert len(bytes.fromhex(tail)) == 17
|
||||
assert pack(doc)[PRESET_LEN - 1] == 0x11
|
||||
|
||||
|
||||
def test_factory_image_reads_as_midisuite_shows_it():
|
||||
# Captured from MidiSuite's Reset with scripts/pad/decode_usbmon.py.
|
||||
raw = (ROOT / "tests" / "data" / "smc_pad_factory.bin").read_bytes()
|
||||
doc = unpack(raw)
|
||||
assert pack(doc) == raw
|
||||
first = doc["presets"][0]
|
||||
# PAD4, bottom right of the PAD1–PAD16 grid: Note 39, Channel 10, 0–127, Led 255.
|
||||
pad4 = first["pads"][2 * 16 + 3]
|
||||
assert (pad4["note"], pad4["channel"], pad4["min"], pad4["max"], pad4["led"]) == (39, 10, 0, 127, 255)
|
||||
# The [<] button: CC Push, Channel 1, CC 25, 0–127, Led 255.
|
||||
left = first["buttons"][0]
|
||||
assert (left["type"], left["channel"], left["number"], left["min"], left["max"], left["led"]) == (2, 1, 25, 0, 127, 255)
|
||||
# Knob 6: CC, Channel 1, CC 35, 0–127.
|
||||
knob6 = first["knobs"][5]
|
||||
assert (knob6["type"], knob6["channel"], knob6["number"], knob6["left"], knob6["right"]) == (0, 1, 35, 0, 127)
|
||||
|
||||
|
||||
def test_factory_document_packs_back_to_the_midisuite_image():
|
||||
from pathlib import Path
|
||||
|
||||
from padcontroller.preset import pack
|
||||
from padcontroller.server import Editor
|
||||
|
||||
document = Editor().factory()
|
||||
assert pack(document) == (Path(__file__).parents[1] / "padcontroller" / "factory.bin").read_bytes()
|
||||
assert document["global"]["raw"] == "780032040000020001010000"
|
||||
|
||||
|
||||
def test_global_bank_byte_round_trips_and_is_checked():
|
||||
import pytest
|
||||
|
||||
from padcontroller.preset import PresetError, pack_global, unpack_global
|
||||
|
||||
raw = bytes.fromhex("780032040000020001010001")
|
||||
block = unpack_global(raw)
|
||||
assert block["bank"] == 1
|
||||
assert pack_global(block) == raw
|
||||
block["bank"] = 0
|
||||
assert pack_global(block)[11] == 0
|
||||
block["bank"] = 2
|
||||
with pytest.raises(PresetError):
|
||||
pack_global(block)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""padcontroller.midi: picking the pad's port and keeping the ALSA links up."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from padcontroller.midi import missing_links, parse_aconnect, pick_source # noqa: E402
|
||||
|
||||
BOTH = [
|
||||
"Midi Through:Midi Through Port-0 14:0",
|
||||
"SINCO:SINCO SMC-PAD-Private 20:0",
|
||||
"SINCO:SINCO SMC-PAD-Master 20:1",
|
||||
"SMC-PAD:SMC-PAD Bluetooth 128:0",
|
||||
"padcontroller-out:padcontroller 130:0",
|
||||
]
|
||||
|
||||
ACONNECT = """\
|
||||
client 20: 'SINCO' [type=kernel,card=1]
|
||||
0 'SINCO SMC-PAD-Private'
|
||||
1 'SINCO SMC-PAD-Master'
|
||||
\tConnecting To: 129:0
|
||||
client 128: 'SMC-PAD' [type=user,pid=1153]
|
||||
0 'SMC-PAD Bluetooth'
|
||||
client 129: 'padcontroller-in' [type=user,pid=57888]
|
||||
0 'RtMidi input '
|
||||
\tConnected From: 20:1
|
||||
client 130: 'padcontroller-out' [type=user,pid=57888]
|
||||
0 'padcontroller '
|
||||
client 131: 'qlcplus' [type=user,pid=57635]
|
||||
0 '__QLC__ '
|
||||
"""
|
||||
|
||||
|
||||
def test_usb_wins_over_bluetooth():
|
||||
assert BOTH[pick_source(BOTH)] == "SINCO:SINCO SMC-PAD-Master 20:1"
|
||||
|
||||
|
||||
def test_bluetooth_when_unplugged():
|
||||
names = [n for n in BOTH if "SINCO" not in n]
|
||||
assert names[pick_source(names)] == "SMC-PAD:SMC-PAD Bluetooth 128:0"
|
||||
|
||||
|
||||
def test_no_pad_and_never_our_own_port():
|
||||
assert pick_source(["padcontroller-out:padcontroller 130:0"]) is None
|
||||
|
||||
|
||||
def test_parse_aconnect_reads_links():
|
||||
ports = {p.addr: p for p in parse_aconnect(ACONNECT)}
|
||||
assert ports["20:1"].to == {"129:0"}
|
||||
assert ports["129:0"].sources == {"20:1"}
|
||||
assert ports["131:0"].client == "qlcplus"
|
||||
|
||||
|
||||
def test_relinks_qlc_after_a_restart():
|
||||
ports = parse_aconnect(ACONNECT)
|
||||
assert missing_links(ports, "SINCO:SINCO SMC-PAD-Master 20:1") == [("130:0", "131:0")]
|
||||
|
||||
|
||||
def test_relinks_a_replugged_pad_and_only_that_one():
|
||||
ports = parse_aconnect(ACONNECT.replace("\tConnected From: 20:1\n", ""))
|
||||
links = missing_links(ports, "SINCO:SINCO SMC-PAD-Master 20:1")
|
||||
assert ("20:1", "129:0") in links
|
||||
assert not any(src == "128:0" for src, _ in links)
|
||||
|
||||
|
||||
def test_nothing_missing_when_linked():
|
||||
text = ACONNECT.replace(" 0 'padcontroller '\n", " 0 'padcontroller '\n\tConnecting To: 131:0\n")
|
||||
assert missing_links(parse_aconnect(text), "SINCO:SINCO SMC-PAD-Master 20:1") == []
|
||||
assert missing_links(parse_aconnect(text), None) == []
|
||||
@@ -0,0 +1,448 @@
|
||||
"""Show engine: workspace XML, spec validation, animations, and the agent tools."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
from showfile import Show, midi_note
|
||||
from showfile.play import load_show
|
||||
from showfile.tools import list_fixtures, sample_animation, show_schema, validate_show, write_show
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NS = {"q": "http://www.qlcplus.org/Workspace"}
|
||||
|
||||
|
||||
def _xml(spec: dict) -> ET.Element:
|
||||
show = Show.from_spec(spec)
|
||||
return ET.fromstring(show.xml())
|
||||
|
||||
|
||||
def _text(root: ET.Element, path: str) -> list[str]:
|
||||
return [el.text or "" for el in root.findall(path, NS)]
|
||||
|
||||
|
||||
class ShowFileTest(unittest.TestCase):
|
||||
def spec(self) -> dict:
|
||||
return {
|
||||
"author": "Jimmy",
|
||||
"universes": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "Universe 1",
|
||||
"output": {
|
||||
"plugin": "ArtNet",
|
||||
"uid": "192.168.1.92",
|
||||
"ip": "192.168.1.228",
|
||||
"universe": 0,
|
||||
"line": 7,
|
||||
},
|
||||
}
|
||||
],
|
||||
"fixtures": [
|
||||
{
|
||||
"key": "m1",
|
||||
"manufacturer": "Small Eye 7",
|
||||
"model": "Mover",
|
||||
"mode": "43 Channel",
|
||||
"name": "Small Eye 7 #1",
|
||||
"address": 0,
|
||||
},
|
||||
{
|
||||
"key": "m2",
|
||||
"manufacturer": "Small Eye 7",
|
||||
"model": "Mover",
|
||||
"mode": "43 Channel",
|
||||
"name": "Small Eye 7 #2",
|
||||
"address": 44,
|
||||
},
|
||||
{
|
||||
"key": "can1",
|
||||
"manufacturer": "beamZ",
|
||||
"model": "BCC145",
|
||||
"mode": "8 Channel",
|
||||
"address": 87,
|
||||
},
|
||||
],
|
||||
"functions": [
|
||||
{
|
||||
"key": "eight",
|
||||
"type": "efx",
|
||||
"name": "Figure of 8",
|
||||
"algorithm": "Eight",
|
||||
"fixtures": ["m1", "m2"],
|
||||
"width": 40,
|
||||
"height": 30,
|
||||
"x_offset": 128,
|
||||
"y_offset": 140,
|
||||
"duration_ms": 8000,
|
||||
},
|
||||
{
|
||||
"key": "rel",
|
||||
"type": "efx",
|
||||
"name": "Rel",
|
||||
"algorithm": "Circle",
|
||||
"fixtures": ["m1"],
|
||||
"width": 20,
|
||||
"height": 0,
|
||||
"relative": True,
|
||||
"homes": {"m1": [100, 140]},
|
||||
"duration_ms": 4000,
|
||||
},
|
||||
{
|
||||
"key": "focus",
|
||||
"type": "sequence",
|
||||
"name": "Colour Focus",
|
||||
"run_order": "SingleShot",
|
||||
"steps": [
|
||||
{"fade_ms": 100, "values": {"m1": {"10": 0}}},
|
||||
{"fade_ms": 100, "values": {"m1": {"10": 255}}},
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "sweep",
|
||||
"type": "path",
|
||||
"name": "Sweep",
|
||||
"closed": False,
|
||||
"fixtures": [{"fixture": "m2", "mirror_pan": True}],
|
||||
"points": [
|
||||
{"pan": 80, "tilt": 160, "fade_ms": 1000},
|
||||
{"pan": 180, "tilt": 40, "fade_ms": 1000},
|
||||
],
|
||||
},
|
||||
{"key": "red", "type": "scene", "name": "Red", "values": {"can1": {"2": 255, "4": 0}}},
|
||||
{"key": "blue", "type": "scene", "name": "Blue", "values": {"can1": {"2": 0, "4": 255}}},
|
||||
{
|
||||
"key": "collapse",
|
||||
"type": "chaser",
|
||||
"name": "Ring Collapse",
|
||||
"run_order": "SingleShot",
|
||||
"steps": [
|
||||
{"function": "red", "fade_ms": 100, "hold_ms": 0},
|
||||
{"function": "blue", "fade_ms": 100, "hold_ms": 0},
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "cols",
|
||||
"type": "colour_chase",
|
||||
"name": "Can Chase",
|
||||
"fixtures": ["can1"],
|
||||
"channels": {"r": 2, "g": 3, "b": 4},
|
||||
"fade_ms": 0,
|
||||
"hold_ms": 100,
|
||||
"frames": [[[255, 0, 0]], [[0, 0, 255]]],
|
||||
},
|
||||
],
|
||||
"vc": [
|
||||
{
|
||||
"type": "slider",
|
||||
"caption": "Dim",
|
||||
"channels": [["can1", 0]],
|
||||
"x": 10,
|
||||
"y": 28,
|
||||
"w": 44,
|
||||
"h": 240,
|
||||
"value": 255,
|
||||
"fg": [255, 255, 255],
|
||||
},
|
||||
{
|
||||
"type": "button",
|
||||
"caption": "Red",
|
||||
"function": "red",
|
||||
"x": 20,
|
||||
"y": 300,
|
||||
"w": 110,
|
||||
"h": 60,
|
||||
"bg": [255, 0, 0],
|
||||
"input": {"universe": 1, "note": [9, 36]},
|
||||
},
|
||||
{
|
||||
"type": "xypad",
|
||||
"caption": "M1",
|
||||
"fixture": "m1",
|
||||
"x": 10,
|
||||
"y": 28,
|
||||
"w": 240,
|
||||
"h": 240,
|
||||
},
|
||||
{
|
||||
"type": "solo",
|
||||
"caption": "Looks",
|
||||
"x": 0,
|
||||
"y": 400,
|
||||
"w": 200,
|
||||
"h": 80,
|
||||
"children": [
|
||||
{
|
||||
"type": "button",
|
||||
"caption": "Blue",
|
||||
"function": "blue",
|
||||
"x": 4,
|
||||
"y": 24,
|
||||
"w": 60,
|
||||
"h": 40,
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
"run": ["eight"],
|
||||
}
|
||||
|
||||
def test_workspace_xml_has_patch_widgets_and_animations(self):
|
||||
show = Show.from_spec(self.spec())
|
||||
root = ET.fromstring(show.xml())
|
||||
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
||||
self.assertEqual(addresses, [0, 44, 87])
|
||||
output = root.find(".//q:Output", NS)
|
||||
self.assertEqual(output.get("Plugin"), "ArtNet")
|
||||
self.assertEqual(output.get("Line"), "7")
|
||||
self.assertEqual(output.find("q:PluginParameters", NS).get("outputIP"), "192.168.1.228")
|
||||
self.assertEqual(_text(root, ".//q:Algorithm"), ["Eight", "Circle"])
|
||||
self.assertEqual(_text(root, ".//q:IsRelative"), ["0", "1"])
|
||||
self.assertIn("127", _text(root, ".//q:Axis/q:Offset"))
|
||||
self.assertIn("0,100", "".join(_text(root, ".//q:FixtureVal")))
|
||||
steps = root.findall(".//q:Function[@Type='Sequence']/q:Step", NS)
|
||||
joined = " ".join(step.text or "" for step in steps)
|
||||
self.assertIn("0,175", joined)
|
||||
self.assertIn("10,255", joined)
|
||||
chaser = root.find(".//q:Function[@Name='Ring Collapse']", NS)
|
||||
self.assertEqual(
|
||||
[step.text for step in chaser.findall("q:Step", NS)],
|
||||
[str(show.functions_by_key["red"].id), str(show.functions_by_key["blue"].id)],
|
||||
)
|
||||
self.assertEqual(show.summary()["functions"]["rel"]["type"], "Collection")
|
||||
self.assertIsNotNone(root.find(".//q:SoloFrame", NS))
|
||||
button = root.find(".//q:Button[@Caption='Red']", NS)
|
||||
self.assertEqual(button.find("q:Input", NS).get("Channel"), str(midi_note(9, 36)))
|
||||
self.assertEqual(button.find("q:Function", NS).get("ID"), str(show.functions_by_key["red"].id))
|
||||
slider = root.find(".//q:Slider", NS)
|
||||
self.assertEqual(slider.find("q:Level", NS).get("Value"), "255")
|
||||
self.assertEqual(slider.find("q:Level/q:Channel", NS).text, "0")
|
||||
|
||||
def test_playback_moves_and_fades(self):
|
||||
show = Show.from_spec(self.spec())
|
||||
pans = {show_frame(show, t, ["eight"])["m1"][0] for t in range(0, 8000, 500)}
|
||||
self.assertGreater(len(pans), 1)
|
||||
self.assertEqual(show_frame(show, 0, ["eight"])["m1"][8], 255)
|
||||
relative = {show_frame(show, t, ["rel"])["m1"][0] for t in range(0, 4000, 250)}
|
||||
self.assertIn(100, relative)
|
||||
self.assertGreater(len(relative), 1)
|
||||
self.assertEqual(show_frame(show, 0, ["collapse"])["can1"][2], 0)
|
||||
self.assertEqual(show_frame(show, 100, ["collapse"])["can1"][2], 255)
|
||||
self.assertEqual(show_frame(show, 150, ["collapse"])["can1"], {2: 128, 4: 128})
|
||||
self.assertEqual(show_frame(show, 200, ["collapse"])["can1"], {2: 0, 4: 255})
|
||||
self.assertEqual(show_frame(show, 0, ["cols"])["can1"][2], 255)
|
||||
self.assertEqual(show_frame(show, 100, ["cols"])["can1"][2], 0)
|
||||
self.assertEqual(show_frame(show, 50, ["focus"])["m1"][10], 0)
|
||||
self.assertEqual(show_frame(show, 150, ["focus"])["m1"][10], 128)
|
||||
|
||||
def test_validation_names_the_key_and_write_stays_inside_the_project(self):
|
||||
result = validate_show(
|
||||
{
|
||||
"fixtures": [
|
||||
{"key": "can1", "manufacturer": "beamZ", "model": "BCC145", "mode": "nope", "address": 0}
|
||||
],
|
||||
"functions": [{"key": "eight", "type": "efx", "name": "E", "fixtures": ["missing"]}],
|
||||
}
|
||||
)
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertIn("fixtures.can1.mode", [item["path"] for item in result["errors"]])
|
||||
self.assertIn("functions.eight.fixtures", [item["path"] for item in result["errors"]])
|
||||
refused = write_show({}, "/tmp/showfile-outside.qxw")
|
||||
self.assertFalse(refused["ok"])
|
||||
self.assertFalse(Path("/tmp/showfile-outside.qxw").exists())
|
||||
|
||||
def test_tools_list_schema_sample_and_write(self):
|
||||
fixtures = list_fixtures()
|
||||
bcc = next(item for item in fixtures["fixtures"] if item["model"] == "BCC145")
|
||||
mode = next(item for item in bcc["modes"] if item["name"] == "8 Channel")
|
||||
self.assertEqual(mode["channels"][0]["name"], "Dimmer")
|
||||
self.assertIn("fixtures", show_schema()["properties"])
|
||||
sample = sample_animation(
|
||||
{
|
||||
"type": "efx",
|
||||
"algorithm": "Eight",
|
||||
"fixtures": ["m1", "m2"],
|
||||
"width": 40,
|
||||
"height": 30,
|
||||
"duration_ms": 8000,
|
||||
"relative": True,
|
||||
"homes": {"m1": [128, 140], "m2": [100, 140]},
|
||||
},
|
||||
steps=8,
|
||||
)
|
||||
self.assertTrue(sample["ok"])
|
||||
self.assertEqual([track["key"] for track in sample["tracks"]], ["m1", "m2"])
|
||||
self.assertGreater(len({point[0] for point in sample["tracks"][0]["points"]}), 1)
|
||||
target = ROOT / "shows" / "_showfile_test.qxw"
|
||||
try:
|
||||
written = write_show(self.spec(), "shows/_showfile_test.qxw")
|
||||
self.assertTrue(written["ok"])
|
||||
self.assertEqual(written["fixtures"]["can1"]["address"], 87)
|
||||
self.assertEqual(written["functions"]["eight"]["type"], "EFX")
|
||||
self.assertEqual(written["functions"]["rel"]["type"], "Collection")
|
||||
self.assertTrue(target.is_file())
|
||||
finally:
|
||||
target.unlink(missing_ok=True)
|
||||
|
||||
def test_animation_script_dry_run(self):
|
||||
show = load_show(ROOT / "scripts" / "anim" / "anim_eight.py")
|
||||
frames = [show_frame(show, t) for t in (0, 2000)]
|
||||
self.assertNotEqual(frames[0]["m1"][2], frames[1]["m1"][2])
|
||||
self.assertEqual(frames[0]["m1"][8], 255)
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-m", "showfile", "run", "scripts/anim/anim_eight.py", "--seconds", "0.1"],
|
||||
cwd=ROOT,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
payload = json.loads(completed.stdout)
|
||||
self.assertTrue(payload["ok"])
|
||||
self.assertEqual(payload["functions"], ["eight"])
|
||||
self.assertGreaterEqual(len(payload["samples"]), 1)
|
||||
|
||||
def test_simple_board_matches_the_stage_patch(self):
|
||||
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
|
||||
show = Show.from_spec(spec)
|
||||
root = ET.fromstring(show.xml())
|
||||
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
||||
self.assertEqual(addresses, [87, 95, 103, 111, 119, 127, 135, 143, 0, 44])
|
||||
captions = [el.get("Caption") for el in root.findall(".//q:XYPad", NS)]
|
||||
self.assertEqual(captions, ["M1 Position", "M2 Position"])
|
||||
sliders = root.findall(".//q:Slider", NS)
|
||||
self.assertEqual(len(sliders), 50)
|
||||
dim = next(el for el in sliders if el.get("Caption") == "C Dim")
|
||||
self.assertEqual(dim.find("q:Level", NS).get("Value"), "255")
|
||||
self.assertEqual(len(dim.findall("q:Level/q:Channel", NS)), 8)
|
||||
self.assertEqual(
|
||||
[el.get("Caption") for el in root.findall(".//q:Frame", NS) if el.get("Caption")],
|
||||
["Cans individual RGBW", "Movers individual RGBW"],
|
||||
)
|
||||
size = root.find(".//q:Properties/q:Size", NS)
|
||||
self.assertEqual((size.get("Width"), size.get("Height")), ("1654", "480"))
|
||||
|
||||
def test_stage_map_drives_the_whole_rig(self):
|
||||
stage = json.loads((ROOT / "stage" / "map.json").read_text(encoding="utf-8"))
|
||||
show = load_show(ROOT / "scripts" / "anim" / "anim_stage.py")
|
||||
self.assertEqual([fx.key for fx in show.fixtures], list(stage["fixtures"]))
|
||||
for key, raw in stage["fixtures"].items():
|
||||
fixture = show.fixtures_by_key[key]
|
||||
self.assertEqual(fixture.address, raw["address"])
|
||||
self.assertEqual(fixture.x, raw["x"])
|
||||
self.assertEqual(fixture.y, raw["y"])
|
||||
if "direction" in raw:
|
||||
self.assertEqual(fixture.direction, raw["direction"])
|
||||
if "zero" in raw:
|
||||
self.assertEqual(fixture.zero, raw["zero"])
|
||||
self.assertEqual(show.fixtures_by_key["#1"].channel("Red"), 2)
|
||||
self.assertEqual(len(show.fixtures_by_key["M1"].named("Red")), 7)
|
||||
self.assertEqual([group.name for group in show.groups], ["Cans", "Movers"])
|
||||
from showfile.play import dmx_frames
|
||||
|
||||
frame = show_frame(show, 100)
|
||||
dmx = dmx_frames(show, frame)
|
||||
self.assertEqual(dmx[0][87], 255)
|
||||
self.assertEqual(dmx[0][300 + 8], 255)
|
||||
self.assertEqual(frame["M1"][show.fixtures_by_key["M1"].channel("Zoom")], 40)
|
||||
colour = sum(
|
||||
frame[key][2] + frame[key][3] + frame[key][4]
|
||||
for key, raw in stage["fixtures"].items()
|
||||
if raw["kind"] == "can"
|
||||
)
|
||||
self.assertGreater(colour, 0)
|
||||
tracks = []
|
||||
for key in ("M1", "M3"):
|
||||
tracks.append([(show_frame(show, t)[key][0], show_frame(show, t)[key][2]) for t in range(0, 3000, 250)])
|
||||
self.assertGreater(len(set(tracks[0])), 1)
|
||||
self.assertNotEqual(tracks[0], tracks[1])
|
||||
spec = Show.from_spec({"stage": "stage/map.json", "run": []})
|
||||
self.assertEqual(spec.fixtures_by_key["M4"].address, 300)
|
||||
self.assertEqual(spec.fixtures_by_key["#15"].address, 199)
|
||||
missing = validate_show({"stage": "stage/no-such.json"})
|
||||
self.assertFalse(missing["ok"])
|
||||
self.assertEqual(missing["errors"][0]["path"], "stage")
|
||||
outside = validate_show({"stage": "/etc/passwd"})
|
||||
self.assertFalse(outside["ok"])
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-m", "showfile", "run", "scripts/anim/anim_stage.py", "--seconds", "0.1"],
|
||||
cwd=ROOT,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
payload = json.loads(completed.stdout)
|
||||
self.assertTrue(payload["ok"])
|
||||
self.assertEqual(payload["functions"], ["stage"])
|
||||
|
||||
def test_mcp_lists_and_calls_a_tool(self):
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "showfile.mcp"],
|
||||
cwd=ROOT,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
)
|
||||
assert proc.stdin and proc.stdout
|
||||
try:
|
||||
_mcp(proc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
|
||||
_mcp(proc, {"jsonrpc": "2.0", "method": "notifications/initialized"})
|
||||
listed = _mcp(proc, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||
names = [tool["name"] for tool in listed["result"]["tools"]]
|
||||
self.assertEqual(
|
||||
names,
|
||||
["list_fixtures", "show_schema", "validate_show", "write_show", "sample_animation", "run_animation"],
|
||||
)
|
||||
called = _mcp(
|
||||
proc,
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "list_fixtures", "arguments": {}},
|
||||
},
|
||||
)
|
||||
body = json.loads(called["result"]["content"][0]["text"])
|
||||
self.assertIn("BCC145", [item["model"] for item in body["fixtures"]])
|
||||
finally:
|
||||
if proc.stdin:
|
||||
proc.stdin.close()
|
||||
try:
|
||||
proc.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
if proc.stdout:
|
||||
proc.stdout.close()
|
||||
|
||||
|
||||
def show_frame(show: Show, elapsed: float, keys: list[str] | None = None) -> dict:
|
||||
from showfile import frame_at
|
||||
|
||||
return frame_at(show, elapsed, keys)
|
||||
|
||||
|
||||
def _mcp(proc: subprocess.Popen, message: dict) -> dict:
|
||||
data = json.dumps(message).encode()
|
||||
assert proc.stdin and proc.stdout
|
||||
proc.stdin.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
|
||||
proc.stdin.flush()
|
||||
if "id" not in message:
|
||||
return {}
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if line in (b"\r\n", b"\n"):
|
||||
break
|
||||
key, _, value = line.decode().partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
return json.loads(proc.stdout.read(int(headers["content-length"])))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Stage simulator: Art-Net decode and the XCHC patch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
from simulator.artnet import ArtNetNode, build_artdmx, parse_artdmx, parse_opcode
|
||||
from simulator.decode import apply_cto, decode_can, decode_mover, lens_angle, lens_spin, mix_rgbw, view_stage
|
||||
from simulator.server import Simulator, make_server
|
||||
from simulator.stage import apply_show, load_stage, set_heading, wrap_degrees
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_artdmx_roundtrip():
|
||||
frame = bytearray(512)
|
||||
frame[87] = 255
|
||||
frame[89] = 200
|
||||
packet = build_artdmx(frame, universe=0, sequence=3)
|
||||
parsed = parse_artdmx(packet)
|
||||
assert parsed is not None
|
||||
universe, data = parsed
|
||||
assert universe == 0
|
||||
assert data[87] == 255
|
||||
assert data[89] == 200
|
||||
assert parse_opcode(packet) == 0x5000
|
||||
|
||||
|
||||
def test_poll_is_not_dmx():
|
||||
packet = b"Art-Net\x00" + bytes([0x00, 0x20]) + bytes(10)
|
||||
assert parse_opcode(packet) == 0x2000
|
||||
assert parse_artdmx(packet) is None
|
||||
|
||||
|
||||
def test_xchc_patch_matches_the_stage_map():
|
||||
stage = load_stage(ROOT / "stage" / "map.json")
|
||||
apply_show(stage, ROOT / "shows" / "xchc.qxw")
|
||||
by_id = {fixture.id: fixture for fixture in stage.fixtures}
|
||||
assert by_id["#1"].address == 87
|
||||
assert by_id["#1"].dmx == 88
|
||||
assert by_id["#8"].address == 143
|
||||
assert by_id["M1"].address == 0
|
||||
assert by_id["M1"].dmx == 1
|
||||
assert by_id["M2"].address == 44
|
||||
assert by_id["M1"].channels == 43
|
||||
assert by_id["#3"].kind == "can"
|
||||
assert stage.output_ip == "192.168.1.228"
|
||||
assert stage.name == "xchc"
|
||||
assert by_id["#9"].x == -3.5 and by_id["#9"].y == -0.8
|
||||
assert by_id["#11"].y == -6.8 and by_id["#12"].x == 3.5
|
||||
assert by_id["#13"].x == -3.5 and by_id["#15"].x == 3.5
|
||||
assert by_id["#14"].x == 0.0 and by_id["#14"].y == -7.65
|
||||
assert by_id["#1"].address == 87 and by_id["#9"].address == 151
|
||||
assert by_id["#15"].address == 199 and by_id["M1"].address == 0
|
||||
assert by_id["M2"].address == 44 and by_id["#15"].channels == 8
|
||||
assert by_id["M3"].address == 257 and by_id["M3"].channels == 43
|
||||
assert by_id["M3"].x == -1.75 and by_id["M3"].y == -7.65
|
||||
assert by_id["M4"].address == 300 and by_id["M4"].x == 1.75
|
||||
assert by_id["#1"].direction == 90 and by_id["#8"].direction == -90
|
||||
assert by_id["#3"].direction == 0 and by_id["#14"].direction == -179
|
||||
assert by_id["M1"].zero == 0 and by_id["M4"].zero == 0
|
||||
assert stage.warnings == []
|
||||
|
||||
|
||||
def test_can_red_and_white():
|
||||
assert mix_rgbw(0, 0, 0, 255, 255) == (255, 255, 255)
|
||||
viewed = decode_can([255, 0, 255, 0, 0, 0, 0, 0])
|
||||
assert (viewed["r"], viewed["g"], viewed["b"]) == (255, 0, 0)
|
||||
assert viewed["function"] == "mix"
|
||||
assert viewed["strobe_hz"] == 0
|
||||
assert decode_can([255, 255, 255, 0, 0, 0, 0, 0])["strobe_hz"] > 0
|
||||
assert decode_can([128, 0, 0, 0, 0, 0, 120, 0])["effect"] is True
|
||||
|
||||
|
||||
def test_can_macro_functions():
|
||||
assert decode_can([255, 0, 0, 0, 0, 0, 51, 0])["function"] == "fixed"
|
||||
assert decode_can([255, 0, 0, 0, 0, 0, 51, 0])["r"] == 255
|
||||
assert decode_can([0, 0, 0, 0, 0, 0, 80, 0])["r"] == 0
|
||||
jump = decode_can([255, 0, 0, 0, 0, 0, 120, 200])
|
||||
assert jump["function"] == "jump"
|
||||
assert jump["speed_hz"] > 1
|
||||
assert jump["palette"][0] == [255, 0, 0]
|
||||
pulse = decode_can([255, 0, 255, 80, 0, 0, 170, 0])
|
||||
assert pulse["function"] == "pulse"
|
||||
assert pulse["r"] == 255 and pulse["g"] == 80
|
||||
assert decode_can([255, 0, 0, 0, 0, 0, 220, 0])["function"] == "gradient"
|
||||
sound = decode_can([255, 0, 0, 0, 0, 0, 255, 0])
|
||||
assert sound["function"] == "sound" and sound["sound"] == 2
|
||||
|
||||
|
||||
def test_mover_home_points_at_the_audience():
|
||||
channels = [0] * 43
|
||||
channels[0] = 128 # pan coarse, fine 0 → 32768, the centre of 540°
|
||||
channels[2] = 160
|
||||
channels[8] = 255
|
||||
channels[10] = 255 # red on the first pixel
|
||||
viewed = decode_mover(channels)
|
||||
assert viewed["pan_deg"] == 0
|
||||
assert viewed["r"] == 255
|
||||
assert viewed["beam_m"] > 2
|
||||
parked = [0] * 43
|
||||
parked[8] = 255
|
||||
assert decode_mover(parked)["beam_m"] >= 2.2
|
||||
assert lens_spin(0) == 0
|
||||
assert lens_spin(160) < 0
|
||||
assert lens_spin(230) > 0
|
||||
assert lens_angle(0) == 0
|
||||
assert 25 < lens_angle(64) < 35
|
||||
|
||||
|
||||
def test_mover_functions():
|
||||
channels = [0] * 43
|
||||
channels[5] = 230
|
||||
channels[6] = 255
|
||||
channels[8] = 255
|
||||
channels[39] = 20
|
||||
macro = decode_mover(channels)
|
||||
assert macro["function"] == "macro"
|
||||
assert macro["r"] == 255 and macro["b"] == 0
|
||||
assert macro["zoom_deg"] == 45
|
||||
assert macro["spin_dps"] > 0
|
||||
|
||||
channels[40] = 103
|
||||
static = decode_mover(channels)
|
||||
assert static["function"] == "static"
|
||||
assert static["pixels"][3][0] == 255
|
||||
assert static["pixels"][0] == [0, 0, 0]
|
||||
|
||||
channels[41] = 30
|
||||
dynamic = decode_mover(channels)
|
||||
assert dynamic["function"] == "dynamic"
|
||||
assert dynamic["dynamic"] == "chase"
|
||||
assert dynamic["pixels"][0][0] == 255
|
||||
assert dynamic["speed_hz"] > 0
|
||||
|
||||
warm = [0] * 43
|
||||
warm[8] = 255
|
||||
warm[10] = warm[11] = warm[12] = 255
|
||||
warm[38] = 255
|
||||
tinted = decode_mover(warm)
|
||||
assert tinted["r"] == 255
|
||||
assert tinted["b"] < apply_cto(255, 255, 255, 0)[2]
|
||||
assert tinted["b"] < 100
|
||||
|
||||
strobe = [0] * 43
|
||||
strobe[9] = 240
|
||||
assert decode_mover(strobe)["strobe_mode"] == "random"
|
||||
assert decode_mover([0] * 43)["strobe_mode"] == "open"
|
||||
|
||||
|
||||
def test_map_definition_selects_the_channels():
|
||||
stage = load_stage(ROOT / "stage" / "map.json")
|
||||
mover = next(fixture for fixture in stage.fixtures if fixture.id == "M1")
|
||||
can = next(fixture for fixture in stage.fixtures if fixture.id == "#1")
|
||||
assert can.channel_names[:3] == ["Dimmer", "Strobe", "Red"]
|
||||
assert mover.channel_names[5] == "Lens Rotate"
|
||||
assert mover.channel_names[6] == "Zoom"
|
||||
assert mover.mode == "43 Channel"
|
||||
|
||||
frame = bytearray(512)
|
||||
frame[mover.address + mover.channel_names.index("Pan")] = 128
|
||||
frame[mover.address + mover.channel_names.index("Zoom")] = 255
|
||||
frame[mover.address + mover.channel_names.index("Center Brightness")] = 255
|
||||
frame[mover.address + mover.channel_names.index("Red 1")] = 255
|
||||
frame[mover.address + mover.channel_names.index("Lens Rotate")] = 230
|
||||
live = view_stage(stage, {0: bytes(frame)})["M1"]
|
||||
assert live["zoom_deg"] == 45
|
||||
assert live["spin_dps"] > 0
|
||||
assert live["r"] == 255
|
||||
assert live["pan_deg"] == 0
|
||||
|
||||
|
||||
def test_view_reads_universe_bytes():
|
||||
stage = load_stage(ROOT / "stage" / "map.json")
|
||||
apply_show(stage, ROOT / "shows" / "xchc.qxw")
|
||||
frame = bytearray(512)
|
||||
frame[87] = 255
|
||||
frame[89] = 0
|
||||
frame[90] = 255
|
||||
live = view_stage(stage, {0: bytes(frame)})
|
||||
assert (live["#1"]["r"], live["#1"]["g"], live["#1"]["b"]) == (0, 255, 0)
|
||||
assert live["#2"]["dimmer"] == 0
|
||||
|
||||
|
||||
def test_http_state_follows_artnet():
|
||||
stage = load_stage(ROOT / "stage" / "map.json")
|
||||
apply_show(stage, ROOT / "shows" / "xchc.qxw")
|
||||
node = ArtNetNode("127.0.0.1", 0)
|
||||
node.start()
|
||||
server = make_server(Simulator(stage, node), "127.0.0.1", 0)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
frame = bytearray(512)
|
||||
frame[0] = 128
|
||||
frame[8] = 255
|
||||
frame[10] = 255
|
||||
node.write(0, frame)
|
||||
port = server.server_address[1]
|
||||
with urlopen(f"http://127.0.0.1:{port}/api/state") as response:
|
||||
payload = json.load(response)
|
||||
assert payload["packets"] == 1
|
||||
assert payload["fixtures"]["M1"]["r"] == 255
|
||||
with urlopen(f"http://127.0.0.1:{port}/api/stage") as response:
|
||||
described = json.load(response)
|
||||
assert described["fixtures"][0]["x"] == -3.5
|
||||
finally:
|
||||
server.shutdown()
|
||||
node.close()
|
||||
|
||||
|
||||
def test_heading_is_stored_in_the_map(tmp_path):
|
||||
target = tmp_path / "map.json"
|
||||
target.write_text((ROOT / "stage" / "map.json").read_text())
|
||||
stage = load_stage(target)
|
||||
assert wrap_degrees(270) == -90
|
||||
set_heading(stage, "#1", direction=45)
|
||||
set_heading(stage, "M1", zero=-30)
|
||||
saved = json.loads(target.read_text())
|
||||
assert saved["fixtures"]["#1"]["direction"] == 45
|
||||
assert saved["fixtures"]["#2"]["direction"] == 90
|
||||
assert saved["fixtures"]["M1"]["zero"] == -30
|
||||
assert saved["fixtures"]["M2"]["zero"] == 0
|
||||
again = load_stage(target)
|
||||
by_id = {fixture.id: fixture for fixture in again.fixtures}
|
||||
assert by_id["#1"].direction == 45
|
||||
assert by_id["M1"].zero == -30
|
||||
|
||||
|
||||
def test_switch_stage_lists_and_loads_maps_in_the_same_folder(tmp_path):
|
||||
first = tmp_path / "map.json"
|
||||
first.write_text((ROOT / "stage" / "map.json").read_text())
|
||||
data = json.loads(first.read_text())
|
||||
data["name"] = "movers only"
|
||||
data["fixtures"] = {key: value for key, value in data["fixtures"].items() if key.startswith("M")}
|
||||
(tmp_path / "movers.json").write_text(json.dumps(data))
|
||||
sim = Simulator(load_stage(first), node=None, show=ROOT / "shows" / "xchc.qxw")
|
||||
assert sim.stages() == {"current": "map.json", "stages": ["map.json", "movers.json"]}
|
||||
stage = sim.switch("movers.json")
|
||||
assert stage.name == "movers only"
|
||||
assert stage.show == "xchc.qxw"
|
||||
assert sim.stages()["current"] == "movers.json"
|
||||
for bad in ("../map.json", "missing.json"):
|
||||
try:
|
||||
sim.switch(bad)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(bad)
|
||||
Reference in new issue
Block a user