#!/usr/bin/env python3 """Print the SMC-PAD SysEx in a usbmon capture. sudo tcpdump -i usbmon1 -s 0 -U -w - > captures/pad.pcap python3 scripts/decode_usbmon.py captures/pad.pcap --device 21 Each USB-MIDI packet is reassembled into messages per cable, then SINCO SysEx is decoded to its command, memory, address, and data. """ from __future__ import annotations import argparse import struct import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from padeditor.sysex import decode # noqa: E402 LINKTYPE_USB_LINUX_MMAPPED = 220 HEADER = struct.Struct("> 4 if head == 0: continue body = data[at + 1:at + 1 + CIN_SIZE.get(cin, 0)] key = (direction, cable) if cin in (0x4, 0x5, 0x6, 0x7) or (pending.get(key) and cin == 0xF): buf = pending.setdefault(key, bytearray()) buf += body if cin != 0x4 and buf.endswith(b"\xf7"): yield stamp, direction, cable, bytes(buf) del pending[key] else: yield stamp, direction, cable, bytes(body) def describe(message: bytes) -> str: if message[:1] != b"\xf0" or message[-1:] != b"\xf7": return message.hex(" ") inner = decode(message[1:-1]) if inner[:2] != b"\x00\x59" or len(inner) < 7: return f"sysex {inner.hex(' ')}" command = COMMANDS.get(inner[2], f"cmd {inner[2]:#04x}") length = int.from_bytes(inner[3:6], "little") payload = inner[6:6 + length] if inner[2] in (0x22, 0x23) and len(payload) >= 8: memory = payload[0] address = int.from_bytes(payload[1:5], "little") size = int.from_bytes(payload[5:8], "little") data = payload[8:] text = f"{command} mem {memory} addr {address:#010x} len {size}" return f"{text} data {data.hex()}" if data else text return f"{command} {payload.hex(' ')}" def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("capture", type=Path) parser.add_argument("--device", type=int, help="USB device number from lsusb") args = parser.parse_args(argv) start = None for stamp, direction, cable, message in messages(args.capture, args.device): start = stamp if start is None else start print(f"{stamp - start:8.3f} {direction} cable {cable} {describe(message)}") return 0 if __name__ == "__main__": raise SystemExit(main())