From 18f0ac2dc541ec7730432a77b2d6a8c109cd1d7d Mon Sep 17 00:00:00 2001 From: jimmy Date: Thu, 22 Oct 2026 17:58:04 +1300 Subject: [PATCH] Add a virtual pad and an end-to-end test against the simulator, and run tests with pytest. padcontroller.virtualpad presses pads and sets knobs through padcontroller-in, refusing unless QLC+ last opened shows/test.qxw. tests/test_e2e_pad.py uses it to check can and mover colours in the simulator's /api/state (PAD_E2E=1). pytest is a dev package now, so the plain test functions unittest skipped run too. test_small_eye.py is a rig tester, not a test, so pytest leaves it alone, and the #14 direction assertion now matches the stage map (-179). Co-Authored-By: Claude Opus 5.5 --- Pipfile | 1 + Pipfile.lock | 46 ++++++++++- README.md | 29 +++++++ padcontroller/virtualpad.py | 154 ++++++++++++++++++++++++++++++++++++ tests/conftest.py | 3 + tests/test_e2e_pad.py | 131 ++++++++++++++++++++++++++++++ tests/test_simulator.py | 2 +- 7 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 padcontroller/virtualpad.py create mode 100644 tests/conftest.py create mode 100644 tests/test_e2e_pad.py diff --git a/Pipfile b/Pipfile index 65f099e..72b505d 100644 --- a/Pipfile +++ b/Pipfile @@ -8,6 +8,7 @@ mido = "*" python-rtmidi = "*" [dev-packages] +pytest = "*" [requires] python_version = "3.12" diff --git a/Pipfile.lock b/Pipfile.lock index d454fa0..b590c01 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "2d3b4d17f2edcaf6aca89b25728de94c131f89c846aebf67a8c6ec4981497791" + "sha256": "42b99998dcced8eeecfc0b83f3589f113501d6245312302009027c9a91e11fa6" }, "pipfile-spec": 6, "requires": { @@ -67,5 +67,47 @@ "version": "==1.5.8" } }, - "develop": {} + "develop": { + "iniconfig": { + "hashes": [ + "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", + "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7" + ], + "markers": "python_version >= '3.10'", + "version": "==2.3.1" + }, + "packaging": { + "hashes": [ + "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", + "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c" + ], + "markers": "python_version >= '3.9'", + "version": "==26.3" + }, + "pluggy": { + "hashes": [ + "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", + "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8" + ], + "markers": "python_version >= '3.10'", + "version": "==1.7.0" + }, + "pygments": { + "hashes": [ + "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", + "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c" + ], + "markers": "python_version >= '3.9'", + "version": "==2.21.0" + }, + "pytest": { + "hashes": [ + "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", + "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c" + ], + "index": "pypi", + "markers": "python_version >= '3.10'", + "version": "==9.1.1" + } + } } diff --git a/README.md b/README.md index 96dd991..0f4850c 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,35 @@ Options after the command go to the pad controller (for example `--lock-knobs`). `--no-enable` installs it without starting it at login (start it with `systemctl --user start padcontroller`). `--uninstall` removes the service. Logs: `journalctl --user -u padcontroller -f`. +### Virtual pad + +`padcontroller.virtualpad` presses pads and turns knobs without touching the +pad. It sends into the pad controller's input, so presses get the Play layer +and smoothing like the real thing. It refuses unless QLC+ last opened +`shows/test.qxw` (127.0.0.1 only); `--force` skips that. + +```bash +.venv/bin/python -m padcontroller.virtualpad press 52 # Colour 1 Red +.venv/bin/python -m padcontroller.virtualpad press 52 --play # Play held: Colour 2 Red +.venv/bin/python -m padcontroller.virtualpad press --pad 1 # by pad number (shows/midi_map.json) +.venv/bin/python -m padcontroller.virtualpad cc 34 64 +``` + +`tests/test_e2e_pad.py` uses it to press colour pads and check the simulator's +`/api/state`. It drives the live rig, so it only runs with `PAD_E2E=1`: + +```bash +PAD_E2E=1 .venv/bin/python -m pytest tests/test_e2e_pad.py -v +``` + +The rest of the suite runs offline. Use pytest, since most tests are plain +`def test_` functions that `unittest` doesn't find (`pipenv install --dev` +installs it): + +```bash +.venv/bin/python -m pytest +``` + ## Stage simulator `python -m simulator` listens for Art-Net on port 6454 and draws the rig at diff --git a/padcontroller/virtualpad.py b/padcontroller/virtualpad.py new file mode 100644 index 0000000..7f8f678 --- /dev/null +++ b/padcontroller/virtualpad.py @@ -0,0 +1,154 @@ +"""Virtual pad: press SMC-PAD pads and turn knobs from the command line or a test. + +Sends into the pad controller's input port (padcontroller-in), so presses go +through the same Play layer and CC smoothing as the real pad before QLC+ sees +them. The real pad stays connected; both feed the same port. + +Before sending it checks that the workspace QLC+ opened last is shows/test.qxw, +which only sends Art-Net to 127.0.0.1 (the simulator). Pass --force to skip that. + +Usage: + .venv/bin/python -m padcontroller.virtualpad press 52 # note 52 on channel 10 + .venv/bin/python -m padcontroller.virtualpad press --pad 17 # pad number from shows/midi_map.json + .venv/bin/python -m padcontroller.virtualpad press 52 --play # with Play held (52 -> 68) + .venv/bin/python -m padcontroller.virtualpad cc 34 64 # knob CC 34 to 64 on channel 1 +""" + +from __future__ import annotations + +import argparse +import configparser +import json +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator + +import rtmidi + +from padcontroller.layer import PLAY_CC + +ROOT = Path(__file__).resolve().parents[1] +MIDI_MAP = ROOT / "shows" / "midi_map.json" +TEST_SHOW = ROOT / "shows" / "test.qxw" +QLC_CONF = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf" +TARGET_CLIENT = "padcontroller-in" +# The SMC-PAD sends pads on MIDI channel 10 and knobs on channel 1 (0-based here). +PAD_CHANNEL = 9 +KNOB_CHANNEL = 0 + + +def last_workspace(conf: Path = QLC_CONF) -> Path | None: + """The workspace QLC+ opened most recently, from its recent-files list.""" + parser = configparser.ConfigParser(interpolation=None, strict=False) + try: + parser.read(conf) + recent = parser.get("workspace", "recent0") + except (configparser.Error, OSError): + return None + path = Path(recent) + return path if path.is_absolute() else Path.home() / path + + +def check_test_show(conf: Path = QLC_CONF) -> None: + """Refuse to drive QLC+ unless its last workspace is the 127.0.0.1-only test show.""" + ws = last_workspace(conf) + if ws is None or ws.resolve() != TEST_SHOW.resolve(): + raise SystemExit( + f"QLC+'s last workspace is {ws or '(unknown)'}, not {TEST_SHOW.relative_to(ROOT)}. " + "Open the test show in QLC+ (or pass --force) so presses can't reach the real rig." + ) + + +def pad_note(pad: int, midi_map: Path = MIDI_MAP) -> tuple[int, int]: + """(channel, note) for a pad number in shows/midi_map.json.""" + for entry in json.loads(midi_map.read_text())["pads"]: + if entry["pad"] == pad: + return entry["channel"], entry["note"] + raise SystemExit(f"Pad {pad} is not in {midi_map.relative_to(ROOT)}") + + +class VirtualPad: + """An ALSA MIDI output linked to padcontroller-in.""" + + def __init__(self, target: str = TARGET_CLIENT) -> None: + self.out = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="virtualpad") + ports = self.out.get_ports() + i = next((i for i, name in enumerate(ports) if name.startswith(target + ":")), None) + if i is None: + raise RuntimeError( + f"No {target} MIDI port; is the padcontroller service running? Ports:\n " + + "\n ".join(ports or ["(none)"]) + ) + self.out.open_port(i, "virtualpad") + + def close(self) -> None: + self.out.close_port() + + def __enter__(self) -> VirtualPad: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + def send(self, data: list[int]) -> None: + self.out.send_message(data) + + def press(self, note: int, channel: int = PAD_CHANNEL, velocity: int = 127, hold: float = 0.05) -> None: + """Note on, wait hold seconds, note off: one tap of a pad.""" + self.send([0x90 | channel, note, velocity]) + time.sleep(hold) + self.send([0x80 | channel, note, 0]) + + def cc(self, cc: int, value: int, channel: int = KNOB_CHANNEL) -> None: + self.send([0xB0 | channel, cc, max(0, min(127, value))]) + + @contextmanager + def play(self) -> Iterator[None]: + """Hold Play for the block, so bank 2 pads go out a layer up.""" + self.cc(PLAY_CC, 127) + try: + yield + finally: + self.cc(PLAY_CC, 0) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--force", action="store_true", help="skip the check that QLC+ has the test show open") + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("press", help="tap a pad") + p.add_argument("note", type=int, nargs="?", help="MIDI note (channel 10 unless --channel)") + p.add_argument("--pad", type=int, help="pad number from shows/midi_map.json instead of a note") + p.add_argument("--channel", type=int, default=PAD_CHANNEL + 1, help="MIDI channel 1-16 (default 10)") + p.add_argument("--hold", type=float, default=0.05, help="seconds between note on and off") + p.add_argument("--play", action="store_true", help="hold Play while pressing") + c = sub.add_parser("cc", help="set a knob") + c.add_argument("cc", type=int) + c.add_argument("value", type=int) + c.add_argument("--channel", type=int, default=KNOB_CHANNEL + 1, help="MIDI channel 1-16 (default 1)") + args = ap.parse_args() + + if not args.force: + check_test_show() + with VirtualPad() as pad: + if args.cmd == "cc": + pad.cc(args.cc, args.value, args.channel - 1) + print(f"CC {args.cc} = {args.value} (channel {args.channel})") + return + if args.pad is not None: + channel, note = pad_note(args.pad) + elif args.note is not None: + channel, note = args.channel - 1, args.note + else: + raise SystemExit("press needs a note or --pad") + if args.play: + with pad.play(): + pad.press(note, channel, hold=args.hold) + else: + pad.press(note, channel, hold=args.hold) + print(f"Pressed note {note} (channel {channel + 1}){' with Play held' if args.play else ''}") + + +if __name__ == "__main__": + main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b65470f --- /dev/null +++ b/tests/conftest.py @@ -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"] diff --git a/tests/test_e2e_pad.py b/tests/test_e2e_pad.py new file mode 100644 index 0000000..9817270 --- /dev/null +++ b/tests/test_e2e_pad.py @@ -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() diff --git a/tests/test_simulator.py b/tests/test_simulator.py index 5a51e97..6b74e91 100644 --- a/tests/test_simulator.py +++ b/tests/test_simulator.py @@ -60,7 +60,7 @@ def test_xchc_patch_matches_the_stage_map(): 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 == 0 + 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 == []