Files
qlcplus/padcontroller/device.py
T

337 lines
11 KiB
Python

"""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