#!/usr/bin/env python3 """Set the colours of the SMC-PAD pads. MidiSuite is not required. This talks to the pad over the Bluetooth connection it already has. python3 scripts/smc_pad.py python3 scripts/smc_pad.py 1 blue 2 green 5 red python3 scripts/smc_pad.py 1-4 blue 5-8 red --all off python3 scripts/smc_pad.py --bank 8 1 ff8800 Pad 1 is the bottom-left pad. Numbers then go right, and the next row starts at the left. A colour is a name (red, green, blue, yellow, cyan, magenta, orange, white, off) or six hex digits, such as ff8800. The colour shows straight away. It stays until the pad is switched off. """ from __future__ import annotations import argparse import queue import sys import threading import time from dataclasses import dataclass PRESET_SIZE = 3539 PAD_BANKS = 8 PAD_COUNT = 16 PAD_RECORD_SIZE = 26 PAD_TABLE_OFFSET = 211 PAD_RGB_OFFSET = 5 PAD_LED_OFFSET = 8 LED_FOLLOWS_HOST = 0xFF READ = 0x23 WRITE = 0x22 PRESET_REGION = 0x05 STATE_REGION = 0x04 ACK = bytes.fromhex("00590001000000ff") STATE_BASE_BANK = 6 STATE_SLOT = 10 STATE_BANK_TOGGLE = 11 TOGGLE_BANK = 8 COLOURS = { "off": (0x00, 0x00, 0x00), "black": (0x00, 0x00, 0x00), "red": (0xF0, 0x00, 0x00), "green": (0x00, 0xF0, 0x00), "blue": (0x00, 0x00, 0xF0), "yellow": (0xF0, 0xF0, 0x00), "cyan": (0x00, 0xF0, 0xF0), "magenta": (0xF0, 0x00, 0xF0), "orange": (0xF0, 0x60, 0x00), "white": (0xF0, 0xF0, 0xF0), } # Top row first, so a printed grid matches the pad under your hands. READING_ROWS = ((13, 14, 15, 16), (9, 10, 11, 12), (5, 6, 7, 8), (1, 2, 3, 4)) class PadError(Exception): pass def vendor_packet(command: int, region: int, address: int, data_or_count: bytes | int) -> bytes: """One read or write for the pad's configuration channel.""" if isinstance(data_or_count, int): count, data = data_or_count, b"" else: count, data = len(data_or_count), data_or_count payload = bytes((region, *address.to_bytes(4, "little"), *count.to_bytes(3, "little"))) + data checksum = (~sum(payload)) & 0xFF return bytes((0x00, 0x59, command, *len(payload).to_bytes(3, "little"))) + payload + bytes((checksum,)) @dataclass(frozen=True) class Reply: command: int region: int address: int data: bytes checksum_ok: bool def parse_reply(packet: bytes) -> Reply: if len(packet) < 7 or packet[0] != 0x00 or packet[1] != 0x59: raise PadError(f"unexpected reply {packet.hex()}") command = packet[2] length = int.from_bytes(packet[3:6], "little") payload = packet[6 : 6 + length] checksum_ok = len(packet) > 6 + length and (sum(payload) + packet[6 + length]) & 0xFF == 0xFF if command in (READ, WRITE) and len(payload) >= 8: count = int.from_bytes(payload[5:8], "little") return Reply( command, payload[0], int.from_bytes(payload[1:5], "little"), payload[8 : 8 + count], checksum_ok, ) return Reply(command, 0, 0, payload, checksum_ok) def bank_address(slot: int, bank: int) -> int: if not 0 <= slot <= 7: raise PadError(f"preset slot must be 0 to 7, got {slot}") if not 1 <= bank <= PAD_BANKS: raise PadError(f"bank must be 1 to {PAD_BANKS}, got {bank}") return slot * PRESET_SIZE + PAD_TABLE_OFFSET + (bank - 1) * PAD_COUNT * PAD_RECORD_SIZE def parse_state(block: bytes) -> tuple[int, int]: """Return the preset slot and the pad bank on display.""" if len(block) < 16: raise PadError("state block is too short") slot = block[STATE_SLOT] base = block[STATE_BASE_BANK] toggle = block[STATE_BANK_TOGGLE] if not 0 <= slot <= 7 or not 0 <= base <= 7 or toggle not in (0, 1): raise PadError(f"state block is not a preset display: {block.hex()}") bank = TOGGLE_BANK if toggle else base + 1 return slot, bank def colour_of(text: str) -> tuple[int, int, int]: name = text.strip().lower() if name in COLOURS: return COLOURS[name] hex_digits = name[1:] if name.startswith("#") else name if len(hex_digits) == 6 and all(c in "0123456789abcdef" for c in hex_digits): return tuple(int(hex_digits[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value] known = ", ".join(name for name in COLOURS if name != "black") raise PadError(f"unknown colour {text!r}. Use {known}, or six hex digits.") def pad_numbers(text: str) -> list[int]: """'1', '1-4', and '1,3,5' all name pads.""" pads: list[int] = [] for part in text.split(","): part = part.strip() if not part: continue ends = part.split("-") if len(ends) == 1: pads.append(_one_pad(ends[0])) elif len(ends) == 2: first, last = _one_pad(ends[0]), _one_pad(ends[1]) step = 1 if last >= first else -1 pads.extend(range(first, last + step, step)) else: raise PadError(f"bad pad range {text!r}") if not pads: raise PadError(f"bad pad {text!r}") return pads def _one_pad(text: str) -> int: if not text.isdigit(): raise PadError(f"bad pad {text!r}") number = int(text) if not 1 <= number <= PAD_COUNT: raise PadError(f"pad must be 1 to {PAD_COUNT}, got {number}") return number def colour_map(items: list[str], fill: str | None) -> dict[int, tuple[int, int, int]]: """Pairs of pad and colour. Later pairs win. ``fill`` paints every pad first.""" chosen: dict[int, tuple[int, int, int]] = {} if fill is not None: rgb = colour_of(fill) chosen = {pad: rgb for pad in range(1, PAD_COUNT + 1)} if len(items) % 2: raise PadError("each pad needs a colour, for example: 1 blue 5 red") for pad_text, colour_text in zip(items[0::2], items[1::2]): rgb = colour_of(colour_text) for pad in pad_numbers(pad_text): chosen[pad] = rgb return chosen def rgb_at(bank: bytes, pad: int) -> tuple[int, int, int]: start = (pad - 1) * PAD_RECORD_SIZE + PAD_RGB_OFFSET return bank[start], bank[start + 1], bank[start + 2] def led_at(bank: bytes, pad: int) -> int: return bank[(pad - 1) * PAD_RECORD_SIZE + PAD_LED_OFFSET] def paint(bank: bytes, colours: dict[int, tuple[int, int, int]]) -> bytearray: painted = bytearray(bank) for pad, rgb in colours.items(): start = (pad - 1) * PAD_RECORD_SIZE + PAD_RGB_OFFSET painted[start : start + 3] = rgb return painted def format_colour(rgb: tuple[int, int, int]) -> str: return "#{:02x}{:02x}{:02x}".format(*rgb) def format_grid(bank: bytes) -> str: lines = [] for row in READING_ROWS: cells = [] for pad in row: cells.append(f"{pad:2d} {format_colour(rgb_at(bank, pad))}") lines.append(" ".join(cells)) return "\n".join(lines) class PadLink: """BlueZ client for the pad's configuration characteristics.""" def __init__(self) -> None: self._queue: queue.Queue[bytes | BaseException] = queue.Queue() self._loop = None self._notify = None self._write = None self._notify_path = "" def __enter__(self) -> PadLink: self.open() return self def __exit__(self, *_args: object) -> None: self.close() def open(self) -> None: import dbus from dbus.mainloop.glib import DBusGMainLoop from gi.repository import GLib # Look up the pad before the GLib bus exists. On this machine a # GLib connection does not list the configuration characteristics. probe = dbus.SystemBus() device = _find_device(probe, dbus) write_path, notify_path = _find_channels(probe, dbus, device) DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus(private=True) self._notify_path = notify_path self._notify = dbus.Interface(bus.get_object("org.bluez", notify_path), "org.bluez.GattCharacteristic1") self._write = dbus.Interface(bus.get_object("org.bluez", write_path), "org.bluez.GattCharacteristic1") bus.add_signal_receiver( self._on_value, signal_name="PropertiesChanged", dbus_interface="org.freedesktop.DBus.Properties", path=notify_path, ) self._loop = GLib.MainLoop() threading.Thread(target=self._loop.run, daemon=True).start() self._notify.StartNotify() def close(self) -> None: if self._notify is not None: try: self._notify.StopNotify() except Exception: pass if self._loop is not None: self._loop.quit() def _on_value(self, _iface: str, changed: dict, _invalidated: list) -> None: if "Value" in changed: self._queue.put(bytes(changed["Value"])) def request(self, packet: bytes) -> bytes: from gi.repository import GLib while not self._queue.empty(): self._queue.get_nowait() def send() -> bool: try: import dbus self._write.WriteValue( dbus.Array(packet, signature="y"), dbus.Dictionary({"type": "command"}, signature="sv"), ) except Exception as exc: self._queue.put(exc) return False GLib.idle_add(send) try: reply = self._queue.get(timeout=3) except queue.Empty: raise PadError("the pad did not answer") from None if isinstance(reply, BaseException): raise PadError(str(reply)) from reply return reply def read(self, address: int, count: int, region: int = PRESET_REGION) -> bytes: raw = self.request(vendor_packet(READ, region, address, count)) reply = parse_reply(raw) if reply.command != READ or not reply.checksum_ok: raise PadError(f"bad read reply {raw.hex()}") if reply.region != region or reply.address != address or len(reply.data) != count: raise PadError( f"read {region:#x}:{address:#x} returned {len(reply.data)} bytes " f"from {reply.region:#x}:{reply.address:#x}" ) return reply.data def write(self, address: int, data: bytes, region: int = PRESET_REGION) -> None: raw = self.request(vendor_packet(WRITE, region, address, data)) if raw != ACK: reply = parse_reply(raw) if not reply.checksum_ok: raise PadError(f"the pad rejected the write: {raw.hex()}") def _find_device(bus: object, dbus: object) -> str: manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") objects = manager.GetManagedObjects() found: list[tuple[bool, str]] = [] for path, ifaces in objects.items(): device = ifaces.get("org.bluez.Device1") if not device: continue name = str(device.get("Name", "") or device.get("Alias", "")) if "smc-pad" not in name.lower(): continue found.append((bool(device.get("Connected", False)), str(path))) if not found: raise PadError("SMC-PAD not found. Turn it on, and pair it in Bluetooth settings.") found.sort(reverse=True) path = found[0][1] device = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Device1") props = dbus.Interface(bus.get_object("org.bluez", path), "org.freedesktop.DBus.Properties") if not bool(props.Get("org.bluez.Device1", "Connected")): device.Connect() deadline = time.time() + 8 while time.time() < deadline: if bool(props.Get("org.bluez.Device1", "Connected")): break time.sleep(0.2) else: raise PadError("could not connect to the SMC-PAD") return path def _find_channels(bus: object, dbus: object, device: str) -> tuple[str, str]: deadline = time.time() + 5 while True: manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") objects = manager.GetManagedObjects() write_path = notify_path = "" for path, ifaces in objects.items(): if not str(path).startswith(device): continue char = ifaces.get("org.bluez.GattCharacteristic1") if not char: continue uuid = str(char.get("UUID", "")).lower() if uuid.startswith("0000ae41-"): write_path = str(path) elif uuid.startswith("0000ae42-"): notify_path = str(path) if write_path and notify_path: return write_path, notify_path if time.time() > deadline: raise PadError("the pad is connected, but its configuration channel is missing") time.sleep(0.2) def showing(link: PadLink, preset: int | None, bank: int | None) -> tuple[int, int, bytes]: slot, visible = parse_state(link.read(0, 16, STATE_REGION)) if preset is not None: if not 1 <= preset <= 8: raise PadError("preset must be 1 to 8") slot = preset - 1 if bank is not None: if not 1 <= bank <= PAD_BANKS: raise PadError("bank must be 1 to 8") visible = bank image = link.read(bank_address(slot, visible), PAD_COUNT * PAD_RECORD_SIZE) return slot, visible, image def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("items", nargs="*", help="pad colour pairs, such as 1 blue 5-8 red") parser.add_argument("--all", metavar="COLOUR", help="paint every pad this colour first") parser.add_argument("--bank", type=int, help="pad bank 1 to 8; the bank on display is the default") parser.add_argument("--preset", type=int, help="preset 1 to 8; the preset on display is the default") args = parser.parse_args(argv) try: colours = colour_map(args.items, args.all) with PadLink() as link: slot, bank, image = showing(link, args.preset, args.bank) print(f"Preset {slot + 1}, bank {bank}. Pad 1 is the bottom-left pad.") if not colours: print(format_grid(image)) hidden = [pad for pad in range(1, PAD_COUNT + 1) if led_at(image, pad) != LED_FOLLOWS_HOST] if hidden: listed = ", ".join(str(pad) for pad in hidden) print(f"Pads {listed} show incoming MIDI, so their stored colour stays hidden.") return 0 updated = paint(image, colours) if updated == image: print(format_grid(image)) print("Those pads are already that colour.") return 0 link.write(bank_address(slot, bank), bytes(updated)) print(format_grid(updated)) print("Saved on the pad until it is switched off.") except PadError as exc: print(exc, file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())