Add a script that writes SMC-PAD pad colours and saves them on the controller.

The lamps ignore note messages, so the colours are stored in the preset and committed with the same empty write MidiSuite's Save button sends.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jimmyandCursor committed 2026-10-21 17:38:20 +13:00
1 parent 12420bec93
commit 3b0920eeb2
2 files changed
+374

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
#!/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_colours.py --xchc --bank 2
.venv/bin/python scripts/pad_colours.py --dry-run
.venv/bin/python scripts/pad_colours.py --clear
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
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from patch_smc_pad import PAD_COLORS # noqa: E402
# 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)
RAM = 0x80000000
FULL = 0xF0
def encode(source: bytes) -> bytes:
"""Pack a protocol message into the 7-bit SysEx body."""
bit_num = 0
accum = 0
out = bytearray()
for byte in source:
accum = ((byte << (bit_num & 0x1F)) | accum) & 0xFFFFFFFF
bit_num += 1
while True:
out.append(accum & 0x7F)
accum = (accum >> 7) & 0xFFFFFFFF
if bit_num < 7:
break
bit_num -= 7
out.append(accum & 0x7F)
return bytes(out)
def decode(source: bytes) -> bytes:
bit_num = 0
last_val = 0
out = bytearray()
for byte in source:
accum = byte & (0xFFFFFFFF >> (32 - bit_num) if bit_num else 0)
if bit_num > 0:
out.append((last_val & 0x7F) | ((accum << (8 - bit_num)) & 0xFF))
last_val = byte >> bit_num
bit_num = (bit_num + 1) % 8
if last_val > 0:
out.append(last_val)
return bytes(out)
def checksum(payload: bytes) -> int:
total = 0
for byte in payload:
total = (total + byte) & 0xFF
return (~total) & 0xFF
def frame(command: int, payload: bytes) -> list[int]:
data = bytearray((0x00, 0x59, command))
data += len(payload).to_bytes(3, "little")
data += payload
data.append(checksum(payload))
return [0xF0, *encode(bytes(data)), 0xF7]
def read_request(address: int, size: int) -> list[int]:
payload = bytes([5]) + address.to_bytes(4, "little") + size.to_bytes(3, "little")
return frame(0x23, payload)
def write_request(address: int, data: bytes) -> list[int]:
payload = bytes([5]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data
return frame(0x22, payload)
def save_request() -> list[int]:
"""Commit the running preset. MidiSuite's Save is this empty write."""
return write_request(0, b"")
def scale(value: int) -> int:
"""Map 0–255 onto the pad's 0–240 colour range."""
return (value * FULL + 127) // 255
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),
)
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 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")
skip = (bank - 1) * 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:
for name in names:
if "Private" in name:
return name
raise SystemExit(
"SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"])
)
def _transact(midiout, midiin, message: list[int], timeout: float = 0.8) -> bytes:
while True:
item = midiin.get_message()
if not item or not item[0]:
break
midiout.send_message(message)
deadline = time.time() + timeout
while time.time() < deadline:
item = midiin.get_message()
if not item or not item[0]:
time.sleep(0.004)
continue
raw = bytes(item[0])
if raw[:1] == b"\xf0" and raw[-1:] == b"\xf7":
return decode(raw[1:-1])
raise TimeoutError("the pad did not answer")
def apply(clear: bool, bank: int = 1, colours: list[tuple[str, bytes]] | None = None) -> 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[:2] != bytes((0x09, 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:
midiout.close_port()
midiin.close_port()
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("--xchc", action="store_true", help="use the solid colour scenes from shows/xchc.qxw")
parser.add_argument("--clear", action="store_true", help="store black on every scene pad")
parser.add_argument("--dry-run", action="store_true", help="print the colours and do not open a port")
args = parser.parse_args(argv)
palette = xchc_colours(args.clear) if args.xchc 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)
return 0
if __name__ == "__main__":
raise SystemExit(main())