Read the pad over USB when it's plugged in, and keep its links to the pad and QLC+ up.

padcontroller.midi now follows the pad every 2 s: it reopens it after a
replug, moves to USB when that turns up, and re-links QLC+ to the virtual
port after a restart, so QLC+ can stay open. Only the chosen source is
subscribed, so a USB pad no longer gets Bluetooth input as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-22 14:34:05 +13:00
1 parent a295fefac0
commit 8f8c69898a
2 files changed
+162 -46

No files matched your search

+89 -46
View File
@@ -9,7 +9,9 @@ bank 2 in the colours from shows/test.qxw. On Bluetooth it says so and carries o
While Play is held, bank 2 notes 52–67 go out as 68–83 (see padcontroller/layer.py). 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 Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the pad controller is running). patch_smc_pad.py once the pad controller is running). Every 2 s it checks the
links: it reopens the pad when it is replugged (or moves to USB when that turns
up) and re-links QLC+ to the virtual port after a restart, so QLC+ can stay open.
Usage: Usage:
.venv/bin/python -m padcontroller.midi .venv/bin/python -m padcontroller.midi
@@ -26,6 +28,7 @@ import re
import subprocess import subprocess
import sys import sys
import time import time
from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
@@ -42,64 +45,92 @@ sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from pad_lamps import set_lamps # noqa: E402 from pad_lamps import set_lamps # noqa: E402
VIRTUAL_NAME = "padcontroller" VIRTUAL_NAME = "padcontroller"
# USB first when the pad is plugged in, Bluetooth otherwise.
SOURCE_HINTS = ( SOURCE_HINTS = (
"SINCO SMC-PAD-Master",
"SMC-PAD Bluetooth", "SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private", "SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO", "SINCO",
"SMC-PAD", "SMC-PAD",
) )
def find_source_port(midiin: rtmidi.MidiIn) -> int: def pick_source(names: list[str]) -> int | None:
ports = midiin.get_ports() """Index of the best SMC-PAD port in names, or None when the pad is not there."""
for hint in SOURCE_HINTS: for hint in SOURCE_HINTS:
for i, name in enumerate(ports): for i, name in enumerate(names):
if hint in name and VIRTUAL_NAME not in name: if hint in name and VIRTUAL_NAME not in name:
return i 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 return None
def ensure_alsa_link() -> None: def find_source_port(midiin: rtmidi.MidiIn) -> int:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe.""" ports = midiin.get_ports()
src = None i = pick_source(ports)
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"): if i is None:
src = _alsa_port(hint) raise SystemExit(
if src: "No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
break )
dst = _alsa_port("padcontroller-in") return i
if not src or not dst:
@dataclass
class AlsaPort:
addr: str # "client:port"
client: str
name: str
to: set[str] = field(default_factory=set)
sources: set[str] = field(default_factory=set)
def parse_aconnect(text: str) -> list[AlsaPort]:
"""The ports in `aconnect -l` output, with who they connect to and from."""
ports: list[AlsaPort] = []
client = client_name = None
for line in text.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = m.group(1), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if m and client is not None:
ports.append(AlsaPort(f"{client}:{m.group(1)}", client_name, m.group(2).strip()))
continue
m = re.match(r"\s+(Connecting To|Connected From):(.*)", line)
if m and ports:
addrs = set(re.findall(r"\d+:\d+", m.group(2)))
(ports[-1].to if m.group(1) == "Connecting To" else ports[-1].sources).update(addrs)
return ports
def missing_links(ports: list[AlsaPort], src_name: str | None) -> list[tuple[str, str]]:
"""(from, to) ALSA links the pad controller should have but doesn't.
The pad into padcontroller-in (Bluetooth MIDI sometimes drops it, and a replugged
USB pad comes back without it), and padcontroller out to every QLC+ client
(QLC+ only subscribes when it opens the port, so it loses it when we restart).
"""
links = []
ours_in = next((p for p in ports if p.client == "padcontroller-in"), None)
ours_out = next((p for p in ports if p.client == "padcontroller-out"), None)
m = re.search(r"(\d+:\d+)$", src_name or "")
if ours_in and m and m.group(1) not in ours_in.sources:
links.append((m.group(1), ours_in.addr))
if ours_out:
for p in ports:
if p.client == "qlcplus" and p.addr not in ours_out.to:
links.append((ours_out.addr, p.addr))
return links
def ensure_links(src_name: str | None) -> None:
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return return
subprocess.run(["aconnect", src, dst], capture_output=True) for src, dst in missing_links(parse_aconnect(out), src_name):
if subprocess.run(["aconnect", src, dst], capture_output=True).returncode == 0:
print(f"Linked {src} -> {dst}", flush=True)
def main() -> None: def main() -> None:
@@ -137,7 +168,7 @@ def main() -> None:
print(f"Source: {src_name}", flush=True) print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", 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) print("Pass notes through (Play held shifts bank 2 up 16); smooth CC. Ctrl+C to stop.", flush=True)
ensure_alsa_link() ensure_links(src_name)
if not args.no_lamps: if not args.no_lamps:
set_lamps() set_lamps()
@@ -149,7 +180,19 @@ def main() -> None:
while True: while True:
now = time.monotonic() now = time.monotonic()
if now >= next_link_check: if now >= next_link_check:
ensure_alsa_link() # Follow the pad: reopen it when it comes back, and move to USB when plugged in.
names = midiin.get_ports()
best = pick_source(names)
best_name = names[best] if best is not None else None
if best_name != src_name:
midiin.close_port()
if best is not None:
midiin.open_port(best)
print(f"Source: {best_name}", flush=True)
else:
print("Source: (pad gone, waiting)", flush=True)
src_name = best_name
ensure_links(src_name)
next_link_check = now + 2.0 next_link_check = now + 2.0
# Drain inbound # Drain inbound
+73
View File
@@ -0,0 +1,73 @@
"""padcontroller.midi: picking the pad's port and keeping the ALSA links up."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from padcontroller.midi import missing_links, parse_aconnect, pick_source # noqa: E402
BOTH = [
"Midi Through:Midi Through Port-0 14:0",
"SINCO:SINCO SMC-PAD-Private 20:0",
"SINCO:SINCO SMC-PAD-Master 20:1",
"SMC-PAD:SMC-PAD Bluetooth 128:0",
"padcontroller-out:padcontroller 130:0",
]
ACONNECT = """\
client 20: 'SINCO' [type=kernel,card=1]
0 'SINCO SMC-PAD-Private'
1 'SINCO SMC-PAD-Master'
\tConnecting To: 129:0
client 128: 'SMC-PAD' [type=user,pid=1153]
0 'SMC-PAD Bluetooth'
client 129: 'padcontroller-in' [type=user,pid=57888]
0 'RtMidi input '
\tConnected From: 20:1
client 130: 'padcontroller-out' [type=user,pid=57888]
0 'padcontroller '
client 131: 'qlcplus' [type=user,pid=57635]
0 '__QLC__ '
"""
def test_usb_wins_over_bluetooth():
assert BOTH[pick_source(BOTH)] == "SINCO:SINCO SMC-PAD-Master 20:1"
def test_bluetooth_when_unplugged():
names = [n for n in BOTH if "SINCO" not in n]
assert names[pick_source(names)] == "SMC-PAD:SMC-PAD Bluetooth 128:0"
def test_no_pad_and_never_our_own_port():
assert pick_source(["padcontroller-out:padcontroller 130:0"]) is None
def test_parse_aconnect_reads_links():
ports = {p.addr: p for p in parse_aconnect(ACONNECT)}
assert ports["20:1"].to == {"129:0"}
assert ports["129:0"].sources == {"20:1"}
assert ports["131:0"].client == "qlcplus"
def test_relinks_qlc_after_a_restart():
ports = parse_aconnect(ACONNECT)
assert missing_links(ports, "SINCO:SINCO SMC-PAD-Master 20:1") == [("130:0", "131:0")]
def test_relinks_a_replugged_pad_and_only_that_one():
ports = parse_aconnect(ACONNECT.replace("\tConnected From: 20:1\n", ""))
links = missing_links(ports, "SINCO:SINCO SMC-PAD-Master 20:1")
assert ("20:1", "129:0") in links
assert not any(src == "128:0" for src, _ in links)
def test_nothing_missing_when_linked():
text = ACONNECT.replace(" 0 'padcontroller '\n", " 0 'padcontroller '\n\tConnecting To: 131:0\n")
assert missing_links(parse_aconnect(text), "SINCO:SINCO SMC-PAD-Master 20:1") == []
assert missing_links(parse_aconnect(text), None) == []