Rename padeditor to padcontroller, with the MIDI intercept as padcontroller.midi and its virtual port as padcontroller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-22 13:25:06 +13:00
1 parent 1e09cb3825
commit 9742121144
31 files changed
+79 -79

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Pad Controller: the SMC-PAD preset editor and MIDI intercept."""
+33
View File
@@ -0,0 +1,33 @@
"""python3 -m padcontroller [--port 8770]"""
from __future__ import annotations
import argparse
import threading
import webbrowser
from padcontroller.server import make_server
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="padcontroller", description="Pad Controller: SMC-PAD preset editor")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8770)
parser.add_argument("--no-browser", action="store_true")
args = parser.parse_args(argv)
server = make_server(args.host, args.port)
url = f"http://{args.host}:{args.port}/"
print(f"Pad Controller → {url} Ctrl+C to quit")
if not args.no_browser:
threading.Timer(0.4, webbrowser.open, args=(url,)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+336
View File
@@ -0,0 +1,336 @@
"""Read and save the SMC-PAD preset over the Private USB port.
Writes go to the preset address, as MidiSuite sends them; the lamps follow
straight away. Save writes the bytes that differ, checks each read-back,
then sends the empty write MidiSuite's Save button sends, which keeps the
preset after a power cycle. It never sends erase.
"""
from __future__ import annotations
import glob
import sys
import time
from pathlib import Path
from padcontroller.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges
from padcontroller.sysex import (
CMD_READ,
MEM_GLOBAL,
MEM_PRESET,
RAM,
payload_data,
read_request,
save_request,
write_request,
)
ROOT = Path(__file__).resolve().parents[1]
READ_CHUNK = 512
WRITE_CHUNK = 64
class PadError(RuntimeError):
pass
def load_rtmidi():
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
return rtmidi
def private_port(names: list[str]) -> str:
for name in names:
if "Private" in name:
return name
raise PadError(
"SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"])
)
def master_port(names: list[str]) -> str:
for name in names:
if "Master" in name:
return name
raise PadError(
"SMC-PAD Master port not found. Ports:\n " + "\n ".join(names or ["(none)"])
)
def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect: int | None = None) -> 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" or raw[-1:] != b"\xf7":
continue
decoded = decode_body(raw)
if expect is not None and (len(decoded) < 3 or decoded[2] != expect):
continue
return decoded
raise PadError("the pad did not answer")
def decode_body(raw: bytes) -> bytes:
from padcontroller.sysex import decode
return decode(raw[1:-1])
class Link:
"""One open Private port, input and output."""
def __init__(self):
rtmidi = load_rtmidi()
self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
self.name = private_port(self.midiout.get_ports())
index = self.midiout.get_ports().index(self.name)
self.midiin.open_port(index)
self.midiin.ignore_types(sysex=False, timing=True, active_sense=True)
self.midiout.open_port(index)
def close(self) -> None:
for port in (self.midiout, self.midiin):
port.close_port()
port.delete()
def read(self, address: int, size: int, memory: int = MEM_PRESET) -> bytes:
reply = transact(self.midiout, self.midiin, read_request(address, size, memory), expect=CMD_READ)
data = payload_data(reply)
return data[:size]
def write(self, address: int, data: bytes, memory: int = MEM_PRESET) -> None:
transact(self.midiout, self.midiin, write_request(address, data, memory))
def __enter__(self) -> "Link":
return self
def __exit__(self, *exc) -> None:
self.close()
def read_image(link: Link | None = None) -> bytes:
own = link is None
if link is None:
link = Link()
try:
got = bytearray()
while len(got) < IMAGE_LEN:
ask = min(READ_CHUNK, IMAGE_LEN - len(got))
part = link.read(len(got), ask)
if not part:
raise PadError(f"empty read at {len(got)}")
got += part[:ask]
return bytes(got[:IMAGE_LEN])
finally:
if own:
link.close()
def _port_names(kind: str) -> list[str]:
rtmidi = load_rtmidi()
probe = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) if kind == "out" else rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
try:
return list(probe.get_ports())
finally:
probe.delete()
def read_port_names() -> list[str]:
return _port_names("out")
def input_names() -> list[str]:
return _port_names("in")
def connected() -> str | None:
try:
return private_port(read_port_names())
except PadError:
return None
def read_global(link: Link | None = None) -> bytes:
"""The 12-byte settings block MidiSuite polls: tempo, swing, curve, transpose."""
own = link is None
if link is None:
link = Link()
try:
data = link.read(0, GLOBAL_LEN, MEM_GLOBAL)
if len(data) < GLOBAL_LEN:
raise PadError(f"global block read {len(data)} bytes, expected {GLOBAL_LEN}")
return data[:GLOBAL_LEN]
finally:
if own:
link.close()
def set_bank(bank: int, link: Link | None = None) -> int:
"""Switch the pad bank the way MidiSuite does: one live byte in the
global block. It does not commit; Save keeps whatever the block holds."""
from padcontroller.preset import GLOBAL_BANK
if bank not in (0, 1):
raise PadError("pad bank must be 0 or 1")
own = link is None
if link is None:
link = Link()
try:
link.write(GLOBAL_BANK, bytes((bank,)), MEM_GLOBAL)
got = read_global(link)[GLOBAL_BANK]
if got != bank:
raise PadError(f"the pad is on bank {got + 1}, not {bank + 1}")
return bank
finally:
if own:
link.close()
def save_image(desired: bytes, link: Link | None = None, settings: bytes | None = None) -> int:
"""Write differing bytes to the preset and commit them.
Returns how many bytes were written. An unchanged image still gets
MidiSuite's empty save, so Save always commits. The settings block,
when given and changed, is written whole, as MidiSuite does.
"""
if len(desired) != IMAGE_LEN:
raise PadError(f"preset image is {len(desired)} bytes, expected {IMAGE_LEN}")
if settings is not None and len(settings) != GLOBAL_LEN:
raise PadError(f"global block is {len(settings)} bytes, expected {GLOBAL_LEN}")
own = link is None
if link is None:
link = Link()
try:
current = read_image(link)
ranges = changed_ranges(current, desired, WRITE_CHUNK)
for address, data in ranges:
_write_checked(link, address, data)
written = sum(len(data) for _address, data in ranges)
if settings is not None and read_global(link) != settings:
link.write(0, settings, MEM_GLOBAL)
if read_global(link) != settings:
raise PadError("the pad did not keep the global settings")
written += len(settings)
_commit(link)
return written
finally:
if own:
link.close()
def write_colour(preset: int, index: int, rgb: tuple[int, int, int] | list[int]) -> int:
"""Light one pad. The same three-byte write MidiSuite sends while its
colour picker moves. It does not commit; Save does that."""
from padcontroller.preset import colour_offset
if len(rgb) != 3:
raise PadError("a pad colour needs red, green, and blue")
payload = bytes(int(channel) & 0xFF for channel in rgb)
offset = colour_offset(preset, index)
with Link() as link:
_write_checked(link, offset, payload)
return offset
def _write_checked(link: Link, address: int, data: bytes) -> None:
"""Write the preset address, as MidiSuite does, then read it back."""
link.write(address, data)
reply = transact(link.midiout, link.midiin, read_request(address, len(data)))
got = payload_data(reply)
if got[:len(data)] != data:
raise PadError(
f"read-back at {address:#x} was {got[:len(data)].hex()}, expected {data.hex()}"
)
def _commit(link: Link) -> None:
reply = transact(link.midiout, link.midiin, save_request())
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
raise PadError(f"the pad did not accept the save ({reply.hex()})")
def probe_relative(listen: float = 2.5) -> str:
"""Try knob type 0x03 in RAM only, on every preset's last knob.
Restores the original six bytes. Does not save. Returns ``relative``
when a turn of that knob sends a step, ``absolute`` when it sends a
running value, or ``silent`` when nothing arrives.
"""
from padcontroller.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE
knob = KNOB_COUNT - 1
offsets = [index * PRESET_LEN + KNOB_AT + knob * KNOB_LEN for index in range(PRESET_COUNT)]
rtmidi = load_rtmidi()
master_name = master_port(input_names())
heard: list[tuple[int, int, int]] = []
watched: set[tuple[int, int]] = set()
with Link() as link:
original = [link.read(offset, KNOB_LEN) for offset in offsets]
watched = {(rec[2], rec[3]) for rec in original}
try:
for offset, rec in zip(offsets, original):
link.write(RAM + offset, bytes((RELATIVE_TYPE,)) + rec[1:])
heard = _listen_cc(rtmidi, master_name, listen)
finally:
for offset, rec in zip(offsets, original):
link.write(RAM + offset, rec)
matched = [item for item in heard if (item[0], item[1]) in watched]
return _classify(matched)
def _listen_cc(rtmidi, port_name: str, listen: float) -> list[tuple[int, int, int]]:
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
names = midiin.get_ports()
midiin.open_port(names.index(port_name))
midiin.ignore_types(sysex=True, timing=True, active_sense=True)
found: list[tuple[int, int, int]] = []
try:
deadline = time.time() + listen
while time.time() < deadline:
item = midiin.get_message()
if not item or not item[0]:
time.sleep(0.004)
continue
data = bytes(item[0])
if len(data) >= 3 and (data[0] & 0xF0) == 0xB0:
found.append((data[0] & 0x0F, data[1], data[2]))
finally:
midiin.close_port()
midiin.delete()
return found
def _classify(messages: list[tuple[int, int, int]]) -> str:
if not messages:
return "silent"
values = [value for _channel, _cc, value in messages]
unique = set(values)
if unique <= {0, 1, 127} or unique <= {63, 64, 65} or _steps(values):
return "relative"
if len(unique) >= 4:
return "absolute"
return "silent"
def _steps(values: list[int]) -> bool:
"""1..63 clockwise and 65..127 counter-clockwise, with no running ramp."""
for value in values:
if value == 0 or value == 64 or value > 127:
return False
if value >= 16 and value <= 111:
return False
return True
Binary file not shown.
+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]
+202
View File
@@ -0,0 +1,202 @@
"""Pad controller: intercept the SMC-PAD's MIDI and smooth its 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 "padcontroller".
On start it also sets the pad lamps over USB (scripts/pad/pad_lamps.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 padcontroller/layer.py).
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the pad controller is running).
Usage:
.venv/bin/python -m padcontroller.midi
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
padcontroller/systemd/install.sh runs it as a systemd user service.
"""
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[1]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
from padcontroller.layer import PlayLayer # noqa: E402
# The lamp colours come from the show scripts, which are not part of this package.
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from pad_lamps import set_lamps # noqa: E402
VIRTUAL_NAME = "padcontroller"
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("padcontroller-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="padcontroller-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-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()
+317
View File
@@ -0,0 +1,317 @@
"""SMC-PAD preset image: 8 × 3539 bytes, the map MidiSuite edits."""
from __future__ import annotations
IMAGE_LEN = 28312
PRESET_LEN = 3539
PRESET_COUNT = 8
BUTTON_COUNT = 5
BUTTON_LEN = 23
BUTTON_NAMES = ("Left", "Right", "Play", "Stop", "Record")
KNOB_AT = 115
KNOB_COUNT = 16
KNOB_LEN = 6
KNOB_BANK = 8
GAP_AT = 211
PAD_AT = 212
PAD_LEN = 26
PAD_COUNT = 128
PAGE_LEN = 16
PAGE_COUNT = 8
RGB_AT = 4
# Global settings, memory type 4. Offsets are the fields MidiSuite's Glob
# panel showed against the factory block 78 00 32 04 00 00 02 00 01 01 00 00.
GLOBAL_LEN = 12
GLOBAL_TEMPO = 0 # two bytes, little-endian
GLOBAL_SWING = 2
GLOBAL_CURVE = 6
GLOBAL_TRANSPOSE = 7 # signed
GLOBAL_BANK = 11 # 0 is pad bank 1, 1 is pad bank 2; MidiSuite writes it to switch banks
# File bytes. Names are only values MidiSuite has shown for this pad's
# factory image, or a RAM probe on this pad has heard.
KNOB_TYPES = {0x00: "CC"}
BUTTON_TYPES = {0x02: "CC Push"}
# Set after a RAM-only probe hears a relative step from type 0x03.
RELATIVE_TYPE = 0x03
RELATIVE_CONFIRMED = False
FULL = 0xF0
SYSEX_ROOM = 16 # button bytes 6..21; byte 22 is the flag
def scale(value: int) -> int:
"""Map 0–255 onto the pad's 0–240 colour range."""
return (value * FULL + 127) // 255
def knob_type_names() -> dict[int, str]:
names = dict(KNOB_TYPES)
if RELATIVE_CONFIRMED:
names[RELATIVE_TYPE] = "Relative"
return names
def type_catalog() -> dict[str, list[dict[str, int | str]]]:
def rows(names: dict[int, str]) -> list[dict[str, int | str]]:
return [{"value": value, "name": name} for value, name in sorted(names.items())]
return {
"knob": rows(knob_type_names()),
"button": rows(BUTTON_TYPES),
}
class PresetError(ValueError):
pass
def _byte(value: object, label: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255:
raise PresetError(f"{label} must be a byte")
return value
def _channel(value: object, label: str) -> int:
"""MIDI channel 1–16 as stored, which is 0–15."""
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 16:
raise PresetError(f"{label} must be MIDI channel 1–16")
return value - 1
def _hex(value: object, label: str) -> bytes:
if not isinstance(value, str) or len(value) % 2:
raise PresetError(f"{label} must be even-length hex")
try:
return bytes.fromhex(value)
except ValueError as exc:
raise PresetError(f"{label} is not hex") from exc
def unpack(image: bytes) -> dict:
if len(image) != IMAGE_LEN:
raise PresetError(f"preset image is {len(image)} bytes, expected {IMAGE_LEN}")
presets = []
for index in range(PRESET_COUNT):
block = image[index * PRESET_LEN:(index + 1) * PRESET_LEN]
presets.append(_unpack_preset(block))
return {"presets": presets, "types": type_catalog(), "relative": RELATIVE_CONFIRMED}
def pack(document: dict) -> bytes:
presets = document.get("presets")
if not isinstance(presets, list) or len(presets) != PRESET_COUNT:
raise PresetError(f"expected {PRESET_COUNT} presets")
out = bytearray()
for index, preset in enumerate(presets):
out += _pack_preset(preset, index)
if len(out) != IMAGE_LEN:
raise PresetError(f"packed {len(out)} bytes, expected {IMAGE_LEN}")
return bytes(out)
def colour_offset(preset: int, index: int) -> int:
"""Where one pad's colour sits. MidiSuite writes only this address."""
if not 0 <= preset < PRESET_COUNT:
raise PresetError(f"preset {preset + 1} is not on this controller")
if not 0 <= index < PAD_COUNT:
raise PresetError(f"pad {index + 1} is not on this controller")
return preset * PRESET_LEN + PAD_AT + index * PAD_LEN + RGB_AT
def unpack_global(raw: bytes) -> dict:
if len(raw) != GLOBAL_LEN:
raise PresetError(f"global block is {len(raw)} bytes, expected {GLOBAL_LEN}")
return {
"tempo": int.from_bytes(raw[GLOBAL_TEMPO:GLOBAL_TEMPO + 2], "little"),
"swing": raw[GLOBAL_SWING],
"curve": raw[GLOBAL_CURVE],
"transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True),
"bank": raw[GLOBAL_BANK],
"raw": raw.hex(),
}
def pack_global(block: dict) -> bytes:
"""The named fields over the bytes that were read, so unknown ones stay put."""
out = bytearray(_hex(block.get("raw", ""), "global block"))
if len(out) != GLOBAL_LEN:
raise PresetError(f"global block is {len(out)} bytes, expected {GLOBAL_LEN}")
tempo = block.get("tempo")
if isinstance(tempo, bool) or not isinstance(tempo, int) or not 1 <= tempo <= 0xFFFF:
raise PresetError("tempo must be a whole number of BPM")
out[GLOBAL_TEMPO:GLOBAL_TEMPO + 2] = tempo.to_bytes(2, "little")
out[GLOBAL_SWING] = _byte(block.get("swing"), "swing")
out[GLOBAL_CURVE] = _byte(block.get("curve"), "pad curve")
transpose = block.get("transpose")
if isinstance(transpose, bool) or not isinstance(transpose, int) or not -128 <= transpose <= 127:
raise PresetError("transpose must be -128 to 127")
out[GLOBAL_TRANSPOSE] = transpose & 0xFF
bank = block.get("bank", out[GLOBAL_BANK])
if isinstance(bank, bool) or bank not in (0, 1):
raise PresetError("pad bank must be 0 or 1")
out[GLOBAL_BANK] = bank
return bytes(out)
def changed_ranges(before: bytes, after: bytes, limit: int = 64) -> list[tuple[int, bytes]]:
"""Coalesce differing bytes, then split each run into write-sized pieces."""
if len(before) != len(after):
raise PresetError(f"cannot compare {len(before)} bytes with {len(after)}")
runs: list[tuple[int, int]] = []
start = None
for index, (old, new) in enumerate(zip(before, after)):
if old != new:
if start is None:
start = index
elif start is not None:
runs.append((start, index))
start = None
if start is not None:
runs.append((start, len(after)))
pieces: list[tuple[int, bytes]] = []
for run_at, run_end in runs:
at = run_at
while at < run_end:
stop = min(run_end, at + limit)
pieces.append((at, after[at:stop]))
at = stop
return pieces
def _unpack_preset(block: bytes) -> dict:
buttons = []
for index in range(BUTTON_COUNT):
rec = block[index * BUTTON_LEN:(index + 1) * BUTTON_LEN]
length = rec[5]
if length > SYSEX_ROOM:
sysex, padding = rec[6:22], b""
else:
sysex, padding = rec[6:6 + length], rec[6 + length:22]
buttons.append({
"name": BUTTON_NAMES[index],
"type": rec[0],
"channel": rec[1] + 1,
"number": rec[2],
"min": rec[3],
"max": rec[4],
"sysex": sysex.hex(),
"padding": padding.hex(),
"led": rec[22],
})
knobs = []
for index in range(KNOB_COUNT):
at = KNOB_AT + index * KNOB_LEN
rec = block[at:at + KNOB_LEN]
knobs.append({
"type": rec[0],
"speed": rec[1],
"channel": rec[2] + 1,
"number": rec[3],
"left": rec[4],
"right": rec[5],
})
pads = []
for index in range(PAD_COUNT):
at = PAD_AT + index * PAD_LEN
rec = block[at:at + PAD_LEN]
pads.append({
"channel": rec[0] + 1,
"note": rec[1],
"min": rec[2],
"max": rec[3],
"rgb": [rec[4], rec[5], rec[6]],
"led": rec[7],
"tail": rec[8:].hex(),
})
return {"gap": block[GAP_AT], "buttons": buttons, "knobs": knobs, "pads": pads}
def _pack_preset(preset: dict, index: int) -> bytes:
out = bytearray(PRESET_LEN)
buttons = preset.get("buttons")
knobs = preset.get("knobs")
pads = preset.get("pads")
if not isinstance(buttons, list) or len(buttons) != BUTTON_COUNT:
raise PresetError(f"preset {index + 1} needs {BUTTON_COUNT} buttons")
if not isinstance(knobs, list) or len(knobs) != KNOB_COUNT:
raise PresetError(f"preset {index + 1} needs {KNOB_COUNT} knobs")
if not isinstance(pads, list) or len(pads) != PAD_COUNT:
raise PresetError(f"preset {index + 1} needs {PAD_COUNT} pads")
for number, button in enumerate(buttons):
out[number * BUTTON_LEN:(number + 1) * BUTTON_LEN] = _pack_button(button, index, number)
for number, knob in enumerate(knobs):
at = KNOB_AT + number * KNOB_LEN
out[at:at + KNOB_LEN] = _pack_knob(knob, index, number)
out[GAP_AT] = _byte(preset.get("gap", 0), f"preset {index + 1} gap")
for number, pad in enumerate(pads):
at = PAD_AT + number * PAD_LEN
rec = _pack_pad(pad, index, number)
room = PRESET_LEN - at
if len(rec) > room:
raise PresetError(f"preset {index + 1} pad {number + 1} does not fit")
out[at:at + len(rec)] = rec
return bytes(out)
def _pack_button(button: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} {BUTTON_NAMES[index]}"
sysex = _hex(button.get("sysex", ""), f"{label} sysex")
if len(sysex) > SYSEX_ROOM:
raise PresetError(f"{label} sysex is longer than {SYSEX_ROOM} bytes")
padding = _hex(button.get("padding", ""), f"{label} padding")
room = SYSEX_ROOM - len(sysex)
padding = padding[:room]
rec = bytearray(BUTTON_LEN)
rec[0] = _byte(button.get("type"), f"{label} type")
rec[1] = _channel(button.get("channel"), f"{label} channel")
rec[2] = _byte(button.get("number"), f"{label} number")
rec[3] = _byte(button.get("min"), f"{label} min")
rec[4] = _byte(button.get("max"), f"{label} max")
rec[5] = len(sysex)
rec[6:6 + len(sysex)] = sysex
rec[6 + len(sysex):22] = padding + bytes(room - len(padding))
rec[22] = _byte(button.get("led"), f"{label} led")
return bytes(rec)
def _pack_knob(knob: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} knob {index + 1}"
# Any stored type byte round-trips. The editor only offers names it has seen.
return bytes((
_byte(knob.get("type"), f"{label} type"),
_byte(knob.get("speed"), f"{label} speed"),
_channel(knob.get("channel"), f"{label} channel"),
_byte(knob.get("number"), f"{label} number"),
_byte(knob.get("left"), f"{label} left"),
_byte(knob.get("right"), f"{label} right"),
))
def _pack_pad(pad: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} pad {index + 1}"
rgb = pad.get("rgb")
if not isinstance(rgb, list) or len(rgb) != 3:
raise PresetError(f"{label} colour needs three bytes")
tail = _hex(pad.get("tail", ""), f"{label} tail")
stored = PAD_LEN if index < PAD_COUNT - 1 else PRESET_LEN - (PAD_AT + (PAD_COUNT - 1) * PAD_LEN)
tail_room = stored - 8
if len(tail) > tail_room:
raise PresetError(f"{label} tail is longer than {tail_room} bytes")
rec = bytearray(stored)
rec[0] = _channel(pad.get("channel"), f"{label} channel")
rec[1] = _byte(pad.get("note"), f"{label} note")
rec[2] = _byte(pad.get("min"), f"{label} min velocity")
rec[3] = _byte(pad.get("max"), f"{label} max velocity")
rec[4] = _byte(rgb[0], f"{label} red")
rec[5] = _byte(rgb[1], f"{label} green")
rec[6] = _byte(rgb[2], f"{label} blue")
rec[7] = _byte(pad.get("led"), f"{label} led")
rec[8:8 + len(tail)] = tail
return bytes(rec)
+218
View File
@@ -0,0 +1,218 @@
"""Local editor: load the SMC-PAD preset, edit it, save it back."""
from __future__ import annotations
import json
import mimetypes
import threading
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from padcontroller.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour
from padcontroller.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global
STATIC_DIR = Path(__file__).parent / "static"
# The image MidiSuite uploads for its factory reset, and its global block.
FACTORY_IMAGE = Path(__file__).parent / "factory.bin"
FACTORY_GLOBAL = bytes.fromhex("780032040000020001010000")
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
class Editor:
def __init__(self):
self.lock = threading.Lock()
def status(self) -> dict:
port = connected()
return {"connected": port is not None, "port": port}
def load(self) -> dict:
with self.lock:
try:
with Link() as link:
document = unpack(read_image(link))
document["global"] = unpack_global(read_global(link))
return document
except PadError as exc:
raise ApiError(str(exc), 503) from exc
def save(self, document: dict) -> dict:
try:
desired = pack(document)
block = document.get("global")
settings = pack_global(block) if isinstance(block, dict) else None
except PresetError as exc:
raise ApiError(str(exc)) from exc
with self.lock:
try:
written = save_image(desired, settings=settings)
except PadError as exc:
raise ApiError(str(exc), 503) from exc
if written:
message = f"Saved on the pad. {written} bytes written."
else:
message = "Saved on the pad."
return {"ok": True, "message": message, "bytes": written}
def colour(self, body: dict) -> dict:
try:
preset = int(body["preset"])
index = int(body["index"])
rgb = body["rgb"]
if not isinstance(rgb, list) or len(rgb) != 3:
raise PresetError("a pad colour needs red, green, and blue")
except (KeyError, TypeError, ValueError) as exc:
raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc
with self.lock:
try:
offset = write_colour(preset, index, rgb)
except PresetError as exc:
raise ApiError(str(exc)) from exc
except PadError as exc:
raise ApiError(str(exc), 503) from exc
return {"ok": True, "offset": offset}
def bank(self, body: dict) -> dict:
bank = body.get("bank")
if isinstance(bank, bool) or bank not in (0, 1):
raise ApiError("bank must be 0 or 1")
with self.lock:
try:
set_bank(bank)
except PadError as exc:
raise ApiError(str(exc), 503) from exc
return {"ok": True, "bank": bank}
def imported(self, raw: bytes) -> dict:
try:
return unpack(raw)
except PresetError as exc:
raise ApiError(str(exc)) from exc
def factory(self) -> dict:
document = unpack(FACTORY_IMAGE.read_bytes())
document["global"] = unpack_global(FACTORY_GLOBAL)
return document
def exported(self, document: dict) -> bytes:
try:
return pack(document)
except PresetError as exc:
raise ApiError(str(exc)) from exc
def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer:
editor = Editor()
handler = type("BoundHandler", (Handler,), {"editor": editor})
server = ThreadingHTTPServer((host, port), handler)
server.editor = editor # type: ignore[attr-defined]
return server
class Handler(BaseHTTPRequestHandler):
editor: Editor
def log_message(self, fmt: str, *args) -> None:
return
def _json(self, status: int, body: dict) -> None:
raw = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None:
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
if filename:
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
self.end_headers()
self.wfile.write(raw)
def _read(self) -> bytes:
n = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(n) if n > 0 else b""
def _json_body(self) -> dict:
raw = self._read()
if not raw:
return {}
try:
body = json.loads(raw.decode("utf-8"))
except json.JSONDecodeError as exc:
raise ApiError(f"invalid JSON: {exc}") from exc
if not isinstance(body, dict):
raise ApiError("expected a JSON object")
return body
def _static(self, rel: str) -> None:
rel = rel.lstrip("/") or "index.html"
path = (STATIC_DIR / rel).resolve()
if STATIC_DIR.resolve() not in path.parents or not path.is_file():
self.send_error(404)
return
ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
if ctype.startswith("text/") or ctype.endswith(("javascript", "json")):
ctype = f"{ctype}; charset=utf-8"
self._bytes(path.read_bytes(), ctype)
def _dispatch(self, method: str) -> None:
url = urlparse(self.path)
editor = self.editor
try:
if not url.path.startswith("/api/"):
if method != "GET":
self.send_error(405)
return
if url.path == "/favicon.ico":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
return
self._static(url.path)
return
route = (method, url.path)
if route == ("GET", "/api/status"):
self._json(200, editor.status())
elif route == ("POST", "/api/load"):
self._json(200, editor.load())
elif route == ("POST", "/api/save"):
self._json(200, editor.save(self._json_body()))
elif route == ("POST", "/api/colour"):
self._json(200, editor.colour(self._json_body()))
elif route == ("POST", "/api/bank"):
self._json(200, editor.bank(self._json_body()))
elif route == ("POST", "/api/import"):
raw = self._read()
if len(raw) != IMAGE_LEN:
raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}")
self._json(200, editor.imported(raw))
elif route == ("POST", "/api/factory"):
self._json(200, editor.factory())
elif route == ("POST", "/api/export"):
self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin")
else:
self._json(404, {"error": f"no route {method} {url.path}"})
except ApiError as exc:
self._json(exc.status, {"error": str(exc)})
except Exception as exc: # noqa: BLE001 — surface anything else to the UI
traceback.print_exc()
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
def do_GET(self) -> None: # noqa: N802
self._dispatch("GET")
def do_POST(self) -> None: # noqa: N802
self._dispatch("POST")
+490
View File
@@ -0,0 +1,490 @@
const PAGE = 16;
const state = {
doc: null,
saved: null,
preset: 0,
page: 2,
bank: 0,
kind: null,
index: 0,
};
const $ = (id) => document.getElementById(id);
// Colours are stored as the picker gives them, 0–255, as MidiSuite writes them.
function cssColour(rgb) {
return `rgb(${rgb.join(",")})`;
}
function ink(rgb) {
const [r, g, b] = rgb;
return (r * 0.3 + g * 0.59 + b * 0.11) > 150 ? "#111" : "#f4f6fb";
}
function hexColour(rgb) {
return `#${rgb.map((part) => part.toString(16).padStart(2, "0")).join("")}`;
}
function setStatus(text, kind) {
const node = $("status");
node.textContent = text;
node.className = kind || "";
}
function dirty() {
return state.doc !== null && JSON.stringify(state.doc) !== state.saved;
}
function preset() {
return state.doc.presets[state.preset];
}
function selected() {
if (!state.doc || !state.kind) return null;
const block = preset();
if (state.kind === "pad") return block.pads[state.page * PAGE + state.index];
if (state.kind === "knob") return block.knobs[state.bank * 8 + state.index];
return block.buttons[state.index];
}
function typeChoices(kind, current) {
const known = (state.doc.types && state.doc.types[kind]) || [];
const options = known.map((item) => ({ value: item.value, name: item.name }));
if (!options.some((item) => item.value === current)) {
const hex = current.toString(16).padStart(2, "0");
options.push({ value: current, name: `0x${hex}` });
}
return options;
}
async function request(url, options) {
const response = await fetch(url, options);
const type = response.headers.get("Content-Type") || "";
if (type.includes("application/json")) {
const body = await response.json();
if (!response.ok) throw new Error(body.error || response.statusText);
return body;
}
if (!response.ok) throw new Error(response.statusText);
return response.blob();
}
function mark() {
const unsaved = dirty();
$("save").disabled = !state.doc;
$("export").disabled = !state.doc;
$("save").classList.toggle("dirty", unsaved);
return unsaved;
}
function touch() {
if (mark()) setStatus("Not saved on the pad.", "dirty");
else setStatus("No unsaved edits.", "ok");
}
function showEmpty(text, kind) {
const node = $("empty");
node.hidden = false;
node.textContent = text;
node.className = kind || "";
$("board").classList.remove("ready");
}
async function load(manual) {
if (manual && dirty() && !window.confirm("Load from the pad and drop these edits?")) return;
setStatus("Loading the pad…");
showEmpty("Loading the pad…");
try {
state.doc = await request("/api/load", { method: "POST" });
state.saved = JSON.stringify(state.doc);
render();
setStatus("Loaded from the pad.", "ok");
} catch (error) {
setStatus(error.message, "err");
showEmpty(error.message, "err");
}
}
async function save() {
if (!state.doc) return;
setStatus("Saving…");
$("save").disabled = true;
try {
const body = await request("/api/save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(state.doc),
});
state.saved = JSON.stringify(state.doc);
setStatus(body.message, "ok");
} catch (error) {
setStatus(error.message, "err");
}
mark();
}
async function exportFile() {
if (!state.doc) return;
try {
const blob = await request("/api/export", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(state.doc),
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "smc-pad-preset.bin";
link.click();
URL.revokeObjectURL(url);
} catch (error) {
setStatus(error.message, "err");
}
}
async function importFile(file) {
setStatus("Reading file…");
try {
const raw = new Uint8Array(await file.arrayBuffer());
state.doc = await request("/api/import", {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: raw,
});
render();
setStatus("Imported. Save to pad to store it.", "dirty");
} catch (error) {
setStatus(error.message, "err");
}
}
function withBank(global, bank) {
const raw = global.raw.slice(0, 22) + bank.toString(16).padStart(2, "0") + global.raw.slice(24);
return { ...global, bank, raw };
}
async function switchBank(bank) {
try {
await request("/api/bank", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bank }),
});
const wasDirty = dirty();
state.doc.global = withBank(state.doc.global, bank);
if (!wasDirty) {
const saved = JSON.parse(state.saved);
saved.global = withBank(saved.global, bank);
state.saved = JSON.stringify(saved);
}
state.page = bank ? 7 : 2;
$("page").value = String(state.page);
state.kind = state.kind === "pad" ? null : state.kind;
render();
setStatus(`Pad bank ${bank + 1}.`, "ok");
} catch (error) {
setStatus(error.message, "err");
}
}
async function factory() {
if (!window.confirm("Replace all eight presets with the factory settings? Nothing reaches the pad until you Save.")) return;
setStatus("Reading the factory preset…");
try {
state.doc = await request("/api/factory", { method: "POST" });
render();
setStatus("Factory settings loaded. Save to pad to store them.", "dirty");
} catch (error) {
setStatus(error.message, "err");
}
mark();
}
function render() {
if (!state.doc) return;
$("board").classList.add("ready");
renderGlobal();
renderPresets();
renderPages();
renderPads();
renderKnobs();
renderButtons();
renderInspector();
mark();
}
function renderGlobal() {
const row = $("global");
row.replaceChildren();
const block = state.doc.global;
if (!block) return;
const fields = [
["Tempo", "tempo", 1, 999],
["Swing", "swing", 0, 255],
["Pad curve", "curve", 0, 255],
["Transpose", "transpose", -128, 127],
];
for (const [label, key, min, max] of fields) {
row.append(field(label, numberInput(block, key, min, max)));
}
const toggle = document.createElement("button");
toggle.type = "button";
toggle.textContent = `Pad bank ${block.bank + 1}`;
toggle.title = "Switch the pad's bank now, as MidiSuite does";
toggle.addEventListener("click", () => switchBank(1 - block.bank));
row.append(toggle);
}
function renderPresets() {
const row = $("presets");
row.replaceChildren();
state.doc.presets.forEach((_preset, index) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = String(index + 1);
button.classList.toggle("selected", index === state.preset);
button.addEventListener("click", () => {
state.preset = index;
render();
});
row.append(button);
});
}
function renderPages() {
const select = $("page");
const current = select.value;
select.replaceChildren();
const order = [2, 7, 0, 1, 3, 4, 5, 6];
const names = { 2: "Bank 1", 7: "Bank 2", 3: "Page 4 (not lit)" };
for (const page of order) {
const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE);
const option = document.createElement("option");
option.value = String(page);
const name = names[page] || `Page ${page + 1}`;
option.textContent = `${name} · notes ${pads[0].note}–${pads[PAGE - 1].note}`;
select.append(option);
}
select.value = current || String(state.page);
state.page = Number(select.value);
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
}
function paint(node, rgb) {
node.style.background = cssColour(rgb);
node.style.color = ink(rgb);
}
function renderPads() {
const grid = $("pads");
grid.replaceChildren();
const pads = preset().pads;
for (let row = 3; row >= 0; row -= 1) {
for (let col = 0; col < 4; col += 1) {
const index = row * 4 + col;
const pad = pads[state.page * PAGE + index];
const button = document.createElement("button");
button.type = "button";
button.className = "pad";
button.textContent = String(index + 1);
paint(button, pad.rgb);
button.style.opacity = pad.led ? "" : "0.35";
button.classList.toggle("selected", state.kind === "pad" && state.index === index);
button.addEventListener("click", () => select("pad", index));
grid.append(button);
}
}
}
function renderKnobs() {
const row = $("knobs");
row.replaceChildren();
for (let index = 0; index < 8; index += 1) {
const knob = preset().knobs[state.bank * 8 + index];
const button = document.createElement("button");
button.type = "button";
button.className = "knob";
button.textContent = String(state.bank * 8 + index + 1);
button.title = `CC ${knob.number}`;
button.classList.toggle("selected", state.kind === "knob" && state.index === index);
button.addEventListener("click", () => select("knob", index));
row.append(button);
}
}
function renderButtons() {
const row = $("buttons");
row.replaceChildren();
preset().buttons.forEach((button, index) => {
const node = document.createElement("button");
node.type = "button";
node.className = "btn";
node.textContent = button.name;
node.classList.toggle("selected", state.kind === "button" && state.index === index);
node.addEventListener("click", () => select("button", index));
row.append(node);
});
}
let colourTimer = 0;
function paintColour(index, rgb) {
const edited = state.preset;
preset().pads[index].rgb = rgb.slice();
renderPads();
window.clearTimeout(colourTimer);
colourTimer = window.setTimeout(() => sendColour(edited, index, rgb), 180);
}
async function sendColour(preset, index, rgb) {
try {
await request("/api/colour", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ preset, index, rgb }),
});
} catch (error) {
setStatus(error.message, "err");
}
}
function select(kind, index) {
state.kind = kind;
state.index = index;
render();
}
function field(label, node) {
const wrap = document.createElement("label");
wrap.className = "field";
wrap.append(label, node);
return wrap;
}
function numberInput(item, key, min, max) {
const input = document.createElement("input");
input.type = "number";
input.min = String(min);
input.max = String(max);
input.value = String(item[key]);
input.addEventListener("input", () => {
const value = Number(input.value);
if (!Number.isInteger(value) || value < min || value > max) return;
item[key] = value;
if (key === "led") renderPads();
if (key === "note") {
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
}
touch();
});
return input;
}
function renderInspector() {
const aside = $("inspector");
const item = selected();
aside.replaceChildren();
const title = document.createElement("h2");
if (!item) {
title.textContent = "Control";
const note = document.createElement("p");
note.className = "muted";
note.textContent = "Pick a pad, knob, or button.";
aside.append(title, note);
return;
}
if (state.kind === "pad") title.textContent = `Pad ${state.index + 1}`;
else if (state.kind === "knob") title.textContent = `Knob ${state.bank * 8 + state.index + 1}`;
else title.textContent = item.name;
aside.append(title);
if (state.kind !== "pad") {
const type = document.createElement("select");
typeChoices(state.kind, item.type).forEach((option) => {
const node = document.createElement("option");
node.value = String(option.value);
node.textContent = option.name;
node.selected = option.value === item.type;
type.append(node);
});
type.addEventListener("change", () => {
item.type = Number(type.value);
touch();
});
aside.append(field(state.kind === "button" ? "Mode" : "Type", type));
}
aside.append(field("Channel", numberInput(item, "channel", 1, 16)));
if (state.kind === "pad") {
aside.append(field("Note", numberInput(item, "note", 0, 127)));
aside.append(field("Min velocity", numberInput(item, "min", 0, 127)));
aside.append(field("Max velocity", numberInput(item, "max", 0, 127)));
const colour = document.createElement("input");
colour.type = "color";
colour.value = hexColour(item.rgb);
colour.addEventListener("input", () => {
const hex = colour.value;
const rgb = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16));
paintColour(state.page * PAGE + state.index, rgb);
touch();
});
aside.append(field("Colour", colour));
aside.append(field("Led", numberInput(item, "led", 0, 255)));
} else if (state.kind === "knob") {
aside.append(field("CC", numberInput(item, "number", 0, 127)));
aside.append(field("Speed", numberInput(item, "speed", 0, 127)));
aside.append(field("Min", numberInput(item, "left", 0, 127)));
aside.append(field("Max", numberInput(item, "right", 0, 127)));
if (state.doc.relative) {
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "Relative sends the left value one way and the right value the other.";
aside.append(hint);
}
} else {
aside.append(field("CC", numberInput(item, "number", 0, 127)));
aside.append(field("Value 1", numberInput(item, "min", 0, 127)));
aside.append(field("Value 2", numberInput(item, "max", 0, 127)));
aside.append(field("Led", numberInput(item, "led", 0, 255)));
const sysex = document.createElement("input");
sysex.type = "text";
sysex.value = item.sysex;
sysex.spellcheck = false;
sysex.addEventListener("input", () => {
const hex = sysex.value.replace(/\s+/g, "").toLowerCase();
if (hex.length % 2 || /[^0-9a-f]/.test(hex) || hex.length > 32) return;
item.sysex = hex;
touch();
});
aside.append(field("SysEx", sysex));
}
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "A pad colour lights the lamp as you pick it. Save keeps every edit after a power cycle.";
aside.append(hint);
}
$("load").addEventListener("click", () => load(true));
$("save").addEventListener("click", save);
$("export").addEventListener("click", exportFile);
$("factory").addEventListener("click", factory);
$("import").addEventListener("change", () => {
const file = $("import").files[0];
$("import").value = "";
if (file) importFile(file);
});
$("page").addEventListener("change", () => {
state.page = Number($("page").value);
state.kind = state.kind === "pad" ? null : state.kind;
render();
});
$("bank").addEventListener("change", () => {
state.bank = Number($("bank").value);
state.kind = state.kind === "knob" ? null : state.kind;
render();
});
load(false);
+46
View File
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pad Controller</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>Pad Controller</h1>
<button id="load" type="button">Load</button>
<button id="save" type="button" class="primary" disabled>Save to pad</button>
<button id="factory" type="button">Factory reset</button>
<button id="export" type="button" disabled>Export</button>
<label class="file">Import
<input id="import" type="file" accept=".bin,application/octet-stream">
</label>
<span class="spacer"></span>
<span id="status">Load the preset from the pad.</span>
</header>
<main>
<section id="board">
<p id="empty">Loading the pad…</p>
<div class="row" id="global"></div>
<div class="row" id="presets"></div>
<div class="row">
<label>Pad page <select id="page"></select></label>
<label>Knob bank <select id="bank">
<option value="0">1 · knobs 1–8</option>
<option value="1">2 · knobs 9–16</option>
</select></label>
<span id="page-notes" class="muted"></span>
</div>
<div id="pads"></div>
<div id="knobs"></div>
<div id="buttons"></div>
</section>
<aside id="inspector">
<h2>Control</h2>
<p class="muted">Load a preset, then pick a pad, knob, or button.</p>
</aside>
</main>
<script src="/app.js"></script>
</body>
</html>
+102
View File
@@ -0,0 +1,102 @@
:root {
--bg: #15171c;
--panel: #1e2129;
--panel-2: #262a34;
--line: #343946;
--text: #e6e8ee;
--muted: #8d94a6;
--accent: #5aa9ff;
--danger: #ff6b6b;
--ok: #52d273;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 14px;
background: var(--panel);
border-bottom: 1px solid var(--line);
}
header h1 { font-size: 15px; margin: 0 8px 0 0; }
.spacer { flex: 1; }
#status { color: var(--muted); max-width: 46ch; }
#status.err { color: var(--danger); }
#status.ok { color: var(--ok); }
#status.dirty { color: var(--accent); }
button, select, input[type="number"], input[type="text"] {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--line);
border-radius: 6px;
padding: 6px 10px;
font: inherit;
}
button { cursor: pointer; }
button:disabled { opacity: 0.45; cursor: default; }
button.primary { background: #245a9e; border-color: #3d7dcc; }
button.primary.dirty { background: #1e6b38; border-color: var(--ok); }
button.selected, .pad.selected, .knob.selected, .btn.selected {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
label.file { color: var(--muted); }
label.file input { display: none; }
label.file { cursor: pointer; border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; background: var(--panel-2); color: var(--text); }
main { display: flex; min-height: 0; flex: 1; }
#empty { color: var(--muted); margin: 48px 0; }
#empty.err { color: var(--danger); }
#board.ready #empty { display: none; }
#board, #inspector { padding: 16px; }
#board { flex: 1; }
#inspector {
width: 320px;
background: var(--panel);
border-left: 1px solid var(--line);
overflow: auto;
}
#inspector h2 { margin: 0 0 12px; font-size: 15px; }
.muted { color: var(--muted); }
.row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }
.row label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
#presets { gap: 6px; }
#pads {
display: grid;
grid-template-columns: repeat(4, 76px);
gap: 8px;
margin: 8px 0 18px;
}
.pad, .knob, .btn {
border: 1px solid #0008;
color: #111;
font-weight: 650;
text-align: center;
}
.pad { height: 64px; border-radius: 8px; }
.knob {
width: 64px;
height: 64px;
border-radius: 50%;
background: #d7dbe6;
}
#knobs, #buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
.btn { min-width: 72px; height: 36px; border-radius: 6px; background: #c9ceda; }
.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; color: var(--muted); }
.field input, .field select { width: 100%; }
.hint { color: var(--muted); margin-top: 8px; }
#global .field { margin-bottom: 0; }
#global input { width: 90px; }
+81
View File
@@ -0,0 +1,81 @@
"""SINCO / M-VAVE SysEx codec used by MidiSuite and the SMC-PAD."""
from __future__ import annotations
MEM_GLOBAL = 4
MEM_PRESET = 5
CMD_ACK = 0x00
CMD_WRITE = 0x22
CMD_READ = 0x23
RAM = 0x80000000
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, memory: int = MEM_PRESET) -> list[int]:
payload = bytes([memory]) + address.to_bytes(4, "little") + size.to_bytes(3, "little")
return frame(CMD_READ, payload)
def write_request(address: int, data: bytes, memory: int = MEM_PRESET) -> list[int]:
payload = bytes([memory]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data
return frame(CMD_WRITE, payload)
def save_request() -> list[int]:
"""Commit the running preset. MidiSuite's Save is this empty write."""
return write_request(0, b"")
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:]
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Install the SMC-PAD pad controller as a systemd user service and start it.
#
# padcontroller/systemd/install.sh # install, enable, start
# padcontroller/systemd/install.sh --lock-knobs # pass options to the pad controller
# padcontroller/systemd/install.sh --uninstall
#
# Logs: journalctl --user -u padcontroller -f
set -euo pipefail
UNIT=padcontroller.service
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
DEST="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
if [[ "${1:-}" == "--uninstall" ]]; then
systemctl --user disable --now "$UNIT" 2>/dev/null || true
rm -f "$DEST/$UNIT"
systemctl --user daemon-reload
echo "Removed $UNIT."
exit 0
fi
PYTHON="$ROOT/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON="$(command -v python3)"
"$PYTHON" -c "import rtmidi" 2>/dev/null || {
echo "$PYTHON cannot import rtmidi. Run pipenv install (or pip install python-rtmidi) first." >&2
exit 1
}
ARGS="$*"
mkdir -p "$DEST"
sed -e "s|@ROOT@|$ROOT|g" -e "s|@PYTHON@|$PYTHON|g" -e "s|@ARGS@|$ARGS|g" \
"$HERE/$UNIT" >"$DEST/$UNIT"
systemctl --user daemon-reload
systemctl --user enable "$UNIT"
systemctl --user restart "$UNIT"
echo "Installed $DEST/$UNIT and started it."
systemctl --user --no-pager status "$UNIT" | head -5 || true
@@ -0,0 +1,22 @@
# SMC-PAD pad controller (padcontroller.midi) as a systemd user service.
# install.sh fills in @ROOT@, @PYTHON@ and @ARGS@ and copies it to
# ~/.config/systemd/user/.
[Unit]
Description=SMC-PAD pad controller (virtual port "padcontroller")
After=sound.target
# Keep retrying while the pad is switched off or not paired yet.
StartLimitIntervalSec=0
[Service]
Type=simple
WorkingDirectory=@ROOT@
ExecStart=@PYTHON@ -m padcontroller.midi @ARGS@
Environment=PYTHONUNBUFFERED=1
# The pad controller closes its ports on Ctrl+C.
KillSignal=SIGINT
Restart=always
RestartSec=3
[Install]
WantedBy=default.target