The pad controller opened the pad's port as its input and closed it when the pad went, which stopped rtmidi reading at all, so virtual pad presses never reached QLC+ and the chases stayed on their starting blue. Its input is now a port of its own, open for the whole run, with the pad linked into it by aconnect (and the old link dropped when the pad moves between USB and Bluetooth). It also starts without the pad instead of exiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
325 lines
13 KiB
Python
325 lines
13 KiB
Python
"""Pad controller: intercept the SMC-PAD's MIDI and smooth its knob CCs so RGBW fades feel less stepped.
|
||
|
||
Reads the physical pad (Bluetooth or USB), passes pad notes through
|
||
immediately, and eases Control Change values toward their targets at
|
||
~120 Hz before emitting on a virtual port named "padcontroller".
|
||
|
||
On start it also sets the pad lamps over USB (scripts/pad/pad_lamps.py): bank 1 off and
|
||
bank 2 in the colours from shows/test.qxw. On Bluetooth it says so and carries on.
|
||
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
|
||
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 Bluetooth when that
|
||
turns up) and re-links QLC+ to the virtual port after a restart, so QLC+ can stay open.
|
||
|
||
QLC+ reopens its MIDI port when it loads a show, so a new link to QLC+ while
|
||
the pad controller runs means the show has just loaded with every button off.
|
||
That is a link the pad controller had to make, or one QLC+ made itself: a
|
||
restarted QLC+ subscribes to the virtual port on its own as it opens the show,
|
||
before the next check, so a QLC+ process or port fed that wasn't at the last
|
||
check counts too (qlc_feeds). REOPEN_DELAY later it presses the last colour pads
|
||
again (see PlayLayer.colours), which it keeps in COLOURS_FILE so they outlive a
|
||
restart of the pad controller.
|
||
|
||
When one of the movers' movement pads goes off, SETTLE_DELAY later it
|
||
nudges the Pan and Tilt knobs a step and puts them back, so QLC+ drops
|
||
the EFX's last offset (see PlayLayer.settle).
|
||
|
||
Usage:
|
||
.venv/bin/python -m padcontroller.midi
|
||
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
|
||
|
||
padcontroller/systemd/install.sh runs it as a systemd user service.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import math
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
from typing import Callable
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
import glob
|
||
|
||
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
|
||
sys.path.insert(0, p)
|
||
import rtmidi
|
||
|
||
from padcontroller.layer import LAMP_CHANNEL, PlayLayer # noqa: E402
|
||
|
||
# The lamp colours come from the show scripts, which are not part of this package.
|
||
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
|
||
from pad_lamps import set_lamps # noqa: E402
|
||
|
||
VIRTUAL_NAME = "padcontroller"
|
||
COLOURS_FILE = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "padcontroller" / "colours.json"
|
||
REOPEN_DELAY = 1.5 # s for QLC+ to finish loading the virtual console
|
||
SETTLE_DELAY = 0.1 # s for QLC+ to stop a relative EFX before the knob nudge, and between its two steps
|
||
RESTART_DELAY = 0.1 # s after a Colour 1 press before the can pattern's off tap, and between it and the on tap
|
||
# Bluetooth first when the pad is paired, USB otherwise.
|
||
SOURCE_HINTS = (
|
||
"SMC-PAD Bluetooth",
|
||
"SINCO SMC-PAD-Master",
|
||
"SINCO SMC-PAD-Private",
|
||
"SINCO",
|
||
"SMC-PAD",
|
||
)
|
||
|
||
|
||
def pick_source(names: list[str]) -> int | None:
|
||
"""Index of the best SMC-PAD port in names, or None when the pad is not there."""
|
||
for hint in SOURCE_HINTS:
|
||
for i, name in enumerate(names):
|
||
if hint in name and VIRTUAL_NAME not in name:
|
||
return i
|
||
return None
|
||
|
||
|
||
@dataclass
|
||
class AlsaPort:
|
||
addr: str # "client:port"
|
||
client: str
|
||
name: str
|
||
pid: str | None = None # the client's process, for user clients
|
||
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 = pid = None
|
||
for line in text.splitlines():
|
||
m = re.match(r"client (\d+): '([^']+)'(?:.*\bpid=(\d+))?", line)
|
||
if m:
|
||
client, client_name, pid = m.groups()
|
||
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(), pid))
|
||
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 qlc_feeds(ports: list[AlsaPort]) -> set[tuple[str | None, str]]:
|
||
"""(pid, address) of each QLC+ port the pad controller's output is linked to."""
|
||
ours_out = next((p for p in ports if p.client == "padcontroller-out"), None)
|
||
if ours_out is None:
|
||
return set()
|
||
return {(p.pid, p.addr) for p in ports if p.client == "qlcplus" and p.addr in ours_out.to}
|
||
|
||
|
||
def ensure_links(src_name: str | None) -> tuple[bool, set[tuple[str | None, str]]]:
|
||
"""Make the missing links. Whether one of them was to QLC+, and the QLC+ ports fed after."""
|
||
try:
|
||
out = subprocess.check_output(["aconnect", "-l"], text=True)
|
||
except (FileNotFoundError, subprocess.CalledProcessError):
|
||
return False, set()
|
||
ports = parse_aconnect(out)
|
||
qlc = {p.addr: p.pid for p in ports if p.client == "qlcplus"}
|
||
fed = qlc_feeds(ports)
|
||
to_qlc = False
|
||
for src, dst in missing_links(ports, src_name):
|
||
if subprocess.run(["aconnect", src, dst], capture_output=True).returncode == 0:
|
||
print(f"Linked {src} -> {dst}", flush=True)
|
||
if dst in qlc:
|
||
to_qlc = True
|
||
fed.add((qlc[dst], dst))
|
||
return to_qlc, fed
|
||
|
||
|
||
def unlink_source(src_name: str | None) -> None:
|
||
"""Take the pad's old port off padcontroller-in, so a pad moving from USB to Bluetooth isn't heard twice."""
|
||
m = re.search(r"(\d+:\d+)$", src_name or "")
|
||
if m:
|
||
subprocess.run(["aconnect", "-d", m.group(1), "padcontroller-in:0"], capture_output=True)
|
||
|
||
|
||
def load_colours(layer: PlayLayer) -> None:
|
||
try:
|
||
saved = json.loads(COLOURS_FILE.read_text())
|
||
layer.colours = {int(k): tuple(v) if v else None for k, v in saved.items()}
|
||
except (OSError, ValueError, TypeError):
|
||
pass
|
||
|
||
|
||
def save_colours(layer: PlayLayer) -> None:
|
||
try:
|
||
COLOURS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||
COLOURS_FILE.write_text(json.dumps(layer.colours) + "\n")
|
||
except OSError as exc:
|
||
print(f"Colours not saved: {exc}", flush=True)
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description=__doc__)
|
||
ap.add_argument(
|
||
"--tau",
|
||
type=float,
|
||
default=0.055,
|
||
help="smoothing time constant in seconds (default 0.055)",
|
||
)
|
||
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
|
||
ap.add_argument("--no-lamps", action="store_true", help="leave the pad lamp colours alone")
|
||
args = ap.parse_args()
|
||
|
||
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-in")
|
||
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-out")
|
||
|
||
names = midiin.get_ports()
|
||
src = pick_source(names)
|
||
src_name = names[src] if src is not None else None
|
||
# Our own input port, with the pad linked into it by ensure_links: it keeps reading while
|
||
# the pad is away (rtmidi stops reading when an opened port closes), so the virtual pad
|
||
# still gets through.
|
||
midiin.open_virtual_port("RtMidi input")
|
||
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
|
||
midiout.open_virtual_port(VIRTUAL_NAME)
|
||
|
||
# current/target as floats 0..127, keyed by (channel, cc)
|
||
current: dict[tuple[int, int], float] = {}
|
||
target: dict[tuple[int, int], float] = {}
|
||
last_sent: dict[tuple[int, int], int] = {}
|
||
layer = PlayLayer()
|
||
load_colours(layer)
|
||
saved_colours = dict(layer.colours)
|
||
reopen_at: float | None = None
|
||
# (when, messages to send then), for the settle after a mover EFX
|
||
later: list[tuple[float, Callable[[], list[list[int]]]]] = []
|
||
# Links made this soon after start are ours being restored, with QLC+'s buttons as they were.
|
||
reopen_from = time.monotonic() + 5.0
|
||
|
||
print(f"Source: {src_name or '(pad gone, waiting)'}", 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)
|
||
_, fed = ensure_links(src_name)
|
||
for out in layer.layer_lamp():
|
||
midiout.send_message(out)
|
||
if not args.no_lamps:
|
||
set_lamps()
|
||
|
||
dt = 1.0 / args.rate
|
||
alpha = 1.0 - math.exp(-dt / max(args.tau, 1e-4))
|
||
next_link_check = time.monotonic() + 2.0
|
||
|
||
try:
|
||
while True:
|
||
now = time.monotonic()
|
||
if now >= next_link_check:
|
||
# Follow the pad: reopen it when it comes back, and move to Bluetooth when paired.
|
||
names = midiin.get_ports()
|
||
best = pick_source(names)
|
||
best_name = names[best] if best is not None else None
|
||
if best_name != src_name:
|
||
unlink_source(src_name)
|
||
print(f"Source: {best_name or '(pad gone, waiting)'}", flush=True)
|
||
src_name = best_name
|
||
linked, now_fed = ensure_links(src_name)
|
||
if (linked or now_fed - fed) and now >= reopen_from:
|
||
reopen_at = now + REOPEN_DELAY
|
||
fed = now_fed
|
||
next_link_check = now + 2.0
|
||
|
||
if reopen_at is not None and now >= reopen_at:
|
||
reopen_at = None
|
||
taps = layer.reopen()
|
||
for out in taps:
|
||
midiout.send_message(out)
|
||
pressed = sum(out[0] & 0xF0 == 0x90 and out[0] & 0x0F != LAMP_CHANNEL for out in taps)
|
||
print(f"QLC+ reopened: pressed {pressed} colour pad(s) again", flush=True)
|
||
|
||
# Drain inbound
|
||
while True:
|
||
msg = midiin.get_message()
|
||
if msg is None:
|
||
break
|
||
data, _ = msg
|
||
if not data:
|
||
continue
|
||
for out in layer.handle(list(data)):
|
||
cmd = out[0] & 0xF0
|
||
if cmd == 0xB0 and len(out) >= 3:
|
||
# Control Change → smooth
|
||
key = (out[0] & 0x0F, out[1])
|
||
target[key] = float(out[2])
|
||
if key not in current:
|
||
current[key] = float(out[2])
|
||
last_sent[key] = -1
|
||
else:
|
||
# Notes, aftertouch, PC, etc. → immediate
|
||
midiout.send_message(out)
|
||
if layer.settle:
|
||
layer.settle = False
|
||
later += [(now + SETTLE_DELAY, layer.nudge), (now + 2 * SETTLE_DELAY, layer.positions)]
|
||
if layer.restart_pattern:
|
||
layer.restart_pattern = False
|
||
later += [(now + RESTART_DELAY, layer.pattern_tap), (now + 2 * RESTART_DELAY, layer.pattern_tap)]
|
||
for due in [item for item in later if now >= item[0]]:
|
||
later.remove(due)
|
||
for out in due[1]():
|
||
midiout.send_message(out)
|
||
if layer.colours != saved_colours:
|
||
save_colours(layer)
|
||
saved_colours = dict(layer.colours)
|
||
|
||
# Ease CC toward targets and emit when quantized value moves
|
||
for key, tgt in list(target.items()):
|
||
cur = current.get(key, tgt)
|
||
cur = cur + (tgt - cur) * alpha
|
||
# Snap when close so we actually reach the endpoint
|
||
if abs(tgt - cur) < 0.15:
|
||
cur = tgt
|
||
current[key] = cur
|
||
q = int(round(cur))
|
||
q = 0 if q < 0 else 127 if q > 127 else q
|
||
if last_sent.get(key) != q:
|
||
ch, cc = key
|
||
midiout.send_message([0xB0 | ch, cc, q])
|
||
last_sent[key] = q
|
||
|
||
time.sleep(dt)
|
||
except KeyboardInterrupt:
|
||
print("\nStopped.", flush=True)
|
||
finally:
|
||
midiin.close_port()
|
||
midiout.close_port()
|
||
del midiin
|
||
del midiout
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|