Light pad bank 2 from page 7, and add factory reset and a pad bank toggle to the editor.

Bank 2's lamp colours come from preset page 7, not page 3, so pad_colours.py
writes there and the editor labels it Bank 2. The factory reset loads the
image MidiSuite uploads for its own reset, and the bank toggle writes the
global-block byte MidiSuite uses to switch banks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Sonnet 5.5 committed 2026-10-21 20:34:34 +13:00
1 parent 63b3129cca
commit 3992744a1d
9 files changed
+239 -113

No files matched your search

+21
View File
@@ -178,6 +178,27 @@ def read_global(link: Link | None = None) -> bytes:
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 padeditor.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.
Binary file not shown.
+6
View File
@@ -31,6 +31,7 @@ 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.
@@ -132,6 +133,7 @@ def unpack_global(raw: bytes) -> dict:
"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(),
}
@@ -151,6 +153,10 @@ def pack_global(block: dict) -> bytes:
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)
+24 -1
View File
@@ -10,10 +10,13 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, write_colour
from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour
from padeditor.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):
@@ -76,12 +79,28 @@ class Editor:
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)
@@ -173,11 +192,15 @@ class Handler(BaseHTTPRequestHandler):
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:
+51 -2
View File
@@ -158,6 +158,48 @@ async function importFile(file) {
}
}
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");
@@ -185,6 +227,12 @@ function renderGlobal() {
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() {
@@ -207,8 +255,8 @@ function renderPages() {
const select = $("page");
const current = select.value;
select.replaceChildren();
const order = [2, 3, 0, 1, 4, 5, 6, 7];
const names = { 2: "Bank 1", 3: "Bank 2" };
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");
@@ -422,6 +470,7 @@ function renderInspector() {
$("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 = "";
+1
View File
@@ -11,6 +11,7 @@
<h1>SMC-PAD</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">
+82 -103
View File
@@ -8,6 +8,10 @@ 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
.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
@@ -20,89 +24,32 @@ 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))
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)
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]:
@@ -124,6 +71,31 @@ XCHC_COLOURS = (
)
# 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:
@@ -145,11 +117,17 @@ def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]:
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")
skip = (bank - 1) * 16 * RECORD
page = BANK_PAGE.get(bank, bank + 1)
skip = (page - 2) * 16 * RECORD
return tuple(base + skip for base in BANKS)
@@ -178,33 +156,18 @@ def payload_data(decoded: bytes) -> bytes:
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)"])
)
try:
return _private_port(names)
except PadError as exc:
raise SystemExit(str(exc)) from exc
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:
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)
@@ -221,9 +184,9 @@ def apply(clear: bool, bank: int = 1, colours: list[tuple[str, bytes]] | None =
try:
note = 36 + (bank - 1) * 16
for base in bank_bases(bank):
reply = _transact(midiout, midiin, read_request(base, 2))
reply = transact(midiout, midiin, read_request(base, 2))
mark = payload_data(reply)
if mark[:2] != bytes((0x09, note)):
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"
)
@@ -231,16 +194,16 @@ def apply(clear: bool, bank: int = 1, colours: list[tuple[str, bytes]] | None =
shown = set()
for name, address, rgb in colour_writes(clear, bank, colours):
for base in bases:
_transact(midiout, midiin, write_request(base + address, rgb))
transact(midiout, midiin, write_request(base + address, rgb))
if name in shown:
continue
check = payload_data(_transact(midiout, midiin, read_request(address, 3)))
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())
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)
@@ -252,10 +215,26 @@ def apply(clear: bool, bank: int = 1, colours: list[tuple[str, bytes]] | None =
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("--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 None
if args.dry_run:
seen = set()
@@ -265,7 +244,7 @@ def main(argv: list[str] | None = None) -> int:
seen.add(name)
print(f"{name:<8} {address:#06x} {rgb.hex()}")
return 0
apply(args.clear, args.bank, palette)
apply(args.clear, args.bank, palette, any_note=args.page is not None)
return 0
+27 -7
View File
@@ -53,7 +53,7 @@ def test_scene_colours_are_stored_on_the_note_36_pads():
}
def test_xchc_colours_are_stored_on_pad_bank_2():
def test_xchc_colours_are_stored_on_page_7_for_pad_bank_2():
writes = colours.colour_writes(bank=2, colours=colours.xchc_colours())
first = [item for item in writes if item[1] < colours.BANKS[1]]
assert [name for name, _addr, _rgb in first] == [
@@ -74,13 +74,13 @@ def test_xchc_colours_are_stored_on_pad_bank_2():
"",
"",
]
assert first[0][1:] == (1464, bytes.fromhex("f00000"))
assert first[1][1:] == (1490, bytes.fromhex("f07800"))
assert first[6][1:] == (1464 + 6 * 26, bytes.fromhex("7800f0"))
assert first[8][1:] == (1464 + 8 * 26, bytes.fromhex("f0f0f0"))
assert first[9][1:] == (1464 + 9 * 26, b"\x00\x00\x00")
assert first[0][1:] == (3128, bytes.fromhex("f00000"))
assert first[1][1:] == (3154, bytes.fromhex("f07800"))
assert first[6][1:] == (3128 + 6 * 26, bytes.fromhex("7800f0"))
assert first[8][1:] == (3128 + 8 * 26, bytes.fromhex("f0f0f0"))
assert first[9][1:] == (3128 + 9 * 26, b"\x00\x00\x00")
assert {address for name, address, _rgb in writes if name == "Red"} == {
base + 16 * 26 + 4 for base in colours.BANKS
base + 5 * 16 * 26 + 4 for base in colours.BANKS
}
@@ -99,3 +99,23 @@ def test_private_port_is_not_the_master_or_qlc():
"qlcplus:__QLC__ 128:0",
]
assert colours.private_port(names) == "SINCO:SINCO SMC-PAD-Private 20:0"
def test_identify_lights_each_page_in_its_own_colour():
factory = (ROOT / "tests" / "data" / "smc_pad_factory.bin").read_bytes()
image = colours.identify_image(factory)
preset = colours.preset
assert len(image) == len(factory)
for number in range(preset.PRESET_COUNT):
for index in range(preset.PAD_COUNT):
at = preset.colour_offset(number, index)
_name, red, green, blue = colours.PAGE_COLOURS[index // preset.PAGE_LEN]
assert image[at:at + 3] == bytes(map(colours.scale, (red, green, blue)))
changed = {at for at in range(len(image)) if image[at] != factory[at]}
lamps = {
preset.colour_offset(number, index) + step
for number in range(preset.PRESET_COUNT)
for index in range(preset.PAD_COUNT)
for step in range(3)
}
assert changed <= lamps
+27
View File
@@ -169,3 +169,30 @@ def test_factory_image_reads_as_midisuite_shows_it():
# Knob 6: CC, Channel 1, CC 35, 0–127.
knob6 = first["knobs"][5]
assert (knob6["type"], knob6["channel"], knob6["number"], knob6["left"], knob6["right"]) == (0, 1, 35, 0, 127)
def test_factory_document_packs_back_to_the_midisuite_image():
from pathlib import Path
from padeditor.preset import pack
from padeditor.server import Editor
document = Editor().factory()
assert pack(document) == (Path(__file__).parents[1] / "padeditor" / "factory.bin").read_bytes()
assert document["global"]["raw"] == "780032040000020001010000"
def test_global_bank_byte_round_trips_and_is_checked():
import pytest
from padeditor.preset import PresetError, pack_global, unpack_global
raw = bytes.fromhex("780032040000020001010001")
block = unpack_global(raw)
assert block["bank"] == 1
assert pack_global(block) == raw
block["bank"] = 0
assert pack_global(block)[11] == 0
block["bank"] = 2
with pytest.raises(PresetError):
pack_global(block)