Files
qlcplus/scripts/pad_colours.py
T

268 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 --colour-set --bank 2
.venv/bin/python scripts/pad_colours.py --dry-run
.venv/bin/python scripts/pad_colours.py --clear
.venv/bin/python scripts/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[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts"))
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."""
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())