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