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:
jimmyandClaude Opus 5.5 committed 2026-10-22 20:00:21 +13:00
commit 72c227b153
106 files changed
+33054 -420

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Figure-of-8 on the two Small Eye movers.
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim/anim_eight.py
python3 -m showfile run scripts/anim/anim_eight.py --seconds 1
Send Art-Net, for example at the stage simulator:
python3 scripts/anim/anim_eight.py --ip 127.0.0.1 --seconds 8
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile import Show
from showfile.play import script_main
def build() -> Show:
show = Show(author="Jimmy")
m1 = show.patch(
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #1", address=0, key="m1"
)
m2 = show.patch(
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #2", address=44, key="m2"
)
show.efx(
"Figure of 8",
[m1, m2],
algorithm="Eight",
width=40,
height=30,
x_offset=128,
y_offset=140,
duration_ms=8000,
key="eight",
)
show.run("eight")
return show
if __name__ == "__main__":
script_main(build)
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""The whole stage: a colour chase on the cans and a figure-8 on every mover.
The patch, positions, and channel names come from stage/map.json.
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim/anim_stage.py
python3 -m showfile run scripts/anim/anim_stage.py --seconds 1
Send Art-Net at the stage simulator:
python3 scripts/anim/anim_stage.py --ip 127.0.0.1 --seconds 12
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile import Show
from showfile.play import script_main
def build() -> Show:
show = Show(author="Jimmy")
rig = show.patch_stage(ROOT / "stage" / "map.json")
red, green, blue = (rig.cans[0].channel(name) for name in ("Red", "Green", "Blue"))
dimmers = {
can.key: {can.channel("Dimmer"): 255, can.channel("Strobe"): 0}
for can in rig.cans
}
show.scene("Can dimmers", dimmers, key="dim")
frames = []
count = len(rig.cans)
for head in range(count):
frame = []
for index in range(count):
colour = _hsv(index / count)
distance = min((index - head) % count, (head - index) % count)
if distance == 0:
frame.append(colour)
elif distance == 1:
frame.append(tuple(channel // 3 for channel in colour))
else:
frame.append((0, 0, 0))
frames.append(frame)
show.colour_chase(
"Can chase",
rig.cans,
{"r": red, "g": green, "b": blue},
frames,
fade_ms=80,
hold_ms=140,
key="chase",
)
look = {}
movers = []
for index, mover in enumerate(rig.movers):
colour = (255, 40, 0) if index % 2 == 0 else (40, 80, 255)
values = {
mover.channel("Zoom"): 40,
mover.channel("Dynamic Effect"): 30 if index % 2 == 0 else 160,
mover.channel("Lens Rotate"): 210 if index % 2 == 0 else 40,
}
for channel in mover.named("White"):
values[channel] = 0
for red_ch, green_ch, blue_ch in zip(mover.named("Red"), mover.named("Green"), mover.named("Blue")):
values[red_ch] = colour[0]
values[green_ch] = colour[1]
values[blue_ch] = colour[2]
look[mover.key] = values
movers.append({"fixture": mover, "start_offset": index * 90})
show.scene("Mover look", look, key="look")
show.efx(
"Movers",
movers,
algorithm="Eight",
width=36,
height=22,
x_offset=128,
y_offset=140,
duration_ms=12000,
key="movers",
)
show.collection("Stage", ["dim", "chase", "look", "movers"], key="stage")
show.run("stage")
return show
def _hsv(hue: float) -> tuple[int, int, int]:
hue = hue % 1.0
segment = int(hue * 6) % 6
frac = hue * 6 - int(hue * 6)
fade = int(255 * (1 - frac))
rise = int(255 * frac)
if segment == 0:
return 255, rise, 0
if segment == 1:
return fade, 255, 0
if segment == 2:
return 0, 255, rise
if segment == 3:
return 0, fade, 255
if segment == 4:
return rise, 0, 255
return 255, 0, fade
if __name__ == "__main__":
script_main(build)
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env bash
# Flash LuxDMX onto a Seeed Studio XIAO ESP32S3.
#
# The XIAO is an ESP32-S3R8 (octal 8 MB PSRAM, native USB only). It shows up
# as an Espressif "USB JTAG/serial" port (/dev/ttyACM*), not a ttyUSB UART
# dongle. This downloads the current LuxDMX release and writes the
# octal-PSRAM image. esptool detects the flash size and rewrites the image
# header to match (this board reports 16 MB). The partition table ends at
# 4 MB, so either size fits. The write is a full erase, so the first boot
# opens the setup access point.
#
# scripts/flash_luxdmx_xiao.sh
# scripts/flash_luxdmx_xiao.sh --port /dev/ttyACM0
# scripts/flash_luxdmx_xiao.sh --plain # leave the PSRAM unused
# scripts/flash_luxdmx_xiao.sh --version v1.0.273
# scripts/flash_luxdmx_xiao.sh --dry-run
#
# A full USB flash erases saved Wi-Fi and config. To update a board that is
# already set up, use the device's own Firmware Update page instead.
#
# After it boots, join the open Wi-Fi "LuxDMX-setup" and open
# http://192.168.4.1. In /config apply the "Seeed XIAO ESP32-S3" template:
# DMX data is D0 (GPIO1) and the RDM return is D1 (GPIO2). The DevKit
# defaults (GPIO16/17) are not broken out on this board.
set -euo pipefail
REPO="tombueng/LuxDMX"
TAG="latest"
PORT=""
PLAIN=0
YES=0
DRY=0
BAUD=921600
usage() {
sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'
exit 2
}
while [[ $# -gt 0 ]]; do
case "$1" in
--port) PORT="${2:?}"; shift 2 ;;
--version) TAG="${2:?}"; shift 2 ;;
--baud) BAUD="${2:?}"; shift 2 ;;
--plain) PLAIN=1; shift ;;
--yes) YES=1; shift ;;
--dry-run) DRY=1; shift ;;
-h|--help) usage ;;
*) echo "Unknown option: $1" >&2; usage ;;
esac
done
# Ubuntu's esptool package is missing the ESP32-S3 flasher stub, so a
# version check is not enough. Use it only when that stub is actually there.
esptool_has_s3_stub() {
"$1" - << 'PY'
import pathlib, sys
try:
import esptool
except ImportError:
sys.exit(1)
root = pathlib.Path(esptool.__file__).resolve().parent / "targets" / "stub_flasher"
ok = (root / "stub_flasher_32s3.json").is_file() or any(root.glob("*/esp32s3.json"))
sys.exit(0 if ok else 1)
PY
}
if esptool_has_s3_stub python3; then
ESPTOOL=(python3 -m esptool)
else
VENV="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx/esptool-venv"
if [[ ! -x "$VENV/bin/python" ]] || ! esptool_has_s3_stub "$VENV/bin/python"; then
echo "System esptool has no ESP32-S3 stub. Installing one into ${VENV}…"
python3 -m venv "$VENV"
"$VENV/bin/pip" install -q 'esptool>=4.8,<5'
fi
ESPTOOL=("$VENV/bin/python" -m esptool)
fi
if [[ "$PLAIN" -eq 1 ]]; then
BOOT="bootloader-esp32s3.bin"
PARTS="partitions-esp32s3.bin"
APP="firmware-esp32s3.bin"
IMAGE="plain ESP32-S3 (PSRAM left unused)"
else
BOOT="bootloader-esp32s3-psram.bin"
PARTS="partitions-esp32s3-psram.bin"
APP="firmware-esp32s3-psram.bin"
IMAGE="ESP32-S3 octal PSRAM (XIAO ESP32S3 / S3R8)"
fi
find_port() {
if [[ -n "$PORT" ]]; then
[[ -e "$PORT" ]] || { echo "Port not found: $PORT" >&2; exit 1; }
echo "$PORT"
return
fi
local -a matches=()
local p
shopt -s nullglob
for p in /dev/serial/by-id/*; do
case "$p" in
*[Ee]spressif*|*[Ss]eeed*|*[Xx][Ii][Aa][Oo]*)
matches+=("$(readlink -f "$p")")
;;
esac
done
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 ]]; then
echo "${matches[0]}"
return
fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "More than one Espressif/Seeed serial port. Pass --port." >&2
printf ' %s\n' "${matches[@]}" >&2
exit 1
fi
shopt -s nullglob
matches=(/dev/ttyACM*)
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 && -e "${matches[0]}" ]]; then
echo "${matches[0]}"
return
fi
echo "No XIAO found. Plug in the USB-C port, then re-run." >&2
echo "If it still does not appear: hold B, tap R, release B, and pass --port." >&2
exit 1
}
CACHE_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx"
mkdir -p "$CACHE_ROOT"
mapfile -t DL < <(python3 - "$CACHE_ROOT" "$TAG" "$BOOT" "$PARTS" "boot_app0.bin" "$APP" << 'PY'
import json, pathlib, sys, urllib.request
cache_root, tag, *names = sys.argv[1:]
api = f"https://api.github.com/repos/tombueng/LuxDMX/releases/tags/{tag}"
req = urllib.request.Request(api, headers={"Accept": "application/vnd.github+json", "User-Agent": "luxdmx-flash"})
with urllib.request.urlopen(req, timeout=60) as resp:
release = json.load(resp)
name = release.get("name") or release.get("tag_name") or tag
# "Latest → v1.0.273 (....)" — cache by the version, not the moving tag.
version = name
for token in name.replace("→", " ").replace("(", " ").split():
if token.startswith("v") and token[1:2].isdigit():
version = token
break
assets = {a["name"]: a for a in release.get("assets", [])}
missing = [n for n in names if n not in assets]
if missing:
sys.exit(f"Release {version} has no {', '.join(missing)}")
dest = pathlib.Path(cache_root) / version
dest.mkdir(parents=True, exist_ok=True)
for n in names:
path = dest / n
size = assets[n]["size"]
if path.is_file() and path.stat().st_size == size:
continue
url = assets[n]["browser_download_url"]
tmp = path.with_suffix(path.suffix + ".part")
urllib.request.urlretrieve(url, tmp)
if tmp.stat().st_size != size:
tmp.unlink(missing_ok=True)
sys.exit(f"Short download: {n}")
tmp.replace(path)
print(version)
print(dest)
PY
)
VERSION="${DL[0]}"
DIR="${DL[1]}"
PORT="$(find_port)"
echo "LuxDMX ${VERSION} (${IMAGE})"
echo "Port ${PORT} baud ${BAUD}"
echo "This erases the whole flash, including saved Wi-Fi and config."
if [[ "$DRY" -eq 1 ]]; then
echo "Dry run — not flashing."
exit 0
fi
if [[ "$YES" -ne 1 ]]; then
if [[ ! -t 0 ]]; then
echo "Pass --yes to flash without a prompt." >&2
exit 1
fi
read -r -p "Flash now? [y/N] " ans
[[ "$ans" == [yY] ]] || { echo "Cancelled."; exit 1; }
fi
set +e
"${ESPTOOL[@]}" --chip esp32s3 --port "$PORT" --baud "$BAUD" \
--before default_reset --after hard_reset \
write_flash --erase-all --flash_mode keep --flash_freq keep --flash_size detect --compress \
0x0000 "${DIR}/${BOOT}" \
0x8000 "${DIR}/${PARTS}" \
0xe000 "${DIR}/boot_app0.bin" \
0x10000 "${DIR}/${APP}"
rc=$?
set -e
if [[ $rc -ne 0 ]]; then
echo >&2
echo "Flash failed. Put the XIAO in download mode and run this again:" >&2
echo " hold B, tap R, release B, then: $0 --port $PORT --yes" >&2
exit $rc
fi
cat << 'EOF'
Flashed. On first boot the XIAO opens an open Wi-Fi network:
SSID LuxDMX-setup
URL http://192.168.4.1
In /config, apply the "Seeed XIAO ESP32-S3" template so the DMX pins
match the header (D0 = data out, D1 = RDM return). Then point QLC+
Art-Net at the address shown there, universe 0.
EOF
-305
View File
@@ -1,305 +0,0 @@
#!/usr/bin/env python3
"""Generate shows/simple.qxw — per-mover position + shared and individual RGBW."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "shows" / "simple.qxw"
# Fixture IDs match shows/xchc.qxw
CANS = list(range(8)) # BCC145 #1–#8
M1, M2 = 8, 9
MOVERS = [M1, M2]
# Can 8ch: Dim=0, R=2, G=3, B=4, W=5
# Mover 43ch: Center Bright=8; RGBW heads 1–7
MOVER_R = [10, 14, 18, 22, 26, 30, 34]
MOVER_G = [11, 15, 19, 23, 27, 31, 35]
MOVER_B = [12, 16, 20, 24, 28, 32, 36]
MOVER_W = [13, 17, 21, 25, 29, 33, 37]
COLORS = [
("R", 2, MOVER_R, "4294901760", "Red"),
("G", 3, MOVER_G, "4278255360", "Green"),
("B", 4, MOVER_B, "4278190335", "Blue"),
("W", 5, MOVER_W, "4294967295", "None"),
]
def appearance(
fg: str = "Default",
bg: str = "Default",
frame: str = "Sunken",
) -> str:
return f""" <Appearance>
<FrameStyle>{frame}</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def slider(
wid: int,
caption: str,
x: int,
y: int,
w: int,
h: int,
channels: list[tuple[int, int]],
*,
value: int = 0,
fg: str = "Default",
cng: str = "None",
) -> str:
ch_xml = "\n".join(
f' <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in channels
)
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance(fg=fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{ch_xml}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>"""
def xypad(wid: int, caption: str, fid: int, x: int, y: int, w: int, h: int) -> str:
return f""" <XYPad Caption="{caption}" ID="{wid}" InvertedAppearance="0">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance()}
<Fixture ID="{fid}" Head="0">
<Axis ID="X" LowLimit="0" HighLimit="1" Reverse="False"/>
<Axis ID="Y" LowLimit="0" HighLimit="1" Reverse="False"/>
</Fixture>
<Window hMin="0" hMax="255" vMin="0" vMax="255"/>
<Pan Position="128"/>
<Tilt Position="128"/>
</XYPad>"""
def label_frame(caption: str, x: int, y: int, w: int, h: int) -> str:
return f""" <Frame Caption="{caption}">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
<AllowChildren>True</AllowChildren>
<AllowResize>True</AllowResize>
<ShowHeader>True</ShowHeader>
<ShowEnableButton>False</ShowEnableButton>
<ShowIntensityButton>False</ShowIntensityButton>
<Mixing>False</Mixing>
</Frame>"""
def fixture_xml() -> str:
parts = []
for i in range(8):
parts.append(
f""" <Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>{i}</ID>
<Name>BCC145 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{87 + i * 8}</Address>
<Channels>8</Channels>
</Fixture>"""
)
for i, addr in enumerate((0, 44)):
parts.append(
f""" <Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>{8 + i}</ID>
<Name>Small Eye 7 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>43</Channels>
</Fixture>"""
)
return "\n".join(parts)
def main() -> None:
pad_w, pad_h = 240, 240
sl_w, sl_h = 44, 240
ind_w, ind_h = 36, 160
gap = 8
widgets: list[str] = []
wid = 0
max_x = 0
max_y = 0
def place_slider(caption, x, y, w, h, channels, value=0, fg="Default", cng="None"):
nonlocal wid, max_x, max_y
widgets.append(
slider(wid, caption, x, y, w, h, channels, value=value, fg=fg, cng=cng)
)
wid += 1
max_x = max(max_x, x + w)
max_y = max(max_y, y + h)
y0 = 28
x = 10
widgets.append(xypad(wid, "M1 Position", M1, x, y0, pad_w, pad_h))
wid += 1
x += pad_w + gap
widgets.append(xypad(wid, "M2 Position", M2, x, y0, pad_w, pad_h))
wid += 1
x += pad_w + gap + 12
max_x = max(max_x, x)
max_y = max(max_y, y0 + pad_h)
place_slider("C Dim", x, y0, sl_w, sl_h, [(f, 0) for f in CANS], 255, "4294967295")
x += sl_w + 2
for name, can_ch, _mover_chs, fg, cng in COLORS:
place_slider(
f"C {name}",
x,
y0,
sl_w,
sl_h,
[(f, can_ch) for f in CANS],
fg=fg,
cng=cng,
)
x += sl_w + 2
x += 14
place_slider("M Dim", x, y0, sl_w, sl_h, [(f, 8) for f in MOVERS], 255, "4294967295")
x += sl_w + 2
for name, _can_ch, mover_chs, fg, cng in COLORS:
place_slider(
f"M {name}",
x,
y0,
sl_w,
sl_h,
[(f, c) for f in MOVERS for c in mover_chs],
fg=fg,
cng=cng,
)
x += sl_w + 2
y1 = y0 + pad_h + 36
x = 10
widgets.append(label_frame("Cans individual RGBW", x, y1 - 28, 200, 24))
for i, fid in enumerate(CANS):
col_x = x + i * (4 * (ind_w + 2) + 10)
for j, (name, can_ch, _m, fg, cng) in enumerate(COLORS):
place_slider(
f"{i + 1}{name}",
col_x + j * (ind_w + 2),
y1,
ind_w,
ind_h,
[(fid, can_ch)],
fg=fg,
cng=cng,
)
mx = x + 8 * (4 * (ind_w + 2) + 10) + 16
widgets.append(label_frame("Movers individual RGBW", mx, y1 - 28, 220, 24))
for mi, (fid, label) in enumerate(((M1, "M1"), (M2, "M2"))):
col_x = mx + mi * (4 * (ind_w + 2) + 14)
for j, (name, _can_ch, mover_chs, fg, cng) in enumerate(COLORS):
place_slider(
f"{label}{name}",
col_x + j * (ind_w + 2),
y1,
ind_w,
ind_h,
[(fid, c) for c in mover_chs],
fg=fg,
cng=cng,
)
total_w = max_x + 16
total_h = max_y + 16
qxw = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="192.168.1.92" Line="7">
<PluginParameters outputIP="192.168.1.228" outputUni="0"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixture_xml()}
<FixtureGroup ID="0">
<Name>BCC145 U</Name>
<Size X="8" Y="1"/>
<Head X="0" Y="0" Fixture="0">0</Head>
<Head X="1" Y="0" Fixture="1">0</Head>
<Head X="2" Y="0" Fixture="2">0</Head>
<Head X="3" Y="0" Fixture="3">0</Head>
<Head X="4" Y="0" Fixture="4">0</Head>
<Head X="5" Y="0" Fixture="5">0</Head>
<Head X="6" Y="0" Fixture="6">0</Head>
<Head X="7" Y="0" Fixture="7">0</Head>
</FixtureGroup>
<FixtureGroup ID="1">
<Name>Small Eye Movers</Name>
<Size X="2" Y="1"/>
<Head X="0" Y="0" Fixture="8">0</Head>
<Head X="1" Y="0" Fixture="9">0</Head>
</FixtureGroup>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
{"\n".join(widgets)}
</Frame>
<Properties>
<Size Width="{total_w}" Height="{total_h}"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
"""
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(qxw)
print(f"Wrote {OUT} ({total_w}x{total_h}, {wid} widgets)")
if __name__ == "__main__":
main()
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Print the SMC-PAD SysEx in a usbmon capture.
sudo tcpdump -i usbmon1 -s 0 -U -w - > captures/pad.pcap
python3 scripts/pad/decode_usbmon.py captures/pad.pcap --device 21
Each USB-MIDI packet is reassembled into messages per cable, then SINCO
SysEx is decoded to its command, memory, address, and data.
"""
from __future__ import annotations
import argparse
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from padcontroller.sysex import decode # noqa: E402
LINKTYPE_USB_LINUX_MMAPPED = 220
HEADER = struct.Struct("<QBBBBHBBqiiIIQiiII") # 64 bytes
# Payload bytes carried by each USB-MIDI code index number.
CIN_SIZE = {0x2: 2, 0x3: 3, 0x4: 3, 0x5: 1, 0x6: 2, 0x7: 3, 0x8: 3, 0x9: 3,
0xA: 3, 0xB: 3, 0xC: 2, 0xD: 2, 0xE: 3, 0xF: 1}
COMMANDS = {0x00: "ack", 0x22: "write", 0x23: "read"}
def packets(path: Path):
raw = path.read_bytes()
magic = struct.unpack_from("<I", raw)[0]
if magic not in (0xA1B2C3D4, 0xA1B23C4D):
raise SystemExit(f"{path} is not a little-endian pcap")
linktype = struct.unpack_from("<I", raw, 20)[0]
if linktype != LINKTYPE_USB_LINUX_MMAPPED:
raise SystemExit(f"{path} has link type {linktype}, expected usbmon ({LINKTYPE_USB_LINUX_MMAPPED})")
at = 24
while at + 16 <= len(raw):
sec, frac, incl, _orig = struct.unpack_from("<IIII", raw, at)
at += 16
yield sec + frac / 1e6, raw[at:at + incl]
at += incl
def transfers(path: Path, device: int | None):
"""(time, direction, data) for bulk and interrupt transfers that carry data."""
for stamp, frame in packets(path):
if len(frame) < HEADER.size:
continue
fields = HEADER.unpack_from(frame)
kind, xfer, endpoint, devnum = fields[1], fields[2], fields[3], fields[4]
if device is not None and devnum != device:
continue
if xfer not in (1, 3):
continue
data = frame[HEADER.size:]
inbound = bool(endpoint & 0x80)
# Host-to-pad data rides on the submit, pad-to-host on the completion.
if data and ((not inbound and kind == ord("S")) or (inbound and kind == ord("C"))):
yield stamp, "pad→host" if inbound else "host→pad", data
def messages(path: Path, device: int | None):
pending: dict[tuple[str, int], bytearray] = {}
for stamp, direction, data in transfers(path, device):
for at in range(0, len(data) - 3, 4):
head = data[at]
cin, cable = head & 0x0F, head >> 4
if head == 0:
continue
body = data[at + 1:at + 1 + CIN_SIZE.get(cin, 0)]
key = (direction, cable)
if cin in (0x4, 0x5, 0x6, 0x7) or (pending.get(key) and cin == 0xF):
buf = pending.setdefault(key, bytearray())
buf += body
if cin != 0x4 and buf.endswith(b"\xf7"):
yield stamp, direction, cable, bytes(buf)
del pending[key]
else:
yield stamp, direction, cable, bytes(body)
def describe(message: bytes) -> str:
if message[:1] != b"\xf0" or message[-1:] != b"\xf7":
return message.hex(" ")
inner = decode(message[1:-1])
if inner[:2] != b"\x00\x59" or len(inner) < 7:
return f"sysex {inner.hex(' ')}"
command = COMMANDS.get(inner[2], f"cmd {inner[2]:#04x}")
length = int.from_bytes(inner[3:6], "little")
payload = inner[6:6 + length]
if inner[2] in (0x22, 0x23) and len(payload) >= 8:
memory = payload[0]
address = int.from_bytes(payload[1:5], "little")
size = int.from_bytes(payload[5:8], "little")
data = payload[8:]
text = f"{command} mem {memory} addr {address:#010x} len {size}"
return f"{text} data {data.hex()}" if data else text
return f"{command} {payload.hex(' ')}"
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("capture", type=Path)
parser.add_argument("--device", type=int, help="USB device number from lsusb")
args = parser.parse_args(argv)
start = None
for stamp, direction, cable, message in messages(args.capture, args.device):
start = stamp if start is None else start
print(f"{stamp - start:8.3f} {direction} cable {cable} {describe(message)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Print SMC-PAD pad and knob numbers.
pipenv run python scripts/midi.py
pipenv run python scripts/pad/midi.py
Each pad press prints pad N. Each knob turn prints knob N and its step
(+ for up, - for down).
@@ -18,7 +18,7 @@ from pathlib import Path
import mido
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
MAP_PATH = ROOT / "shows" / "midi_map.json"
# (channel, note) -> pad number. Loaded from shows/midi_map.json.
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""Store scene colours in an SMC-PAD preset bank.
Pad bank 1 is notes 36–51 and pad bank 2 is notes 52–67, bottom-left
first. Note messages do not change these lamps. The colour is three
bytes in the preset, written over the Private USB port.
.venv/bin/python scripts/pad/pad_colours.py --xchc --bank 2
.venv/bin/python scripts/pad/pad_colours.py --colour-set --bank 2
.venv/bin/python scripts/pad/pad_colours.py --dry-run
.venv/bin/python scripts/pad/pad_colours.py --clear
.venv/bin/python scripts/pad/pad_colours.py --identify
--identify lights every pad on a page in that page's colour, in rainbow
order, in all eight presets, so the page on show can be read at a glance.
The write is checked by reading it back. It is sent to the running copy
and to the stored preset, and it leaves notes, channels, and knobs as
they are. An empty write at the start of the preset then commits it,
which is what MidiSuite's Save button sends.
"""
from __future__ import annotations
import argparse
import glob
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from patch_smc_pad import PAD_COLORS # noqa: E402
from padcontroller import preset # noqa: E402
from padcontroller.device import PadError, read_image, save_image, transact # noqa: E402
from padcontroller.device import private_port as _private_port # noqa: E402
from padcontroller.preset import scale # noqa: E402
from padcontroller.sysex import ( # noqa: E402
RAM,
decode,
encode,
payload_data,
read_request,
save_request,
write_request,
)
# Preset image, memory type 5. Each of these offsets is a note-36 pad,
# and the next 15 records are notes 37–51. The running copy is at RAM.
RECORD = 26
RGB_AT = 4
BANKS = (1044, 8122, 11661, 15200, 18739, 22278, 25817)
def led_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]:
return (min(255, r + w), min(255, g + w), min(255, b + w))
# shows/xchc.qxw functions 0–8, in that order. The pad lamps are RGB, so
# the white scene is stored as white rather than the can's white channel.
XCHC_COLOURS = (
("Red", 255, 0, 0),
("Orange", 255, 127, 0),
("Yellow", 255, 255, 0),
("Green", 0, 255, 0),
("Cyan", 0, 255, 255),
("Blue", 0, 0, 255),
("Violet", 127, 0, 255),
("Magenta", 255, 0, 255),
("White", 255, 255, 255),
)
# One colour per pad page, page 1 first. Rainbow order, so the page
# number can be counted from red.
PAGE_COLOURS = (
("Red", 255, 0, 0),
("Orange", 255, 100, 0),
("Yellow", 255, 255, 0),
("Green", 0, 255, 0),
("Cyan", 0, 255, 255),
("Blue", 0, 0, 255),
("Violet", 160, 0, 255),
("White", 255, 255, 255),
)
def identify_image(image: bytes) -> bytes:
"""The image with each pad page lit in its PAGE_COLOURS colour."""
out = bytearray(image)
for number in range(preset.PRESET_COUNT):
for index in range(preset.PAD_COUNT):
_name, red, green, blue = PAGE_COLOURS[index // preset.PAGE_LEN]
at = preset.colour_offset(number, index)
out[at:at + 3] = bytes((scale(red), scale(green), scale(blue)))
return bytes(out)
def scene_colours(clear: bool = False) -> list[tuple[str, bytes]]:
colours = []
for name, r, g, b, w in PAD_COLORS:
if clear:
colours.append((name, b"\x00\x00\x00"))
continue
red, green, blue = led_rgb(r, g, b, w)
colours.append((name, bytes((scale(red), scale(green), scale(blue)))))
return colours
def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]:
"""The nine xchc colour scenes, then the rest of the 16-pad bank off."""
colours = []
for name, red, green, blue in XCHC_COLOURS:
rgb = b"\x00\x00\x00" if clear else bytes((scale(red), scale(green), scale(blue)))
colours.append((name, rgb))
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
return colours
def colour_set(clear: bool = False) -> list[tuple[str, bytes]]:
"""The colours of shows/test.qxw in pad order, then the rest of the bank off."""
sys.path.insert(0, str(ROOT / "scripts" / "shows"))
from colour_sets import COLOURS
colours = []
for name, r, g, b, w in COLOURS:
rgb = b"\x00\x00\x00" if clear else bytes(scale(c) for c in led_rgb(r, g, b, w))
colours.append((name, rgb))
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
return colours
# Preset page whose records light each pad bank. Page 3 also sends notes
# 52–67 but its colours are not shown; bank 2 takes them from page 7.
BANK_PAGE = {1: 2, 2: 7}
def bank_bases(bank: int) -> tuple[int, ...]:
"""Preset addresses where this pad bank's note records start."""
if bank < 1:
raise ValueError(f"pad bank {bank} is not on this controller")
page = BANK_PAGE.get(bank, bank + 1)
skip = (page - 2) * 16 * RECORD
return tuple(base + skip for base in BANKS)
def colour_writes(
clear: bool = False,
bank: int = 1,
colours: list[tuple[str, bytes]] | None = None,
) -> list[tuple[str, int, bytes]]:
"""(name, address, rgb) for one pad bank in every preset."""
palette = scene_colours(clear) if colours is None else list(colours)
if clear and colours is not None:
palette = [(name, b"\x00\x00\x00") for name, _rgb in palette]
placed = []
for base in bank_bases(bank):
for index, (name, rgb) in enumerate(palette):
placed.append((name, base + index * RECORD + RGB_AT, rgb))
return placed
def payload_data(decoded: bytes) -> bytes:
"""Bytes after the type, address, and length in a read reply."""
if decoded[:3] != b"\x00\x59\x23":
raise ValueError(f"unexpected reply {decoded[:8].hex()}")
payload = decoded[6:-1]
return payload[8:]
def private_port(names: list[str]) -> str:
try:
return _private_port(names)
except PadError as exc:
raise SystemExit(str(exc)) from exc
def apply(
clear: bool,
bank: int = 1,
colours: list[tuple[str, bytes]] | None = None,
any_note: bool = False,
) -> None:
for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
if path not in sys.path:
sys.path.insert(0, path)
import rtmidi
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
port = private_port(midiout.get_ports())
index = midiout.get_ports().index(port)
midiin.open_port(index)
midiin.ignore_types(sysex=False, timing=True, active_sense=True)
midiout.open_port(index)
print(f"Port: {port}", flush=True)
try:
note = 36 + (bank - 1) * 16
for base in bank_bases(bank):
reply = transact(midiout, midiin, read_request(base, 2))
mark = payload_data(reply)
if mark[0] != 0x09 or (not any_note and mark[1] != note):
raise SystemExit(
f"preset at {base} is {mark.hex()}, not the note-{note} pads; nothing was written"
)
bases = (RAM, 0)
shown = set()
for name, address, rgb in colour_writes(clear, bank, colours):
for base in bases:
transact(midiout, midiin, write_request(base + address, rgb))
if name in shown:
continue
check = payload_data(transact(midiout, midiin, read_request(address, 3)))
if check != rgb:
raise SystemExit(f"{name or 'pad'} read back {check.hex()}, expected {rgb.hex()}")
shown.add(name)
if name:
print(f" {name:<8} {address:#06x} {rgb.hex()}", flush=True)
reply = transact(midiout, midiin, save_request())
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
raise SystemExit(f"the pad did not accept the save ({reply.hex()})")
print("Saved on the pad.", flush=True)
finally:
for port in (midiout, midiin):
port.close_port()
port.delete()
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--bank", type=int, default=1, help="pad bank to write (2 is notes 52–67)")
parser.add_argument("--page", type=int, help="write preset page 0–7 instead (page 2 is bank 1, 3 is bank 2; 7 repeats 52–67)")
parser.add_argument("--xchc", action="store_true", help="use the solid colour scenes from shows/xchc.qxw")
parser.add_argument("--colour-set", action="store_true", help="use the 16 colours from shows/test.qxw")
parser.add_argument("--clear", action="store_true", help="store black on every scene pad")
parser.add_argument("--identify", action="store_true", help="light each pad page in its own colour")
parser.add_argument("--dry-run", action="store_true", help="print the colours and do not open a port")
args = parser.parse_args(argv)
if args.page is not None:
if not 2 <= args.page < preset.PAGE_COUNT:
parser.error("--page must be 2–7")
args.bank = args.page - 1
if args.identify:
for page, (name, red, green, blue) in enumerate(PAGE_COLOURS, 1):
print(f"page {page} {name:<7} {bytes((scale(red), scale(green), scale(blue))).hex()}")
if not args.dry_run:
try:
written = save_image(identify_image(read_image()))
except PadError as exc:
raise SystemExit(str(exc)) from exc
print(f"Saved on the pad ({written} bytes changed).")
return 0
palette = xchc_colours(args.clear) if args.xchc else colour_set(args.clear) if args.colour_set else None
if args.dry_run:
seen = set()
for name, address, rgb in colour_writes(args.clear, args.bank, palette):
if not name or name in seen:
continue
seen.add(name)
print(f"{name:<8} {address:#06x} {rgb.hex()}")
return 0
apply(args.clear, args.bank, palette, any_note=args.page is not None)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Set the SMC-PAD lamps: bank 1 off, bank 2 in the colours of shows/test.qxw.
.venv/bin/python scripts/pad/pad_lamps.py
Needs the USB Private port. padcontroller.midi does this on start; run this
when the pad is read by Chataigne instead.
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def set_lamps() -> None:
"""Bank 1 lamps off, bank 2 lamps from shows/test.qxw. Needs the USB Private port."""
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
import pad_colours
try:
pad_colours.apply(True, bank=1)
pad_colours.apply(False, bank=2, colours=pad_colours.colour_set())
except (SystemExit, Exception) as exc: # the Bluetooth link has no Private port
print(f"Lamps not set: {exc}", flush=True)
if __name__ == "__main__":
set_lamps()
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""Build shows/midi.qxw — M-VAVE SMC-PAD controlling 20× BCC145 (Dim + RGBW)."""
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "shows" / "midi.qxw"
PROFILE_SRC = ROOT / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_DST = Path.home() / ".qlcplus" / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_NAME = "M-VAVE SMC-PAD"
MIDI_UNIVERSE_ID = 1 # Universe 2
OMNI_MIDICHANNEL = 16 # pads ch10 + knobs ch1
PAD_MIDI_CH = 9
# 20× BCC145, 8ch mode, physical/UI start channel 88
# QLC XML Address is 0-based: Address 87 → DMX/UI channel 88 (same as xchc.qxw).
BCC_COUNT = 20
BCC_START_ADDRESS = 87
BCC_CHANNELS = 8
UNIVERSE_CHANNELS = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS # 247
# 8ch map: 0 Dim, 1 Strobe, 2–5 RGBW, 6 Macro, 7 Speed
STROBE_CH, MACRO_CH, SPEED_CH = 1, 6, 7
# Knob bank 1 (CC 30–37): knobs 1–8 — master Dim/RGBW/Strobe/Macro/Speed
# Knob bank 2 (CC 38–44): knobs 9–15 — Dim boost for #9–#15 (HTP vs master)
KNOB_BANK1 = [
# (cc, caption, widget_id, dmx_ch, fg, cng, value, fixtures|None)
(32, "Dim", 0, 0, "4294967295", "None", 200, None),
(36, "R", 1, 2, "4294901760", "Red", 0, None),
(37, "G", 2, 3, "4278255360", "Green", 0, None),
(34, "B", 3, 4, "4278190335", "Blue", 0, None),
(35, "W", 4, 5, "4294967295", "None", 0, None),
(33, "Strobe", 5, STROBE_CH, "4294922844", "None", 0, None),
(30, "Macro", 6, MACRO_CH, "4288256409", "None", 0, None),
(31, "Speed", 7, SPEED_CH, "4286611584", "None", 0, None),
]
KNOB_BANK2 = [
# (cc, caption, widget_id, fixture_id)
(38, "F9", 20, 8),
(39, "F10", 21, 9),
(40, "F11", 22, 10),
(41, "F12", 23, 11),
(42, "F13", 24, 12),
(43, "F14", 25, 13),
(44, "F15", 26, 14),
]
# 4×4 pads → colour flashes / utility (scenes built below)
# note 36..51 with OMNI encoding
PAD_COLORS = [
# (name, r, g, b, w) — bottom row left→right, then up
("Red", 255, 0, 0, 0),
("Green", 0, 255, 0, 0),
("Blue", 0, 0, 255, 0),
("White", 0, 0, 0, 255),
("Yellow", 255, 255, 0, 0),
("Cyan", 0, 255, 255, 0),
("Magenta", 255, 0, 255, 0),
("Orange", 255, 80, 0, 0),
("Warm", 255, 120, 40, 80),
("Cool", 80, 120, 255, 40),
("Pink", 255, 40, 120, 0),
("Lime", 120, 255, 0, 0),
("Full", 255, 255, 255, 255),
("Half", 128, 128, 128, 128),
("Dim50", 0, 0, 0, 0), # blackout colour; dim stays
("Black", 0, 0, 0, 0),
]
def detect_midi_uid() -> str:
"""Prefer smoothed virtual port when the pad controller (padcontroller.midi) is running."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
out = ""
for name in (
"padcontroller",
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
):
if name in out:
return name
return "SMC-PAD Bluetooth"
ARTNET_OUTPUT_IP = "192.168.1.175"
# Device Art-Net universe (IceRay SwOut); keep in sync with the box
ARTNET_OUTPUT_UNI = "0"
ARTNET_LINE = "0"
def detect_artnet_uid() -> str:
"""Local IPv4 on the same /24 as the Art-Net node (prefer wlan/eth)."""
try:
out = subprocess.check_output(["ip", "-4", "-o", "addr", "show"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return "192.168.1.90"
prefix = ".".join(ARTNET_OUTPUT_IP.split(".")[:3]) + "."
candidates: list[str] = []
for line in out.splitlines():
# 2: wlo1 inet 192.168.1.90/24 ...
parts = line.split()
if len(parts) < 4 or parts[2] != "inet":
continue
ip = parts[3].split("/", 1)[0]
iface = parts[1]
if ip.startswith(prefix) and not iface.startswith(("lo", "vir", "docker", "br-", "mpq")):
candidates.append(ip)
return candidates[0] if candidates else "192.168.1.90"
def output_xml() -> str:
uid = detect_artnet_uid()
return f""" <Output Plugin="ArtNet" UID="{uid}" Line="{ARTNET_LINE}">
<PluginParameters outputIP="{ARTNET_OUTPUT_IP}" outputUni="{ARTNET_OUTPUT_UNI}" UniverseChannels="{UNIVERSE_CHANNELS}"/>
</Output>"""
def install_profile() -> None:
PROFILE_DST.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(PROFILE_SRC, PROFILE_DST)
def appearance(fg: str = "Default") -> str:
return f""" <Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def fixture_ids() -> range:
return range(BCC_COUNT)
def slider(
wid: int,
caption: str,
x: int,
y: int,
dmx_ch: int,
*,
fg: str,
cng: str,
value: int,
midi_cc: int | None,
fixtures: range | list[int] | None = None,
width: int = 60,
height: int = 280,
) -> str:
inp = ""
if midi_cc is not None:
inp = f'\n <Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_cc}"/>'
fids = list(fixture_ids() if fixtures is None else fixtures)
channels = "\n".join(
f' <Channel Fixture="{fid}">{dmx_ch}</Channel>' for fid in fids
)
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{width}" Height="{height}"/>
{appearance(fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{channels}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>{inp}
</Slider>"""
def scene_xml(fid: int, name: str, r: int, g: int, b: int, w: int) -> str:
# BCC145 8ch: Dim left to slider; force Strobe/Macro/Speed off; set RGBW.
vals = [
(STROBE_CH, 0),
(2, r),
(3, g),
(4, b),
(5, w),
(MACRO_CH, 0),
(SPEED_CH, 0),
]
fv = "\n".join(
f' <FixtureVal ID="{fx}" Channel="{ch}">{v}</FixtureVal>'
for fx in fixture_ids()
for ch, v in vals
)
return f""" <Function ID="{fid}" Type="Scene" Name="{name}">
<Bus Role="Fade">1</Bus>
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
{fv}
</Function>"""
def fixtures_xml() -> str:
blocks = []
for i in fixture_ids():
addr = BCC_START_ADDRESS + i * BCC_CHANNELS
blocks.append(
f""" <Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>{i}</ID>
<Name>BCC145 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>{BCC_CHANNELS}</Channels>
</Fixture>"""
)
return "\n".join(blocks)
def button_xml(wid: int, caption: str, x: int, y: int, func_id: int, midi_ch: int, bg: str) -> str:
return f""" <Button Caption="{caption}" ID="{wid}" Icon="">
<WindowState Visible="True" X="{x}" Y="{y}" Width="70" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="{func_id}"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
<Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_ch}"/>
</Button>"""
def bg_color(r: int, g: int, b: int) -> str:
# QLC packed ARGB as decimal
return str((0xFF << 24) | (r << 16) | (g << 8) | b)
def build(uid: str) -> str:
functions = []
buttons = []
for i, (name, r, g, b, w) in enumerate(PAD_COLORS):
fid = 10 + i
note = 36 + i
midi_ch = (PAD_MIDI_CH << 12) | (128 + note)
functions.append(scene_xml(fid, name, r, g, b, w))
row, col = divmod(i, 4)
# pad grid: bottom row is notes 36-39 → visual row 3
vx = 20 + col * 80
vy = 20 + (3 - row) * 66
buttons.append(
button_xml(10 + i, name, vx, vy, fid, midi_ch, bg_color(r, g, b))
)
sliders = []
for i, (cc, cap, wid, dmx, fg, cng, val, fxs) in enumerate(KNOB_BANK1):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
20,
dmx,
fg=fg,
cng=cng,
value=val,
midi_cc=cc,
fixtures=fxs,
)
)
for i, (cc, cap, wid, fx) in enumerate(KNOB_BANK2):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
310,
0, # Dim
fg="4294967295",
cng="None",
value=200,
midi_cc=cc,
fixtures=[fx],
height=120,
)
)
vc_widgets = "\n".join(buttons + sliders)
funcs = "\n".join(functions)
fixtures = fixtures_xml()
dmx_out = output_xml()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
{dmx_out}
</Universe>
<Universe Name="Universe 2" ID="1">
<Input Plugin="MIDI" UID="{uid}" Line="0" Profile="{PROFILE_NAME}">
<PluginParameters midichannel="{OMNI_MIDICHANNEL}"/>
</Input>
</Universe>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixtures}
{funcs}
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
{vc_widgets}
</Frame>
<Properties>
<Size Width="900" Height="460"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
"""
def patch_qsettings(uid: str) -> None:
conf = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf"
if not conf.exists():
return
text = conf.read_text()
key = uid.replace(" ", "%20")
pattern = rf"(Input\\{re.escape(key)}\\midichannel=)\d+"
if re.search(pattern, text):
text = re.sub(pattern, rf"\g<1>{OMNI_MIDICHANNEL}", text)
elif "[midiplugin]" in text and f"Input\\{key}\\midichannel=" not in text:
text = text.replace(
"[midiplugin]\n",
f"[midiplugin]\nInput\\{key}\\midichannel={OMNI_MIDICHANNEL}\n"
f"Input\\{key}\\mode=Control Change\n"
f"Input\\{key}\\initmessage=\n",
1,
)
conf.write_text(text)
def main() -> None:
uid = detect_midi_uid()
install_profile()
patch_qsettings(uid)
OUT.write_text(build(uid))
ui_start = BCC_START_ADDRESS + 1
ui_last = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS
print(f"Wrote {OUT}")
print(f" MIDI: {uid} OMNI on Universe 2")
print(
f" Art-Net → {ARTNET_OUTPUT_IP} uni {ARTNET_OUTPUT_UNI} "
f"(local {detect_artnet_uid()})"
)
print(
f" {BCC_COUNT}× BCC145 8ch @ UI {ui_start}–{ui_last} "
f"(XML Address {BCC_START_ADDRESS}–{BCC_START_ADDRESS + (BCC_COUNT - 1) * BCC_CHANNELS})"
)
print(" Bank1 knobs 1–8: Dim/RGBW/Strobe/Macro/Speed (all)")
print(" Bank2 knobs 9–15: Dim for #9–#15")
print(" 16 pads → colour scenes (all fixtures; strobe/macro forced off)")
if __name__ == "__main__":
main()
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Reliable MIDI bring-up for shows/midi.qxw
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) pad controller (creates "padcontroller")
# 3) patch workspace to that port
# 4) open QLC+ last
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
PYTHON="${ROOT}/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON=python3
pad_present() {
aconnect -l 2>/dev/null | grep -Eq "SMC-PAD Bluetooth|SINCO|SMC-PAD"
}
echo "Waiting for SMC-PAD (Bluetooth or USB)…"
for _ in $(seq 1 30); do
if pad_present; then
break
fi
sleep 1
done
if ! pad_present; then
echo "No SMC-PAD in aconnect -l. Pair/connect the pad, then re-run." >&2
aconnect -l >&2 || true
exit 1
fi
# Restart the pad controller so it re-opens the pad port cleanly. Use the systemd
# user service when it is installed (padcontroller/systemd/install.sh).
SERVICE=padcontroller.service
LOG=/tmp/padcontroller.log
if systemctl --user is-enabled --quiet "$SERVICE" 2>/dev/null; then
systemctl --user restart "$SERVICE"
LOG=
else
# avoid pkill -f; it matches this script
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/python.* -m padcontroller[.]midi/ {print $1}')
sleep 0.4
nohup "$PYTHON" -m padcontroller.midi --tau 0.055 >>"$LOG" 2>&1 &
fi
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
break
fi
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
echo "The pad controller failed to create padcontroller." >&2
if [[ -n "$LOG" ]]; then
tail -20 "$LOG" >&2 || true
else
journalctl --user -u "$SERVICE" -n 20 --no-pager >&2 || true
fi
exit 1
fi
python3 scripts/pad/patch_smc_pad.py
kill "$(pgrep -x qlcplus)" 2>/dev/null || true
sleep 0.5
nohup qlcplus --open "$ROOT/shows/midi.qxw" >/tmp/qlcplus.log 2>&1 &
sleep 1.5
echo
echo "Chain (expect pad → padcontroller → qlcplus):"
aconnect -l | grep -E "SMC-PAD|SINCO|padcontroller|qlcplus" -A2 || aconnect -l
echo
echo "OK — twist a knob / hit a pad. If silent: re-run this script (don't pick Midi Through in IO)."
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# Launch Mover Pattern Studio (local web app) for the shows in this repo.
# scripts/pattern_studio.sh # opens http://127.0.0.1:8765 in your browser
# scripts/pattern_studio.sh --port 9000 --no-browser
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 -m patternstudio "$@"
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Add two sets of 16 colour scenes and their buttons to shows/test.show.json.
Colour 1 paints all 15 cans and colour 2 the four movers, so one colour
for each can be on at once. Each set is a solo frame and every scene
fades in and out over FADE_MS. Bank 2 (notes 52–67) picks colour 1.
Holding Play picks set B: the pad controller turns those notes into 68–83 while
Play is down. Bank 1 is kept for animations.
python3 scripts/shows/colour_sets.py && python3 -m showfile write shows/test.show.json -o shows/test.qxw
The sliders are Playback sliders over five scenes per set (Dim, R, G, B, W),
so they never override a channel. Knobs 1–5 move colour 1's sliders and knobs
6–10 colour 2's. Run the pad controller with --lock-knobs to make them work only
after the Custom pad is pressed; any other pad sends them back to zero (see
padcontroller/layer.py).
"""
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SPEC = ROOT / "shows" / "test.show.json"
FADE_MS = 1000
DIMMER, RED, GREEN, BLUE, WHITE = 0, 2, 3, 4, 5
PAD_BANK_2_FIRST_NOTE = 52
HELD_FIRST_NOTE = 68 # padcontroller/layer.py sends bank 2 here while Play is held
PROFILE = "M-VAVE SMC-PAD"
OMNI = 16 # QLC+ MIDI plugin channel that accepts every MIDI channel
PAD_MIDI_CH = 9 # the pads send notes on channel 10
KNOB_FIRST_CC = 30 # pad knob 1; colour 2's sliders follow colour 1's
PAD_PORT = "padcontroller" # padcontroller/midi.py; it applies the Play layer
# name, r, g, b, w. Bottom row first, four to a row. The cans have a white emitter, so the whites use it.
COLOURS = (
("Red", 255, 0, 0, 0),
("Orange", 255, 127, 0, 0),
("Yellow", 255, 255, 0, 0),
("Lime", 127, 255, 0, 0),
("Green", 0, 255, 0, 0),
("Spring", 0, 255, 127, 0),
("Cyan", 0, 255, 255, 0),
("Azure", 0, 127, 255, 0),
("Blue", 0, 0, 255, 0),
("Violet", 127, 0, 255, 0),
("Magenta", 255, 0, 255, 0),
("Pink", 255, 40, 120, 0),
("Warm", 255, 120, 40, 120),
("White", 0, 0, 0, 255),
("Cool", 80, 120, 255, 120),
)
# The top-right pad is the custom colour. Its button shows this swatch, but
# its scene is dark: the sliders next to it mix the colour from five scenes.
# Its pad lamp stays off.
CUSTOM = (("Custom", 255, 60, 0, 0),)
CANS = [f"#{n}" for n in range(1, 16)]
MOVERS = ["M1", "M2", "M3", "M4"]
# Mover channels: 8 is centre brightness, 9 centre strobe, then seven R G B W groups from 10.
MOVER_BRIGHTNESS, MOVER_STROBE, MOVER_GROUPS, MOVER_FIRST_COLOUR = 8, 9, 7, 10
def swatch(r: int, g: int, b: int, w: int) -> list[int]:
return [min(255, r + w), min(255, g + w), min(255, b + w)]
# Mixer beside each grid: caption, can channel, offset in a mover colour group (None is brightness).
SLIDERS = (
("Dim", DIMMER, None, [255, 255, 255]),
("R", RED, 0, [255, 0, 0]),
("G", GREEN, 1, [0, 255, 0]),
("B", BLUE, 2, [0, 0, 255]),
("W", WHITE, 3, [255, 255, 255]),
)
def component(cans: list[str], movers: list[str], can_channel: int, offset: int | None) -> dict:
"""One channel kind of this set at full, for a Playback slider to scale."""
values = {can: {can_channel: 255} for can in cans}
for mover in movers:
if offset is None:
values[mover] = {MOVER_BRIGHTNESS: 255}
else:
values[mover] = {MOVER_FIRST_COLOUR + group * 4 + offset: 255 for group in range(MOVER_GROUPS)}
return values
def custom_off(cans: list[str], movers: list[str]) -> dict:
"""The Custom pad's own scene: dark, so the sliders' scenes set the colour."""
values = {can: {DIMMER: 0} for can in cans}
values.update({mover: {MOVER_BRIGHTNESS: 0} for mover in movers})
return values
def sliders(label: str, first_cc: int) -> list[dict]:
"""Playback sliders. Each scales its own scene, so nothing is overridden."""
return [{
"type": "slider", "caption": caption, "function": f"custom_{label}_{caption}",
"x": 400 + index * 52, "y": 10, "w": 48, "h": 200, "fg": fg,
"input": {"universe": 1, "cc": [0, first_cc + index]},
} for index, (caption, _can, _offset, fg) in enumerate(SLIDERS)]
def main() -> None:
spec = json.loads(SPEC.read_text())
spec["universes"][1]["input"] = {"plugin": "MIDI", "uid": PAD_PORT, "profile": PROFILE, "channel": OMNI, "line": 0}
functions, frames = [], []
for si, (label, cans, movers) in enumerate((("1", CANS, []), ("2", [], MOVERS))):
buttons = []
for i, (name, r, g, b, w) in enumerate(COLOURS + CUSTOM):
key = f"colour_{label}_{i + 1}"
on = 255
values = {can: {DIMMER: on, RED: r, GREEN: g, BLUE: b, WHITE: w} for can in cans}
for mover in movers:
values[mover] = {MOVER_BRIGHTNESS: on, MOVER_STROBE: 0}
for group in range(MOVER_GROUPS):
first = MOVER_FIRST_COLOUR + group * 4
values[mover].update({first: r, first + 1: g, first + 2: b, first + 3: w})
if name == CUSTOM[0][0]:
values = custom_off(cans, movers)
functions.append({
"key": key, "type": "scene", "name": f"{label} {name}",
"fade_in": FADE_MS, "fade_out": FADE_MS, "values": values,
})
sw = swatch(r, g, b, w)
dark = sum(sw) > 380
button = {
"type": "button", "caption": name, "function": key,
# 4 wide like the pads: the first four colours are the bottom row.
"x": 10 + (i % 4) * 96, "y": 10 + (3 - i // 4) * 66, "w": 90, "h": 60,
"bg": sw,
"fg": [0, 0, 0] if dark else [255, 255, 255],
}
button["input"] = {"universe": 1, "note": [PAD_MIDI_CH, (HELD_FIRST_NOTE if si else PAD_BANK_2_FIRST_NOTE) + i]}
buttons.append(button)
for caption, can_channel, offset, _fg in SLIDERS:
functions.append({
"key": f"custom_{label}_{caption}", "type": "scene", "name": f"{label} Custom {caption}",
"values": component(cans, movers, can_channel, offset),
})
frames.append({
"type": "solo", "caption": f"Colour {label}", "x": 10, "y": 10 + si * 310,
"w": 400 + len(SLIDERS) * 52, "h": 300, "children": buttons + sliders(label, KNOB_FIRST_CC + si * len(SLIDERS)),
})
spec["functions"] = functions
spec["vc"] = frames
SPEC.write_text(json.dumps(spec, indent=2) + "\n")
if __name__ == "__main__":
main()
@@ -5,9 +5,9 @@ Traces QLC+'s Eight path (pan = -sin(2t), tilt = cos(t)), rides focus
with throw so the spot stays a similar size, and walks hue around the loop.
The whole 8 slowly drifts in a circle so it does not sit in one place.
python3 scripts/figure8_small_eye.py
python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/figure8_small_eye.py --merge-xchc shows/xchc.qxw
python3 scripts/shows/figure8_small_eye.py
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/shows/figure8_small_eye.py --merge-xchc shows/xchc.qxw
Stop QLC+ output before live mode so the two sources do not fight.
Quit live mode with Ctrl+C (sends blackout).
@@ -22,7 +22,7 @@ import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from test_small_eye import (
@@ -182,7 +182,7 @@ def monitor_xml() -> str:
def main():
path = Path(__file__).resolve().parents[1] / "shows" / "xchc.qxw"
path = Path(__file__).resolve().parents[2] / "shows" / "xchc.qxw"
text = path.read_text()
for i, (name, rgb) in enumerate(COLORS.items()):
@@ -9,7 +9,7 @@ import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "shows" / "cabaret.qxw"
ARTNET_NODE_FALLBACK = "192.168.1.227"
ARTNET_PORT = 6454
+325
View File
@@ -0,0 +1,325 @@
#!/usr/bin/env python3
"""Write a Chataigne project from a show spec.
python3 scripts/shows/make_chataigne.py shows/test.show.json chataigne/test
Writes <out>/<name>.noisette and <out>/<name>.js. The script holds the scenes and
the pad and slider mapping, and sends DMX through the project's DMX module, named Lights, and a copy to Preview. Solo
frames and scene fades follow what QLC+ does with the same spec.
"""
from __future__ import annotations
import argparse
import json
import struct
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
TEMPLATE = ROOT / "chataigne" / "show.template.js"
def absolute_levels(show: dict, stage: dict, values: dict[str, dict[str, int]]) -> dict[int, int]:
"""Map a scene's fixture channels to 1-based DMX channels in the output universe."""
levels: dict[int, int] = {}
for key, channels in values.items():
fixture = stage["fixtures"][key]
for offset, level in channels.items():
levels[int(fixture["address"]) + int(offset) + 1] = int(level)
return levels
SCALE = 1.25
MARGIN = 10
BUTTON = 28
def clear_png() -> bytes:
"""A 4x4 fully transparent PNG, for a trigger that should show what is behind it."""
def chunk(kind: bytes, data: bytes) -> bytes:
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
rows = b"".join(b"\x00" + b"\x00" * 16 for _ in range(4))
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows))
+ chunk(b"IEND", b"")
)
def script_path(name: str) -> str:
"""Chataigne names the script after its file and the module after its title."""
return f"/modules/pad/scripts/{name}/params/"
def ident(prefix: str, number: int, name: str) -> str:
"""A control name Chataigne keeps as written: letters and digits, lower-case first."""
return f"{prefix}{number}" + "".join(c for c in name if c.isalnum())
def collect(show: dict, stage: dict) -> dict:
functions = {f["key"]: f for f in show["functions"]}
groups: dict[str, dict] = {}
for number, frame in enumerate(show["vc"], 1):
pads, sliders = [], []
for widget in frame.get("children", []):
kind = widget["type"]
function = functions[widget["function"]]
binding = widget.get("input") or {}
levels = absolute_levels(show, stage, function["values"])
if kind == "button" and "note" in binding:
pads.append({
"id": ident("c", number, widget["caption"]),
"box": box(frame, widget),
"bg": widget.get("bg", [60, 60, 60]),
"fg": widget.get("fg", [255, 255, 255]),
"note": binding["note"][1],
"name": widget["caption"],
"fade": [function.get("fade_in") or 0, function.get("fade_out") or 0],
"levels": levels,
})
elif kind == "slider" and "cc" in binding:
sliders.append({
"id": ident("s", number, widget["caption"]),
"box": box(frame, widget),
"fg": widget.get("fg", [255, 255, 255]),
"cc": binding["cc"][1],
"name": widget["caption"],
"levels": levels,
})
if pads or sliders:
groups[frame["caption"]] = {
"name": frame["caption"],
"now": f"now{number}",
"box": box(frame, {"x": 0, "y": -30, "w": frame["w"], "h": 26}),
"pads": pads,
"sliders": sliders,
}
return groups
def box(frame: dict, widget: dict) -> list[int]:
"""x, y, w, h of a widget on the dashboard. Frames sit side by side, as on the virtual console."""
return [round((frame["x"] + widget["x"]) * SCALE), round((frame["y"] + widget["y"]) * SCALE + 40),
round(widget["w"] * SCALE), round(widget["h"] * SCALE)]
def colour(rgb: list[int]) -> int:
"""A Chataigne colour value: ARGB as a signed 32-bit int."""
argb = (255 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]
return argb - (1 << 32) if argb >= 1 << 31 else argb
def js_levels(levels: dict[int, int]) -> str:
return "[" + ",".join(f"{ch},{level}" for ch, level in sorted(levels.items())) + "]"
def render_data(groups: dict) -> str:
lines = ["var GROUPS = ["]
for caption, group in groups.items():
lines.append(" {")
lines.append(f" name: {json.dumps(caption)},")
lines.append(f" now: {json.dumps(group['now'])},")
lines.append(" pads: [")
for pad in group["pads"]:
lines.append(
f" {{id: {json.dumps(pad['id'])}, rgb: {json.dumps([round(c / 255, 3) for c in pad['bg']])}, note: {pad['note']}, name: {json.dumps(pad['name'])}, "
f"fadeIn: {pad['fade'][0]}, fadeOut: {pad['fade'][1]}, levels: {js_levels(pad['levels'])}}},"
)
lines.append(" ],")
lines.append(" sliders: [")
for slider in group["sliders"]:
lines.append(
f" {{id: {json.dumps(slider['id'])}, cc: {slider['cc']}, name: {json.dumps(slider['name'])}, levels: {js_levels(slider['levels'])}}},"
)
lines.append(" ]")
lines.append(" },")
lines.append("];")
return "\n".join(lines)
def dashboard_item(index: int, kind: str, target: str, box: list[int], label: str, colours: dict[str, list[int]]) -> dict:
parameters = [
{"value": [float(box[0]), float(box[1])], "controlAddress": "/viewUIPosition"},
{"value": [float(box[2]), float(box[3])], "controlAddress": "/viewUISize"},
{"value": target, "controlAddress": "/target"},
{"value": label, "controlAddress": "/customText", "enabled": True},
]
for address, rgb in colours.items():
parameters.append({"value": colour(rgb), "controlAddress": address, "enabled": True})
return {
"parameters": parameters,
"niceName": f"Item {index}",
"type": kind,
"ghostAddress": target,
"controllable": target,
}
def dashboard(groups: dict, name: str, view: tuple[int, int], overlay: str | None) -> dict:
"""A dashboard with a tile and button per pad, a slider per knob, and what each group is showing."""
items = []
for group in groups.values():
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + group["now"],
group["box"], group["name"], {},
))
for pad in group["pads"]:
x, y, w, h = pad["box"]
# Triggers draw grey whatever colour they are given, but a colour control always paints.
# The tile carries the colour and name; the trigger on it is a transparent image that takes the press.
small = overlay is None
tile = dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + pad["id"] + "Lamp",
[x, y, w, h - BUTTON - 2 if small else h], pad["name"], {"/textColor": [255, 255, 255]},
)
tile["parameters"] += [
{"value": True, "controlAddress": "/readOnly"},
{"value": False, "controlAddress": "/showValue"},
]
items.append(tile)
press = dashboard_item(
len(items) + 1, "DashboardTriggerItem", script_path(name) + pad["id"],
[x, y + h - BUTTON, w, BUTTON] if small else [x, y, w, h], "Select" if small else "",
{"/backgroundColor": pad["bg"], "/textColor": pad["fg"]},
)
if overlay:
# A custom label that is a single space: with none, the trigger draws its own name.
press["parameters"][3].update({"value": " ", "enabled": True})
press["parameters"].append({"value": False, "controlAddress": "/showLabel"})
press["parameters"].append({"value": overlay, "controlAddress": "/customImage", "enabled": True})
items.append(press)
for slider in group["sliders"]:
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + slider["id"], slider["box"], slider["name"],
{"/foregroundColor": slider["fg"]},
))
# Dashboard coordinates start at the middle of the view, so move the board to its top left.
left = min(i["parameters"][0]["value"][0] for i in items)
top = min(i["parameters"][0]["value"][1] for i in items)
for i in items:
position = i["parameters"][0]["value"]
position[0] += MARGIN - view[0] / 2 - left
position[1] += MARGIN - view[1] / 2 - top
return {
"parameters": [{"value": False, "controlAddress": "/editMode"}],
"items": [
{
"niceName": "Board",
"type": "BaseItem",
"itemManager": {
# The web page puts the middle of the canvas at 0, 0, so the canvas has to be the view's size
# for the board to start at its top left.
"parameters": [{"value": [float(view[0]), float(view[1])], "controlAddress": "/canvasSize", "enabled": True}],
"items": items,
"viewOffset": [0, 0],
"viewZoom": 1.0,
},
}
],
"viewOffset": [0, 0],
"viewZoom": 1.0,
}
def dmx_module(name: str, host: str, universe: int, interface: str | None) -> dict:
device: dict = {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}}
if interface:
device["parameters"] = [{"value": interface, "controlAddress": "/networkInterface"}]
return {
"niceName": name,
"type": "DMX",
"params": {
"parameters": [
{"value": "Art-Net", "controlAddress": "/dmxType"},
{"value": 40, "controlAddress": "/sendRate"},
],
"containers": {
"artNet": {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}},
"outputUniverses": {
"items": [
{
"niceName": "Universe",
"parameters": [
{"value": 0, "controlAddress": "/net"},
{"value": 0, "controlAddress": "/subnet"},
{"value": universe, "controlAddress": "/universe"},
],
}
]
}
},
},
"device": device,
}
def project(
script: str, host: str, universe: int, interface: str, groups: dict, preview: str | None, pad: str, view: tuple[int, int], overlay: str | None
) -> dict:
"""A Chataigne project: a DMX module on Art-Net and a MIDI module that runs the show script."""
dmx = [dmx_module("Lights", host, universe, interface)]
if preview:
dmx.append(dmx_module("Preview", preview, universe, None))
midi = {
"niceName": "Pad",
"type": "MIDI",
"params": {"parameters": [{"value": [pad, ""], "inputName": pad, "controlAddress": "/devices"}]},
"scripts": {
"items": [{"niceName": "Show", "parameters": [{"value": script, "controlAddress": "/filePath"}]}]
},
}
return {
"metaData": {"version": "1.10.4"},
"projectSettings": {
"containers": {
"dashboardSettings": {
"parameters": [
{"value": True, "controlAddress": "/enableDashboardServer"},
{"value": 9999, "hexMode": False, "controlAddress": "/serverPort"},
]
}
}
},
"dashboardManager": dashboard(groups, Path(script).stem, view, overlay),
"modules": {"viewOffset": [0, 0], "viewZoom": 1.0, "items": [*dmx, midi]},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("show", type=Path)
parser.add_argument("out", type=Path, help="directory to write into")
parser.add_argument("--host", help="Art-Net destination (default: from the show's output universe)")
parser.add_argument("--pad", default="SINCO SMC-PAD-Master", help="MIDI input the pad arrives on (Bluetooth: SMC-PAD Bluetooth)")
parser.add_argument("--view", default="1574x953", help="dashboard panel size in pixels, for the top-left placement")
parser.add_argument("--small-buttons", action="store_true", help="a grey Select button under each tile, instead of the whole tile pressing")
parser.add_argument("--preview", default="127.0.0.1", help="second Art-Net destination for the simulator; empty for none")
args = parser.parse_args()
show = json.loads(args.show.read_text())
stage = json.loads((ROOT / show["stage"]).read_text())
output = next(u["output"] for u in show["universes"] if u.get("output", {}).get("plugin") == "ArtNet")
name = args.show.name.removesuffix(".show.json")
groups = collect(show, stage)
source = TEMPLATE.read_text().replace("/*__DATA__*/", render_data(groups))
args.out.mkdir(parents=True, exist_ok=True)
(args.out / f"{name}.js").write_text(source)
overlay = None if args.small_buttons else str((args.out / "clear.png").resolve())
if overlay:
(args.out / "clear.png").write_bytes(clear_png())
doc = project(f"{name}.js", args.host or output["ip"], int(output["universe"]), output["uid"], groups, args.preview or None, args.pad, tuple(int(n) for n in args.view.split("x")), overlay)
(args.out / f"{name}.noisette").write_text(json.dumps(doc, indent=2) + "\n")
print(f"{args.out / (name + '.noisette')}: {len(groups)} groups, {sum(len(g['pads']) for g in groups.values())} pads")
if __name__ == "__main__":
main()
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Compile shows/simple.show.json into shows/simple.qxw."""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile.tools import write_show
def main() -> None:
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
result = write_show(spec, "shows/simple.qxw", root=ROOT)
if not result["ok"]:
raise SystemExit(json.dumps(result, indent=2))
print(f"Wrote {result['path']} ({len(result['widgets'])} widgets)")
if __name__ == "__main__":
main()
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Add mover versions of the bank 1 pads to shows/test.qxw, on notes 84–99.
Pause on the pad toggles bank 1 between the cans and the movers: padcontroller
sends bank 1 (notes 36–51) as 84–99 while it is on (padcontroller/layer.py).
Each mover pad sits on its can pad's note plus 48:
92 Strobe flash the movers' centre strobe
96 Chase a stripe through the 7 rings of all four movers
97 Reverse the same, the other way
98 Zigzag mover by mover, M3, M1, M2, M4 (back, front, front, back)
99 Opposing rings outwards on the left movers, inwards on the right
The chases take their colour from the Colour 1 (cans) pads, as the cans'
chases take theirs from Colour 2, so they stand out. Knob 15 (CC 44), the
movers' level, is also their peak. The movers are not sound reactive: Sound and
Threshold (84 and 85) do nothing on their layer.
python3 scripts/shows/mover_bank.py
Run it once on a show without them; it stops if they are already there.
QLC+ has to reopen the show to see them.
"""
from __future__ import annotations
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SHOW = ROOT / "shows" / "test.qxw"
MOVERS_SHIFT = 48 # padcontroller/layer.py
NOTE_BASE = 36992 # QLC+ input channel of a channel-10 note: this plus the note
LEVEL_CC = 44 # knob 15: the Movers level slider, and the movers' peak here
# Fixture IDs left to right on stage: M3 back left, M1 and M2 front, M4 back right.
M1, M2, M3, M4 = 8, 9, 17, 18
LEFT_TO_RIGHT = (M3, M1, M2, M4)
RINGS = 7
BRIGHTNESS, STROBE = 8, 9
GROUP_RINGS, GROUP_ZIGZAG, GROUP_OPPOSING = 5, 6, 7
F_DIMMER, F_FWD, F_HOLD, F_REV, F_ZIG, F_ZIG_HOLD, F_OPP, F_STROBE = range(57, 65)
NO_FUNCTION = 4294967295
def note(can_note: int) -> int:
return NOTE_BASE + can_note + MOVERS_SHIFT
def group(gid: int, name: str, w: int, h: int, heads: list[tuple[int, int, int, int]]) -> str:
rows = "\n".join(f' <Head X="{x}" Y="{y}" Fixture="{f}">{head}</Head>' for x, y, f, head in heads)
return f' <FixtureGroup ID="{gid}">\n <Name>{name}</Name>\n <Size X="{w}" Y="{h}"/>\n{rows}\n </FixtureGroup>\n'
def groups() -> str:
# Rings down Y, one mover per column.
rings = [(x, r, f, r) for x, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
# One mover per row, its rings across.
zigzag = [(r, y, f, r) for y, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
# Left movers' rings run outwards as the right movers' run inwards.
opposing = [(x, y, f, y if x < 2 else RINGS - 1 - y) for x, f in enumerate(LEFT_TO_RIGHT) for y in range(RINGS)]
return (group(GROUP_RINGS, "Movers rings", 4, RINGS, rings)
+ group(GROUP_ZIGZAG, "Movers zigzag", RINGS, 4, zigzag)
+ group(GROUP_OPPOSING, "Movers opposing", 4, RINGS, opposing))
def scene(fid: int, name: str, values: dict[int, int], fade_out: int = 0) -> str:
vals = ",".join(f"{c},{v}" for c, v in values.items())
rows = "\n".join(f' <FixtureVal ID="{f}">{vals}</FixtureVal>' for f in LEFT_TO_RIGHT)
return (f' <Function ID="{fid}" Type="Scene" Name="{name}">\n'
f' <Speed FadeIn="0" FadeOut="{fade_out}" Duration="0"/>\n{rows}\n </Function>\n')
def matrix(fid: int, name: str, gid: int, direction: str, step_ms: int) -> str:
return f""" <Function ID="{fid}" Type="RGBMatrix" Name="{name}">
<Speed FadeIn="0" FadeOut="500" Duration="{step_ms}"/>
<Direction>{direction}</Direction>
<RunOrder>SingleShot</RunOrder>
<Algorithm Type="Script">Stripes</Algorithm>
<MonoColor>4294967040</MonoColor>
<ControlMode>RGB</ControlMode>
<FixtureGroup>{gid}</FixtureGroup>
<Property Name="orientation" Value="Vertical"/>
</Function>
"""
def chaser(fid: int, name: str, ms: int, step: int) -> str:
return f""" <Function ID="{fid}" Type="Chaser" Name="{name}">
<Speed FadeIn="0" FadeOut="0" Duration="{ms}"/>
<Direction>Forward</Direction>
<RunOrder>SingleShot</RunOrder>
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
<Step Number="0" FadeIn="0" Hold="0" FadeOut="0">{step}</Step>
</Function>
"""
def functions() -> str:
# Each hold keeps the movers up while its run steps through, plus the run's fade.
return (scene(F_DIMMER, "Movers dimmer", {BRIGHTNESS: 255, STROBE: 0})
+ matrix(F_FWD, "Movers chase forward run", GROUP_RINGS, "Forward", 200)
+ chaser(F_HOLD, "Movers dimmer hold", RINGS * 200 + 500, F_DIMMER)
+ matrix(F_REV, "Movers chase reverse run", GROUP_RINGS, "Backward", 200)
+ matrix(F_ZIG, "Movers zigzag run", GROUP_ZIGZAG, "Forward", 200)
+ chaser(F_ZIG_HOLD, "Movers zigzag hold", 4 * 200 + 500, F_DIMMER)
+ matrix(F_OPP, "Movers opposing run", GROUP_OPPOSING, "Forward", 200)
+ scene(F_STROBE, "Movers strobe", {BRIGHTNESS: 255, STROBE: 230}, fade_out=50))
def appearance(indent: str, style: str = "None") -> str:
return (f"{indent}<Appearance>\n{indent} <FrameStyle>{style}</FrameStyle>\n"
f"{indent} <ForegroundColor>Default</ForegroundColor>\n{indent} <BackgroundColor>Default</BackgroundColor>\n"
f"{indent} <BackgroundImage>None</BackgroundImage>\n{indent} <Font>Default</Font>\n{indent}</Appearance>\n")
def button(wid: int, caption: str, x: int, y: int, size: int, function: int, channel: int | None,
action: str = "Toggle", indent: str = " ") -> str:
inp = f'{indent} <Input Universe="1" Channel="{channel}"/>\n' if channel is not None else ""
return (f'{indent}<Button Caption="{caption}" ID="{wid}" Icon="">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{size}" Height="{size}"/>\n'
+ appearance(indent + " ")
+ f'{indent} <Function ID="{function}"/>\n{indent} <Action>{action}</Action>\n'
f'{indent} <Intensity Adjust="False">100</Intensity>\n{inp}{indent}</Button>\n')
def submaster(wid: int, caption: str, x: int, y: int, h: int, cc: int, indent: str) -> str:
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="52" Height="{h}"/>\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None">Submaster</SliderMode>\n'
f'{indent} <Level LowLimit="0" HighLimit="255" Value="255"/>\n'
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
def frame(wid: int, caption: str, x: int, y: int, w: int, h: int, body: str, indent: str = " ",
header: bool = True, collapsed: bool = False) -> str:
return (f'{indent}<Frame Caption="{caption}" ID="{wid}">\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>\n'
f'{indent} <AllowChildren>True</AllowChildren>\n{indent} <AllowResize>True</AllowResize>\n'
f'{indent} <ShowHeader>{header}</ShowHeader>\n{indent} <ShowEnableButton>False</ShowEnableButton>\n'
f'{indent} <Collapsed>{collapsed}</Collapsed>\n{indent} <Disabled>False</Disabled>\n'
f'{body}{indent}</Frame>\n')
def vc(xml: str, next_id: int) -> str:
"""The new widgets."""
ids = iter(range(next_id, next_id + 100))
w = {name: next(ids) for name in (
"bank", "fwd", "rev", "zig", "opp", "strobe", "peak",
"runs", "fwd_run", "rev_run", "zig_run", "opp_run",
"colours", "fwd_col", "rev_col", "zig_col", "opp_col")}
bank = (button(w["fwd"], "Chase", 10, 10, 90, F_HOLD, note(48))
+ button(w["rev"], "Chase reverse", 100, 10, 90, F_HOLD, note(49))
+ button(w["zig"], "Zigzag", 190, 10, 90, F_ZIG_HOLD, note(50))
+ button(w["opp"], "Opposing", 280, 10, 90, F_HOLD, note(51))
+ button(w["strobe"], "Strobe", 10, 100, 90, F_STROBE, note(44), action="Flash")
+ submaster(w["peak"], "Peak", 378, 10, 360, LEVEL_CC, " "))
runs = (button(w["fwd_run"], "Chase run", 10, 10, 70, F_FWD, note(48))
+ button(w["rev_run"], "Reverse run", 80, 10, 70, F_REV, note(49))
+ button(w["zig_run"], "Zigzag run", 150, 10, 70, F_ZIG, note(50))
+ button(w["opp_run"], "Opposing run", 220, 10, 70, F_OPP, note(51)))
# The cans' Forward colour matrix follows the Colour 2 pads; these follow Colour 1, 16 notes lower.
template = re.search(r' <Matrix Caption="Forward colour" ID="61">.*? </Matrix>\n', xml, re.S).group(0)
def colour_matrix(wid: int, caption: str, fid: int, x: int, y: int) -> str:
m = template.replace('Caption="Forward colour" ID="61"', f'Caption="{caption}" ID="{wid}"')
m = m.replace('<Function ID="43" InstantApply', f'<Function ID="{fid}" InstantApply')
m = re.sub(r'X="\d+" Y="\d+" Width', f'X="{x}" Y="{y}" Width', m, count=1)
return re.sub(r'Channel="(\d+)"', lambda c: f'Channel="{int(c.group(1)) - 16}"', m)
colours = (colour_matrix(w["fwd_col"], "Movers chase colour", F_FWD, 10, 45)
+ colour_matrix(w["rev_col"], "Movers reverse colour", F_REV, 320, 45)
+ colour_matrix(w["zig_col"], "Movers zigzag colour", F_ZIG, 10, 275)
+ colour_matrix(w["opp_col"], "Movers opposing colour", F_OPP, 320, 275))
return (frame(w["bank"], "Movers pads", 1740, 5, 440, 380, bank, header=False)
+ frame(w["runs"], "Movers chase runs", 1740, 400, 310, 120, runs)
+ frame(w["colours"], "Movers chase colours", 1740, 530, 640, 510, colours, collapsed=True))
def main() -> None:
xml = SHOW.read_text()
if "Movers chase forward run" in xml:
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover pads")
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
if int(i) != NO_FUNCTION) + 1
widgets = vc(xml, next_id)
# The strobe flash is HTP so it beats the colour scenes' centre strobe of 0, as on the cans.
for fid in LEFT_TO_RIGHT:
xml = re.sub(rf"( <ID>{fid}</ID>\n(?: .*\n)*? <Channels>43</Channels>\n)",
rf"\1 <ForcedHTP>{STROBE}</ForcedHTP>\n", xml, count=1)
xml = xml.replace(' <Function ID="0" Type="Scene"', groups() + ' <Function ID="0" Type="Scene"', 1)
xml = xml.replace(" </Engine>", functions() + " </Engine>", 1)
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
xml = xml.replace('<Size Width="1880" Height="950"/>', '<Size Width="2400" Height="1050"/>', 1)
SHOW.write_text(xml)
print(f"Added the mover pads to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
if __name__ == "__main__":
main()
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Add Pan, Tilt, Focus and Rotate sliders for the movers to shows/test.qxw.
As in templeoftechno.qxw, knobs 9–12 (CC 38–41) drive all four movers at once:
Knob 9 CC 38 Pan channel 0
Knob 10 CC 39 Tilt channel 2
Knob 11 CC 40 Focus channel 7
Knob 12 CC 41 Rotate channel 5 (Lens Rotate)
They sit in a Movers position frame beside Sound peak, below the cans' chase runs.
python3 scripts/shows/mover_position.py
Run it once on a show without them; it stops if they are already there.
QLC+ has to reopen the show to see them.
"""
from __future__ import annotations
import re
from pathlib import Path
from mover_bank import LEFT_TO_RIGHT, NO_FUNCTION, ROOT, appearance, frame
SHOW = ROOT / "shows" / "test.qxw"
# Caption, CC, mover channel, starting value: temple techno's.
SLIDERS = (
("Pan", 38, 0, 0),
("Tilt", 39, 2, 0),
("Focus", 40, 7, 70),
("Rotate", 41, 5, 0),
)
def level(wid: int, caption: str, x: int, cc: int, channel: int, value: int, indent: str = " ") -> str:
rows = "".join(f'{indent} <Channel Fixture="{f}">{channel}</Channel>\n' for f in LEFT_TO_RIGHT)
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="10" Width="52" Height="200"/>\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="false">Level</SliderMode>\n'
f'{indent} <Level LowLimit="0" HighLimit="255" Value="{value}">\n{rows}{indent} </Level>\n'
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
def main() -> None:
xml = SHOW.read_text()
if 'Caption="Movers position"' in xml:
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover position sliders")
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
if int(i) != NO_FUNCTION) + 1
sliders = "".join(level(next_id + 1 + i, caption, 10 + 58 * i, cc, channel, value)
for i, (caption, cc, channel, value) in enumerate(SLIDERS))
widgets = frame(next_id, "Movers position", 420, 630, 10 + 58 * len(SLIDERS), 250, sliders)
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
SHOW.write_text(xml)
print(f"Added the mover position sliders to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
if __name__ == "__main__":
main()
@@ -33,7 +33,7 @@ def btn(
</Button>"""
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
def main():