Move the SMC-PAD MIDI intercept into padeditor and add a systemd user service with an installer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-22 12:06:31 +13:00
1 parent 647cfa3a75
commit 00de2595b6
13 files changed
+127 -34

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
.venv/bin/python scripts/pad/pad_lamps.py
Needs the USB Private port. smooth_smc_pad.py does this on start; run this
Needs the USB Private port. padeditor.intercept does this on start; run this
when the pad is read by Chataigne instead.
"""
-64
View File
@@ -1,64 +0,0 @@
"""Hold Play to move the bank 2 pads up a layer.
The SMC-PAD sends CC 27 as 127 when Play goes down and 0 when it comes up.
While it is down, pad notes 52–67 go out as 68–83, so QLC+ can tell a
second set of buttons from the first. Play itself is not passed on.
With lock_knobs, knobs 1–5 (CC 30–34) drive colour 1's sliders and knobs 6–10
(CC 35–39) drive colour 2's, but only after the Custom pad (note 67, or 83
with Play held) has been pressed. Pressing any other bank 2 pad locks them
again, and its sliders are sent back to zero so their scenes stop.
Locked knob turns are dropped.
"""
from __future__ import annotations
PLAY_CC = 27
FIRST_NOTE = 52
LAST_NOTE = 67
SHIFT = 16
CUSTOM_NOTE = 67
KNOB_FIRST_CC = 30
KNOBS_PER_LAYER = 5
class PlayLayer:
def __init__(self, lock_knobs: bool = False) -> None:
self.lock_knobs = lock_knobs
self.unlocked: set[int] = set() # layers 0 and 1
self.held = False
# (channel, note as pressed) -> note sent, so a release matches its press
self.sent: dict[tuple[int, int], int] = {}
def handle(self, data: list[int]) -> list[list[int]]:
"""The messages to send on. Empty when the message is swallowed."""
status = data[0]
kind = status & 0xF0
channel = status & 0x0F
if kind == 0xB0 and len(data) >= 3 and data[1] == PLAY_CC:
self.held = data[2] > 0
return []
if kind == 0xB0 and len(data) >= 3 and self.lock_knobs:
index = data[1] - KNOB_FIRST_CC
if 0 <= index < 2 * KNOBS_PER_LAYER and index // KNOBS_PER_LAYER not in self.unlocked:
return []
if kind not in (0x80, 0x90) or len(data) < 3:
return [list(data)]
note = data[1]
key = (channel, note)
is_on = kind == 0x90 and data[2] > 0
extra: list[list[int]] = []
if is_on and FIRST_NOTE <= note <= LAST_NOTE:
layer = 1 if self.held else 0
if note == CUSTOM_NOTE:
self.unlocked.add(layer)
elif layer in self.unlocked:
self.unlocked.discard(layer)
first = KNOB_FIRST_CC + layer * KNOBS_PER_LAYER
extra = [[0xB0, first + n, 0] for n in range(KNOBS_PER_LAYER)]
if is_on:
out = note + SHIFT if self.held and FIRST_NOTE <= note <= LAST_NOTE else note
self.sent[key] = out
else:
out = self.sent.pop(key, note)
return [[status, out, *data[2:]], *extra]
+1 -1
View File
@@ -75,7 +75,7 @@ PAD_COLORS = [
def detect_midi_uid() -> str:
"""Prefer smoothed virtual port when the smoother daemon is running."""
"""Prefer smoothed virtual port when the intercept (padeditor.intercept) is running."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
-199
View File
@@ -1,199 +0,0 @@
#!/usr/bin/env python3
"""Smooth SMC-PAD 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 "SMC-PAD Smooth".
On start it also sets the pad lamps over USB (pad_colours.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 pad_layer.py).
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the smoother is running).
Usage:
.venv/bin/python scripts/pad/smooth_smc_pad.py
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
sys.path.insert(0, str(Path(__file__).resolve().parent))
from pad_lamps import set_lamps # noqa: E402
from pad_layer import PlayLayer # noqa: E402
VIRTUAL_NAME = "SMC-PAD Smooth"
SOURCE_HINTS = (
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
"SMC-PAD",
)
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
for hint in SOURCE_HINTS:
for i, name in enumerate(ports):
if hint in name and VIRTUAL_NAME not in name:
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
def ensure_alsa_link() -> None:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe."""
src = None
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"):
src = _alsa_port(hint)
if src:
break
dst = _alsa_port("smc-smooth-in")
if not src or not dst:
return
subprocess.run(["aconnect", src, dst], capture_output=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(
"--lock-knobs",
action="store_true",
help="knobs 1-10 move test.qxw's custom sliders only after the Custom pad is pressed",
)
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="smc-smooth-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
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(lock_knobs=args.lock_knobs)
print(f"Source: {src_name}", 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)
ensure_alsa_link()
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:
ensure_alsa_link()
next_link_check = now + 2.0
# 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)
# 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()
+22 -9
View File
@@ -3,7 +3,7 @@
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) smoother (creates "SMC-PAD Smooth")
# 2) intercept (creates "SMC-PAD Smooth")
# 3) patch workspace to that port
# 4) open QLC+ last
set -euo pipefail
@@ -30,12 +30,21 @@ if ! pad_present; then
exit 1
fi
# Restart smoother so it re-opens the pad port cleanly (avoid pkill -f; it matches this script)
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/[.]venv\/bin\/python .*smooth_smc_pad[.]py/ {print $1}')
sleep 0.4
nohup "$PYTHON" scripts/pad/smooth_smc_pad.py --tau 0.055 >>/tmp/smooth_smc_pad.log 2>&1 &
# Restart the intercept so it re-opens the pad port cleanly. Use the systemd
# user service when it is installed (padeditor/systemd/install.sh).
SERVICE=smc-pad-intercept.service
LOG=/tmp/smc_pad_intercept.log
if systemctl --user is-enabled --quiet "$SERVICE" 2>/dev/null; then
systemctl --user restart "$SERVICE"
LOG=
else
# avoid pkill -f; it matches this script
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/python.* -m padeditor[.]intercept/ {print $1}')
sleep 0.4
nohup "$PYTHON" -m padeditor.intercept --tau 0.055 >>"$LOG" 2>&1 &
fi
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
break
@@ -43,8 +52,12 @@ for _ in $(seq 1 20); do
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
echo "Smoother failed to create SMC-PAD Smooth. See /tmp/smooth_smc_pad.log" >&2
tail -20 /tmp/smooth_smc_pad.log >&2 || true
echo "The intercept failed to create SMC-PAD Smooth." >&2
if [[ -n "$LOG" ]]; then
tail -20 "$LOG" >&2 || true
else
journalctl --user -u "$SERVICE" -n 20 --no-pager >&2 || true
fi
exit 1
fi
+5 -5
View File
@@ -4,15 +4,15 @@
Colour 1 paints all 15 cans and colour 2 the four movers, so one colour
for each can be on at once. Each set is a solo frame and every scene
fades in and out over FADE_MS. Bank 2 (notes 52–67) picks colour 1.
Holding Play picks set B: the smoother turns those notes into 68–83 while
Holding Play picks set B: the intercept turns those notes into 68–83 while
Play is down. Bank 1 is kept for animations.
python3 scripts/shows/colour_sets.py && python3 -m showfile write shows/test.show.json -o shows/test.qxw
The sliders are Playback sliders over five scenes per set (Dim, R, G, B, W),
so they never override a channel. Knobs 1–5 move colour 1's sliders and knobs
6–10 colour 2's. Run the smoother with --lock-knobs to make them work only
6–10 colour 2's. Run the intercept with --lock-knobs to make them work only
after the Custom pad is pressed; any other pad sends them back to zero (see
pad_layer.py).
padeditor/layer.py).
"""
from __future__ import annotations
@@ -26,12 +26,12 @@ SPEC = ROOT / "shows" / "test.show.json"
FADE_MS = 1000
DIMMER, RED, GREEN, BLUE, WHITE = 0, 2, 3, 4, 5
PAD_BANK_2_FIRST_NOTE = 52
HELD_FIRST_NOTE = 68 # scripts/pad/pad_layer.py sends bank 2 here while Play is held
HELD_FIRST_NOTE = 68 # padeditor/layer.py sends bank 2 here while Play is held
PROFILE = "M-VAVE SMC-PAD"
OMNI = 16 # QLC+ MIDI plugin channel that accepts every MIDI channel
PAD_MIDI_CH = 9 # the pads send notes on channel 10
KNOB_FIRST_CC = 30 # pad knob 1; colour 2's sliders follow colour 1's
PAD_PORT = "SMC-PAD Smooth" # scripts/pad/smooth_smc_pad.py; it applies the Play layer
PAD_PORT = "SMC-PAD Smooth" # padeditor/intercept.py; it applies the Play layer
# name, r, g, b, w. Bottom row first, four to a row. The cans have a white emitter, so the whites use it.
COLOURS = (