Group scripts into pad/, shows/ and anim/ folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-22 11:54:36 +13:00
1 parent 5f593b973c
commit 647cfa3a75
26 files changed
+68 -66

No files matched your search

+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 padeditor.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())
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Print SMC-PAD pad and knob numbers.
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).
Type 1 on pad 1 to store pads 1–16, or 17 on pad 17 to store pads 17–32.
Type 1 on knob 1 to store knobs 1–8, or 9 on knob 9 to store knobs 9–16.
Mappings are saved to shows/midi_map.json.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import mido
ROOT = Path(__file__).resolve().parents[2]
MAP_PATH = ROOT / "shows" / "midi_map.json"
# (channel, note) -> pad number. Loaded from shows/midi_map.json.
PADS: dict[tuple[int, int], int] = {}
# (channel, controller) -> knob number.
KNOBS: dict[tuple[int, int], int] = {}
PAD_BANK = 16
KNOB_BANK = 8
def load_maps(path: Path = MAP_PATH) -> None:
PADS.clear()
KNOBS.clear()
if not path.is_file():
return
data = json.loads(path.read_text())
for item in data.get("pads", []):
PADS[(int(item["channel"]), int(item["note"]))] = int(item["pad"])
for item in data.get("knobs", []):
KNOBS[(int(item["channel"]), int(item["cc"]))] = int(item["knob"])
def save_maps(path: Path = MAP_PATH) -> None:
data = {
"pads": [
{"channel": channel, "note": note, "pad": pad}
for (channel, note), pad in sorted(PADS.items())
],
"knobs": [
{"channel": channel, "cc": cc, "knob": knob}
for (channel, cc), knob in sorted(KNOBS.items())
],
}
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n")
def ask(kind: str) -> int | None:
word = "pad" if kind == "note" else "knob"
raw = input(f"{word}: ").strip()
if raw == "":
return None
if not raw.isdigit():
print("enter a number", flush=True)
return None
return int(raw)
def assign_bank(kind: str, channel: int, number: int, name: int) -> tuple[int, int]:
"""Store one control, or a whole bank when name is the first in that bank."""
size = PAD_BANK if kind == "note" else KNOB_BANK
target = PADS if kind == "note" else KNOBS
if name % size != 1:
target[(channel, number)] = name
return name, name
for key, value in list(target.items()):
if name <= value < name + size:
del target[key]
for offset in range(size):
target[(channel, number + offset)] = name + offset
return name, name + size - 1
def remember(kind: str, channel: int, number: int, name: int) -> None:
first, last = assign_bank(kind, channel, number, name)
word = "pad" if kind == "note" else "knob"
if first == last:
print(f"{word} {first}", flush=True)
else:
print(f"{word}s {first}–{last}", flush=True)
save_maps()
print(f"saved {MAP_PATH}", flush=True)
def encoder_delta(value: int) -> int:
"""Relative encoder step. 1..63 clockwise, 65..127 counter-clockwise."""
if value <= 0 or value == 64 or value > 127:
return 0
if value < 64:
return value
return value - 128
def label(kind: str, channel: int, number: int, value: int | None = None) -> str | None:
if kind == "note":
pad = PADS.get((channel, number))
if pad is None:
return None
return f"pad {pad}"
knob = KNOBS.get((channel, number))
if knob is None:
return None
if value is None:
return f"knob {knob}"
delta = encoder_delta(value)
if delta == 0:
return None
return f"knob {knob} {delta:+d}"
def find_port(wanted: str | None) -> str:
names = mido.get_input_names()
if wanted:
for name in names:
if wanted in name:
return name
raise SystemExit(f"No MIDI input matching {wanted}. Ports: {', '.join(names) or 'none'}")
for name in names:
low = name.lower()
if "private" in low:
continue
if "smc-pad" in low or "sinco" in low:
return name
raise SystemExit("SMC-PAD not found. Plug it in, or pass part of the port name.")
def midi_hint(kind: str, channel: int, number: int, value: int) -> str:
if kind == "note":
return f"channel {channel} note {number} velocity {value}"
return f"channel {channel} cc {number} value {value}"
def listen(port: str) -> None:
skipped: set[tuple[str, int, int]] = set()
with mido.open_input(port) as incoming:
for msg in incoming:
if msg.type == "note_on" and msg.velocity > 0:
kind, number, value = "note", msg.note, msg.velocity
elif msg.type == "control_change":
kind, number, value = "cc", msg.control, msg.value
else:
continue
name = label(kind, msg.channel, number, value)
if name:
print(name, flush=True)
continue
if kind == "cc" and (msg.channel, number) in KNOBS:
continue
print(midi_hint(kind, msg.channel, number, value), flush=True)
key = (kind, msg.channel, number)
if key in skipped:
continue
try:
entered = ask(kind)
except EOFError:
return
if entered is None:
skipped.add(key)
continue
remember(kind, msg.channel, number, entered)
name = label(kind, msg.channel, number, value)
if name:
print(name, flush=True)
def main() -> int:
load_maps()
wanted = sys.argv[1] if len(sys.argv) > 1 else None
port = find_port(wanted)
print(f"Listening on {port}. Mappings in {MAP_PATH}.", flush=True)
print("Pad 1 stores pads 1–16. Pad 17 stores pads 17–32.", flush=True)
print("Knob 1 stores knobs 1–8. Knob 9 stores knobs 9–16.", flush=True)
print("Ctrl+C to stop.", flush=True)
try:
listen(port)
except KeyboardInterrupt:
return 0
return 0
if __name__ == "__main__":
raise SystemExit(main())
+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 padeditor import preset # noqa: E402
from padeditor.device import PadError, read_image, save_image, transact # noqa: E402
from padeditor.device import private_port as _private_port # noqa: E402
from padeditor.preset import scale # noqa: E402
from padeditor.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. smooth_smc_pad.py 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()
+64
View File
@@ -0,0 +1,64 @@
"""Hold Play to move the bank 2 pads up a layer.
The SMC-PAD sends CC 27 as 127 when Play goes down and 0 when it comes up.
While it is down, pad notes 52–67 go out as 68–83, so QLC+ can tell a
second set of buttons from the first. Play itself is not passed on.
With lock_knobs, knobs 1–5 (CC 30–34) drive colour 1's sliders and knobs 6–10
(CC 35–39) drive colour 2's, but only after the Custom pad (note 67, or 83
with Play held) has been pressed. Pressing any other bank 2 pad locks them
again, and its sliders are sent back to zero so their scenes stop.
Locked knob turns are dropped.
"""
from __future__ import annotations
PLAY_CC = 27
FIRST_NOTE = 52
LAST_NOTE = 67
SHIFT = 16
CUSTOM_NOTE = 67
KNOB_FIRST_CC = 30
KNOBS_PER_LAYER = 5
class PlayLayer:
def __init__(self, lock_knobs: bool = False) -> None:
self.lock_knobs = lock_knobs
self.unlocked: set[int] = set() # layers 0 and 1
self.held = False
# (channel, note as pressed) -> note sent, so a release matches its press
self.sent: dict[tuple[int, int], int] = {}
def handle(self, data: list[int]) -> list[list[int]]:
"""The messages to send on. Empty when the message is swallowed."""
status = data[0]
kind = status & 0xF0
channel = status & 0x0F
if kind == 0xB0 and len(data) >= 3 and data[1] == PLAY_CC:
self.held = data[2] > 0
return []
if kind == 0xB0 and len(data) >= 3 and self.lock_knobs:
index = data[1] - KNOB_FIRST_CC
if 0 <= index < 2 * KNOBS_PER_LAYER and index // KNOBS_PER_LAYER not in self.unlocked:
return []
if kind not in (0x80, 0x90) or len(data) < 3:
return [list(data)]
note = data[1]
key = (channel, note)
is_on = kind == 0x90 and data[2] > 0
extra: list[list[int]] = []
if is_on and FIRST_NOTE <= note <= LAST_NOTE:
layer = 1 if self.held else 0
if note == CUSTOM_NOTE:
self.unlocked.add(layer)
elif layer in self.unlocked:
self.unlocked.discard(layer)
first = KNOB_FIRST_CC + layer * KNOBS_PER_LAYER
extra = [[0xB0, first + n, 0] for n in range(KNOBS_PER_LAYER)]
if is_on:
out = note + SHIFT if self.held and FIRST_NOTE <= note <= LAST_NOTE else note
self.sent[key] = out
else:
out = self.sent.pop(key, note)
return [[status, out, *data[2:]], *extra]
+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 smoother daemon is running."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
out = ""
for name in (
"SMC-PAD Smooth",
"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()
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Smooth SMC-PAD knob CCs so RGBW fades feel less stepped.
Reads the physical pad (Bluetooth or USB), passes pad notes through
immediately, and eases Control Change values toward their targets at
~120 Hz before emitting on a virtual port named "SMC-PAD Smooth".
On start it also sets the pad lamps over USB (pad_colours.py): bank 1 off and
bank 2 in the colours from shows/test.qxw. On Bluetooth it says so and carries on.
While Play is held, bank 2 notes 52–67 go out as 68–83 (see pad_layer.py).
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the smoother is running).
Usage:
.venv/bin/python scripts/pad/smooth_smc_pad.py
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
sys.path.insert(0, str(Path(__file__).resolve().parent))
from pad_lamps import set_lamps # noqa: E402
from pad_layer import PlayLayer # noqa: E402
VIRTUAL_NAME = "SMC-PAD Smooth"
SOURCE_HINTS = (
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
"SMC-PAD",
)
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
for hint in SOURCE_HINTS:
for i, name in enumerate(ports):
if hint in name and VIRTUAL_NAME not in name:
return i
raise SystemExit(
"No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
)
def _alsa_port(client_substr: str, port_substr: str | None = None) -> str | None:
"""Return 'client:port' for an aconnect client/port name match."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return None
client = None
client_name = None
for line in out.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = int(m.group(1)), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if not m or client is None or client_name is None:
continue
port, pname = int(m.group(1)), m.group(2).strip()
if client_substr not in client_name and client_substr not in pname:
continue
if port_substr and port_substr not in pname and port_substr not in client_name:
continue
if VIRTUAL_NAME in pname:
continue
return f"{client}:{port}"
return None
def ensure_alsa_link() -> None:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe."""
src = None
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"):
src = _alsa_port(hint)
if src:
break
dst = _alsa_port("smc-smooth-in")
if not src or not dst:
return
subprocess.run(["aconnect", src, dst], capture_output=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--tau",
type=float,
default=0.055,
help="smoothing time constant in seconds (default 0.055)",
)
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
ap.add_argument(
"--lock-knobs",
action="store_true",
help="knobs 1-10 move test.qxw's custom sliders only after the Custom pad is pressed",
)
ap.add_argument("--no-lamps", action="store_true", help="leave the pad lamp colours alone")
args = ap.parse_args()
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
midiout.open_virtual_port(VIRTUAL_NAME)
# current/target as floats 0..127, keyed by (channel, cc)
current: dict[tuple[int, int], float] = {}
target: dict[tuple[int, int], float] = {}
last_sent: dict[tuple[int, int], int] = {}
layer = PlayLayer(lock_knobs=args.lock_knobs)
print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
print("Pass notes through (Play held shifts bank 2 up 16); smooth CC. Ctrl+C to stop.", flush=True)
ensure_alsa_link()
if not args.no_lamps:
set_lamps()
dt = 1.0 / args.rate
alpha = 1.0 - math.exp(-dt / max(args.tau, 1e-4))
next_link_check = time.monotonic() + 2.0
try:
while True:
now = time.monotonic()
if now >= next_link_check:
ensure_alsa_link()
next_link_check = now + 2.0
# Drain inbound
while True:
msg = midiin.get_message()
if msg is None:
break
data, _ = msg
if not data:
continue
for out in layer.handle(list(data)):
cmd = out[0] & 0xF0
if cmd == 0xB0 and len(out) >= 3:
# Control Change → smooth
key = (out[0] & 0x0F, out[1])
target[key] = float(out[2])
if key not in current:
current[key] = float(out[2])
last_sent[key] = -1
else:
# Notes, aftertouch, PC, etc. → immediate
midiout.send_message(out)
# Ease CC toward targets and emit when quantized value moves
for key, tgt in list(target.items()):
cur = current.get(key, tgt)
cur = cur + (tgt - cur) * alpha
# Snap when close so we actually reach the endpoint
if abs(tgt - cur) < 0.15:
cur = tgt
current[key] = cur
q = int(round(cur))
q = 0 if q < 0 else 127 if q > 127 else q
if last_sent.get(key) != q:
ch, cc = key
midiout.send_message([0xB0 | ch, cc, q])
last_sent[key] = q
time.sleep(dt)
except KeyboardInterrupt:
print("\nStopped.", flush=True)
finally:
midiin.close_port()
midiout.close_port()
del midiin
del midiout
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Reliable MIDI bring-up for shows/midi.qxw
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) smoother (creates "SMC-PAD Smooth")
# 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 smoother so it re-opens the pad port cleanly (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 '/[.]venv\/bin\/python .*smooth_smc_pad[.]py/ {print $1}')
sleep 0.4
nohup "$PYTHON" scripts/pad/smooth_smc_pad.py --tau 0.055 >>/tmp/smooth_smc_pad.log 2>&1 &
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
break
fi
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
echo "Smoother failed to create SMC-PAD Smooth. See /tmp/smooth_smc_pad.log" >&2
tail -20 /tmp/smooth_smc_pad.log >&2 || true
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 → Smooth → qlcplus):"
aconnect -l | grep -E "SMC-PAD|SINCO|Smooth|qlcplus|smc-smooth" -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)."