7 Commits

Author SHA1 Message Date
e5cf15d7b0 Fix rainbow pattern step range in lighting controller
- Change step calculation from beat_index % 2 to beat_index % 256
- Provides full 0-255 step range for rainbow pattern color cycling
- Fixes rainbow pattern that was limited to only 0 or 1 step values
- Alternating phase patterns still use % 2 for proper phase offset
2025-09-19 01:29:08 +12:00
c40b5629bf Fix pattern highlighting in lighting controller GUI
- Add pattern name mapping to translate between MIDI handler names and GUI display names
- Fixes highlighting for patterns with underscores (sequential_pulse, alternating_phase, n_chase)
- Now properly highlights selected patterns in the button grid
2025-09-19 01:15:29 +12:00
a4a00021d8 Fix missing n3 attribute and async function issue
- Add missing self.n3 = 1 attribute to MidiHandler initialization
- Fix update_rgb async function to properly yield control with await asyncio.sleep(0)
- Resolves TypeError about expecting coroutine but getting None
- Application now working properly with buttons and dials functional
2025-09-19 00:07:37 +12:00
f2dcdabf29 Fix indentation errors and reduce debug output
- Comment out all debug logging statements to reduce console noise
- Fix empty if/else blocks by adding pass statements
- Remove beat logging, TCP server logging, and MIDI debug messages
- Keep only essential info, warning, and error messages
- Revert radiate delay separation back to using main delay parameter
2025-09-19 00:02:51 +12:00
5f7db51851 Add rate-limited parameter updates and message type system
- Rate limit parameter updates to 100ms minimum interval
- Send immediate updates if rate limit allows, otherwise queue
- Process pending updates during beat handling
- All knob changes (CC30-37) now trigger parameter updates
- Add message type field: 'b' for beats, 'u' for updates
- Optimize message type to single letters to save packet space
- Prevents ESP-NOW network flooding during rapid knob adjustments
- All packets stay under 230-byte limit with automatic splitting
2025-09-18 22:11:17 +12:00
fcbe9e9094 Implement full parameter sending on pattern change and periodic updates
- Send all parameters when pattern changes (may require 2 packets if >200 bytes)
- Send periodic parameter updates every 8 beats to keep bars synchronized
- Beat packets remain minimal for performance
- All packets stay under 230-byte limit
2025-09-18 21:58:39 +12:00
36dfda74b2 Update GUI layout and MIDI CC mappings: CC36=n3, CC37=delay, remove B1/B2 references 2025-09-18 20:35:31 +12:00
3 changed files with 547 additions and 67 deletions

38
src/bar_config.py Normal file
View File

@@ -0,0 +1,38 @@
# LED Bar Configuration
# Modify these names as needed for your setup
# LED Bar Names/IDs - 4 left bars + 4 right bars
LED_BAR_NAMES = [
"100", # Left Bar 1
"101", # Left Bar 2
"102", # Left Bar 3
"103", # Left Bar 4
"104", # Right Bar 1
"105", # Right Bar 2
"106", # Right Bar 3
"107", # Right Bar 4
]
# Left and right bar groups for spatial control
LEFT_BARS = ["100", "101", "102", "103"]
RIGHT_BARS = ["104", "105", "106", "107"]
# Number of LED bars
NUM_BARS = len(LED_BAR_NAMES)
# Default settings for all bars
DEFAULT_BAR_SETTINGS = {
"pattern": "pulse",
"delay": 100,
"colors": [(0, 255, 0)], # Default green
"brightness": 10,
"num_leds": 200,
"n1": 10,
"n2": 10,
"n3": 1,
"n": 0,
}
# ESP-NOW broadcast settings
ESP_NOW_CHANNEL = 1
ESP_NOW_ENCRYPTION = False

View File

@@ -36,7 +36,9 @@ class App:
# --- MIDI Handler ---
MIDI_PORT_INDEX = 1 # Adjust as needed
WEBSOCKET_SERVER_URI = "ws://192.168.4.1:80/ws"
print(f"Initializing MIDI handler with port index {MIDI_PORT_INDEX}")
self.midi_handler = MidiHandler(MIDI_PORT_INDEX, WEBSOCKET_SERVER_URI)
print("MIDI handler initialized")
self.midi_task: asyncio.Task | None = None
# Start MIDI in background
self.root.after(0, async_handler(self.start_midi))
@@ -50,22 +52,134 @@ class App:
"TNotebook.Tab", background=bg_color, foreground=fg_color, font=("Arial", 30), padding=[10, 5]
)
# --- Status Frame ---
status_frame = ttk.Frame(self.root)
status_frame.pack(padx=16, pady=16, fill="x")
# (Status box removed per request)
self.lbl_delay = ttk.Label(status_frame, text="Delay: -")
self.lbl_brightness = ttk.Label(status_frame, text="Brightness: -")
self.lbl_r = ttk.Label(status_frame, text="R: -")
self.lbl_g = ttk.Label(status_frame, text="G: -")
self.lbl_b = ttk.Label(status_frame, text="B: -")
self.lbl_pattern = ttk.Label(status_frame, text="Pattern: -")
self.lbl_n1 = ttk.Label(status_frame, text="n1: -")
self.lbl_n2 = ttk.Label(status_frame, text="n2: -")
self.lbl_bpm = ttk.Label(status_frame, text="BPM: -")
# Controls overview (dials grid left, buttons grids right)
controls_frame = ttk.Frame(self.root)
controls_frame.pack(padx=16, pady=8, fill="both")
for w in (self.lbl_delay, self.lbl_brightness, self.lbl_r, self.lbl_g, self.lbl_b, self.lbl_pattern, self.lbl_n1, self.lbl_n2, self.lbl_bpm):
w.pack(anchor="w")
# Dials box: 4 rows by 2 columns (top-left origin):
# Row0: n3 (left), Delay (right)
# Row1: n1 (left), n2 (right)
# Row2: B (left), Brightness (right)
# Row3: R (left), G (right)
dials_frame = ttk.LabelFrame(controls_frame, text="Dials (CC30-37)")
dials_frame.pack(side="left", padx=12)
for c in range(2):
dials_frame.grid_columnconfigure(c, minsize=140)
for rr in range(4):
dials_frame.grid_rowconfigure(rr, minsize=70)
self.dials_boxes: list[tk.Label] = []
# Create with placeholders so they are visible before first update
placeholders = {
(0, 0): "n3\n-",
(0, 1): "Delay\n-",
(1, 0): "n1\n-",
(1, 1): "n2\n-",
(2, 0): "B\n-",
(2, 1): "Bright\n-",
(3, 0): "R\n-",
(3, 1): "G\n-",
}
for r in range(4):
for c in range(2):
lbl = tk.Label(
dials_frame,
text=placeholders.get((r, c), "-"),
bg=bg_color,
fg=fg_color,
font=("Arial", 14),
padx=6,
pady=6,
borderwidth=2,
relief="ridge",
width=14,
height=4,
anchor="center",
justify="center",
)
lbl.grid(row=r, column=c, padx=6, pady=6, sticky="nsew")
self.dials_boxes.append(lbl)
# Additional knobs box: 4 rows by 2 columns (CC38-45)
# Row0: K1 (left), K2 (right)
# Row1: K3 (left), K4 (right)
# Row2: K5 (left), K6 (right)
# Row3: K7 (left), K8 (right)
knobs_frame = ttk.LabelFrame(controls_frame, text="Knobs (CC38-45)")
knobs_frame.pack(side="left", padx=12)
for c in range(2):
knobs_frame.grid_columnconfigure(c, minsize=140)
for rr in range(4):
knobs_frame.grid_rowconfigure(rr, minsize=70)
self.knobs_boxes: list[tk.Label] = []
# Create with placeholders so they are visible before first update
knob_placeholders = {
(0, 0): "CC44\n-",
(0, 1): "CC45\n-",
(1, 0): "Rad n1\n-",
(1, 1): "Rad delay\n-",
(2, 0): "Alt n1\n-",
(2, 1): "Alt n2\n-",
(3, 0): "Pulse n1\n-",
(3, 1): "Pulse n2\n-",
}
for r in range(4):
for c in range(2):
lbl = tk.Label(
knobs_frame,
text=knob_placeholders.get((r, c), "-"),
bg=bg_color,
fg=fg_color,
font=("Arial", 14),
padx=6,
pady=6,
borderwidth=2,
relief="ridge",
width=14,
height=4,
anchor="center",
justify="center",
)
lbl.grid(row=r, column=c, padx=6, pady=6, sticky="nsew")
self.knobs_boxes.append(lbl)
# Buttons bank (single)
buttons_frame = ttk.Frame(controls_frame)
buttons_frame.pack(side="left", padx=12)
buttons1_frame = ttk.LabelFrame(buttons_frame, text="Buttons (notes 36-51)")
buttons1_frame.pack(side="top", pady=8)
for c in range(4):
buttons1_frame.grid_columnconfigure(c, minsize=140)
for rr in range(1, 5):
buttons1_frame.grid_rowconfigure(rr, minsize=70)
self.button1_cells: list[tk.Label] = []
for r in range(4):
for c in range(4):
lbl = tk.Label(
buttons1_frame,
text="",
bg=bg_color,
fg=fg_color,
font=("Arial", 14),
padx=6,
pady=6,
borderwidth=2,
relief="ridge",
width=14,
height=4,
anchor="center",
justify="center",
)
lbl.grid(row=1 + (3 - r), column=c, padx=6, pady=6, sticky="nsew")
self.button1_cells.append(lbl)
# (No second buttons bank)
# (No status labels to pack)
# schedule periodic UI updates
self.root.after(200, self.update_status_labels)
@@ -90,7 +204,7 @@ class App:
# --- Asynchronous Update Functions ---
@async_handler
async def update_rgb(self, tab):
pass
await asyncio.sleep(0) # Yield control
def update_status_labels(self):
# Pull values from midi_handler
@@ -99,21 +213,90 @@ class App:
r = getattr(self.midi_handler, 'color_r', 0)
g = getattr(self.midi_handler, 'color_g', 0)
b = getattr(self.midi_handler, 'color_b', 0)
# Single bank values
brightness = getattr(self.midi_handler, 'brightness', '-')
r = getattr(self.midi_handler, 'color_r', 0)
g = getattr(self.midi_handler, 'color_g', 0)
b = getattr(self.midi_handler, 'color_b', 0)
pattern = getattr(self.midi_handler, 'current_pattern', '') or '-'
n1 = getattr(self.midi_handler, 'n1', '-')
n2 = getattr(self.midi_handler, 'n2', '-')
bpm = getattr(self.midi_handler, 'current_bpm', None)
bpm_text = f"{bpm:.2f}" if isinstance(bpm, (float, int)) else "-"
n3 = getattr(self.midi_handler, 'n3', '-')
self.lbl_delay.config(text=f"Delay: {delay}")
self.lbl_brightness.config(text=f"Brightness: {brightness}")
self.lbl_r.config(text=f"R: {r}")
self.lbl_g.config(text=f"G: {g}")
self.lbl_b.config(text=f"B: {b}")
self.lbl_pattern.config(text=f"Pattern: {pattern}")
self.lbl_n1.config(text=f"n1: {n1}")
self.lbl_n2.config(text=f"n2: {n2}")
self.lbl_bpm.config(text=f"BPM: {bpm_text}")
# Update dials 2x4 grid (left→right, top→bottom):
# Row0: n3, Delay
# Row1: n1, n2
# Row2: B, Brightness
# Row3: R, G
dial_values = [
("n3", n3), ("Delay", getattr(self.midi_handler, 'delay', '-')),
("n1", n1), ("n2", n2),
("B", b), ("Brightness", brightness),
("R", r), ("G", g),
]
# Update dial displays
for idx, (label, value) in enumerate(dial_values):
if idx < len(self.dials_boxes):
self.dials_boxes[idx].config(text=f"{label}\n{value}")
# Update additional knobs (CC38-45)
knob_values = [
("CC44", getattr(self.midi_handler, 'knob7', '-')), ("CC45", getattr(self.midi_handler, 'knob8', '-')),
("Rad n1", getattr(self.midi_handler, 'n1', '-')), ("Rad delay", getattr(self.midi_handler, 'delay', '-')),
("Alt n1", getattr(self.midi_handler, 'n1', '-')), ("Alt n2", getattr(self.midi_handler, 'n2', '-')),
("Pulse n1", getattr(self.midi_handler, 'n1', '-')), ("Pulse n2", getattr(self.midi_handler, 'n2', '-')),
]
for idx, (label, value) in enumerate(knob_values):
if idx < len(self.knobs_boxes):
self.knobs_boxes[idx].config(text=f"{label}\n{value}")
# Update buttons bank mappings and selection (single bank)
# Pattern icons for nicer appearance
icon_for = {
"pulse": "💥",
"flicker": "",
"alternating": "↔️",
"n chase": "🏃",
"rainbow": "🌈",
"radiate": "🌟",
"sequential\npulse": "🔄",
"alternating\nphase": "",
"-": "",
}
bank1_patterns = [
# Pulse patterns (row 1)
"pulse", "sequential\npulse",
# Alternating patterns (row 2)
"alternating", "alternating\nphase",
# Chase/movement patterns (row 3)
"n chase", "rainbow",
# Effect patterns (row 4)
"flicker", "radiate",
"-", "-", "-", "-",
"-", "-", "-", "-",
]
# Map MIDI handler pattern names to GUI display names
pattern_name_mapping = {
"sequential_pulse": "sequential\npulse",
"alternating_phase": "alternating\nphase",
"n_chase": "n chase",
}
# Get the display name for the current pattern
display_pattern = pattern_name_mapping.get(pattern, pattern)
# notes numbers per cell (bottom-left origin)
for idx, lbl in enumerate(self.button1_cells):
name = bank1_patterns[idx]
sel = (display_pattern == name and name != "-")
icon = icon_for.get(name, "")
text = f"{icon} {name}" if name != "-" else ""
if sel:
lbl.config(text=text, bg=highlight_pattern_color)
else:
lbl.config(text=text, bg=bg_color)
# (no second bank to update)
# reschedule
self.root.after(200, self.update_status_labels)

View File

@@ -7,6 +7,19 @@ import logging # Added logging import
import time # Added for initial state read
import tkinter as tk
from tkinter import ttk, messagebox # Import messagebox for confirmations
from bar_config import LED_BAR_NAMES, DEFAULT_BAR_SETTINGS
# Pattern name mapping for shorter JSON payloads
PATTERN_NAMES = {
"flicker": "f",
"fill_range": "fr",
"n_chase": "nc",
"alternating": "a",
"pulse": "p",
"rainbow": "r",
"specto": "s",
"radiate": "rd",
}
# Configure logging
@@ -41,16 +54,194 @@ class MidiHandler:
# Raw CC-driven parameters (0-127)
self.n1 = 10
self.n2 = 10
self.n3 = 1
# Additional knobs (CC38-45)
self.knob1 = 0
self.knob2 = 0
self.knob3 = 0
self.knob4 = 0
self.knob5 = 0
self.knob6 = 0
self.knob7 = 0
self.knob8 = 0
# Current state for GUI display
self.current_bpm: float | None = None
self.current_pattern: str = ""
self.beat_index: int = 0
def _current_color_hex(self) -> str:
# Rate limiting for parameter updates
self.last_param_update: float = 0.0
self.param_update_interval: float = 0.1 # 100ms minimum between updates
self.pending_param_update: bool = False
# Sequential pulse pattern state
self.sequential_pulse_enabled: bool = False
self.sequential_pulse_step: int = 0
def _current_color_rgb(self) -> tuple:
r = max(0, min(255, int(self.color_r)))
g = max(0, min(255, int(self.color_g)))
b = max(0, min(255, int(self.color_b)))
return f"#{r:02x}{g:02x}{b:02x}"
return (r, g, b)
async def _handle_sequential_pulse(self):
"""Handle sequential pulse pattern: each bar pulses for 1 beat, then next bar, mirrored"""
from bar_config import LEFT_BARS, RIGHT_BARS
# Calculate which bar should pulse based on beat (1 beat per bar)
bar_index = self.beat_index % 4 # 0-3, cycles every 4 beats
# Create minimal payload - defaults to off
payload = {
"d": { # Defaults - off for all bars
"t": "b", # Message type: beat
"pt": "o", # off
}
}
# Set specific bars to pulse
left_bar = LEFT_BARS[bar_index]
right_bar = RIGHT_BARS[bar_index]
payload[left_bar] = {"pt": "p"} # pulse
payload[right_bar] = {"pt": "p"} # pulse
# logging.debug(f"[Sequential Pulse] Beat {self.beat_index}, pulsing bars {left_bar} and {right_bar}")
await self.ws_client.send_data(payload)
async def _handle_alternating_phase(self):
"""Handle alternating pattern with phase offset: every second bar uses different step"""
from bar_config import LED_BAR_NAMES
# Create minimal payload - same n1/n2 for all bars
payload = {
"d": { # Defaults - pattern and n1/n2
"t": "b", # Message type: beat
"pt": "a", # alternating
"n1": self.n1,
"n2": self.n2,
"s": self.beat_index % 2, # Default step for in-phase bars
}
}
# Set step offset for every second bar (bars 101, 103, 105, 107)
swap_bars = ["101", "103", "105", "107"]
for bar_name in LED_BAR_NAMES:
if bar_name in swap_bars:
# Send step offset for out-of-phase bars
payload[bar_name] = {"s": (self.beat_index + 1) % 2}
else:
# In-phase bars use defaults (no override needed)
payload[bar_name] = {}
# logging.debug(f"[Alternating Phase] Beat {self.beat_index}, step offset for bars {swap_bars}")
await self.ws_client.send_data(payload)
async def _send_full_parameters(self):
"""Send all parameters to bars - may require multiple packets due to size limit"""
from bar_config import LED_BAR_NAMES
# Calculate packet size for full parameters
full_payload = {
"d": {
"t": "u", # Message type: update
"pt": PATTERN_NAMES.get(self.current_pattern, self.current_pattern),
"dl": self.delay,
"cl": [self._current_color_rgb()],
"br": self.brightness,
"n1": self.n1,
"n2": self.n2,
"n3": self.n3,
"s": self.beat_index % 256, # Use full range for rainbow patterns
}
}
# Estimate size: ~200 bytes for defaults + 8 bars * 2 bytes = ~216 bytes
# This should fit in one packet, but let's be safe
payload_size = len(str(full_payload))
if payload_size > 200: # Split into 2 packets if too large
# Packet 1: Pattern and timing parameters
payload1 = {
"d": {
"t": "u", # Message type: update
"pt": PATTERN_NAMES.get(self.current_pattern, self.current_pattern),
"dl": self.delay,
"br": self.brightness,
}
}
for bar_name in LED_BAR_NAMES:
payload1[bar_name] = {}
# Packet 2: Color and pattern parameters
payload2 = {
"d": {
"t": "u", # Message type: update
"cl": [self._current_color_rgb()],
"n1": self.n1,
"n2": self.n2,
"n3": self.n3,
"s": self.beat_index % 2, # Keep step small (0 or 1) for alternating patterns
}
}
for bar_name in LED_BAR_NAMES:
payload2[bar_name] = {}
# logging.debug(f"[Full Params] Sending in 2 packets due to size ({payload_size} bytes)")
await self.ws_client.send_data(payload1)
await asyncio.sleep(0.01) # Small delay between packets
await self.ws_client.send_data(payload2)
else:
# Single packet
for bar_name in LED_BAR_NAMES:
full_payload[bar_name] = {}
# logging.debug(f"[Full Params] Sending single packet ({payload_size} bytes)")
await self.ws_client.send_data(full_payload)
async def _request_param_update(self):
"""Request a parameter update with rate limiting"""
import time
current_time = time.time()
if current_time - self.last_param_update >= self.param_update_interval:
# Can send immediately
self.last_param_update = current_time
await self._send_full_parameters()
# logging.debug("[Rate Limit] Parameter update sent immediately")
else:
# Rate limited - mark as pending
self.pending_param_update = True
# logging.debug("[Rate Limit] Parameter update queued (rate limited)")
async def _send_normal_pattern(self):
"""Send normal pattern to all bars - include required parameters"""
# Patterns that need specific parameters
patterns_needing_params = ["alternating", "flicker", "n_chase", "rainbow", "radiate"]
payload = {
"d": { # Defaults
"t": "b", # Message type: beat
"pt": PATTERN_NAMES.get(self.current_pattern, self.current_pattern),
}
}
# Add required parameters for patterns that need them
if self.current_pattern in patterns_needing_params:
payload["d"].update({
"n1": self.n1,
"n2": self.n2,
"n3": self.n3,
"dl": self.delay,
"s": self.beat_index % 256, # Use full range for rainbow patterns
})
# Add empty entries for each bar (they'll use defaults)
for bar_name in LED_BAR_NAMES:
payload[bar_name] = {}
# logging.debug(f"[Beat] Triggering '{self.current_pattern}' for {len(LED_BAR_NAMES)} bars")
await self.ws_client.send_data(payload)
async def _send_reset_to_sound(self):
try:
@@ -77,38 +268,48 @@ class MidiHandler:
break
message = data.decode().strip()
logging.debug(f"[MidiHandler - TCP Server] Received from {addr}: {message}") # Changed to debug
# logging.debug(f"[MidiHandler - TCP Server] Received from {addr}: {message}") # Changed to debug
if self.beat_sending_enabled:
try:
# Attempt to parse as float (BPM) from sound.py
bpm_value = float(message)
self.current_bpm = bpm_value
# On each beat, trigger currently selected pattern
# On each beat, trigger currently selected pattern(s)
if not self.current_pattern:
logging.debug("[Beat] No pattern selected yet; ignoring beat")
pass # No pattern selected yet; ignoring beat
else:
payload = {
"0": {
"pattern": self.current_pattern,
"delay": self.delay,
"colors": [self._current_color_hex()],
"brightness": self.brightness,
"num_leds": 200,
"n1": self.n1,
"n2": self.n2,
"n": self.beat_index,
}
}
self.beat_index = (self.beat_index + 1) % 1000000
logging.debug(f"[Beat] Triggering pattern '{self.current_pattern}' with payload: {payload}")
await self.ws_client.send_data(payload)
# Send periodic parameter updates every 8 beats
if self.beat_index % 8 == 0:
await self._send_full_parameters()
# Check for pending parameter updates (rate limited)
if self.pending_param_update:
import time
current_time = time.time()
if current_time - self.last_param_update >= self.param_update_interval:
self.last_param_update = current_time
self.pending_param_update = False
await self._send_full_parameters()
# logging.debug("[Rate Limit] Pending parameter update sent")
if self.current_pattern == "sequential_pulse":
# Sequential pulse pattern: each bar pulses for 1 beat, then next bar, mirrored
await self._handle_sequential_pulse()
elif self.current_pattern == "alternating_phase":
# Alternating pattern with phase offset: every second bar is out of phase
await self._handle_alternating_phase()
elif self.current_pattern:
# Normal pattern mode - run on all bars
await self._send_normal_pattern()
except ValueError:
logging.warning(f"[MidiHandler - TCP Server] Received non-BPM message from {addr}, not forwarding: {message}") # Changed to warning
except Exception as e:
logging.error(f"[MidiHandler - TCP Server] Error processing received message from {addr}: {e}") # Changed to error
else:
logging.debug(f"[MidiHandler - TCP Server] Beat received from {addr} but sending to WebSocket is disabled: {message}") # Changed to debug
pass # Beat sending disabled
except asyncio.CancelledError:
logging.info(f"[MidiHandler - TCP Server] Client handler for {addr} cancelled.") # Changed to info
@@ -136,8 +337,14 @@ class MidiHandler:
msg = port.receive(block=False)
if msg and msg.type == 'control_change':
if msg.control == 36:
self.n3 = max(1, msg.value)
logging.info(f"[Init] n3 set to {self.n3} from CC36")
elif msg.control == 37:
self.delay = msg.value * 4
logging.info(f"[Init] Delay set to {self.delay} ms from CC36")
logging.info(f"[Init] Delay set to {self.delay} ms from CC37")
elif msg.control == 39:
self.delay = msg.value * 4
logging.info(f"[Init] Delay set to {self.delay} ms from CC39")
elif msg.control == 33:
self.brightness = round((msg.value / 127) * 100)
logging.info(f"[Init] Brightness set to {self.brightness} from CC33")
@@ -191,39 +398,78 @@ class MidiHandler:
while True:
msg = port.receive(block=False) # Non-blocking read
if msg:
logging.debug(msg) # Changed to debug
# logging.debug(msg) # Changed to debug
match msg.type:
case 'note_on':
logging.debug(f" Note ON: Note={msg.note}, Velocity={msg.velocity}, Channel={msg.channel}") # Changed to debug
# Bind patterns starting at MIDI note 36
pattern_bindings: list[tuple[str, dict]] = [
("pulse", {"n1": 120, "n2": 120}),
("flicker", {}),
("alternating", {"n1": 6, "n2": 6}),
("n_chase", {"n1": 5, "n2": 5}),
("fill_range", {"n1": 10, "n2": 20}),
("rainbow", {}),
("specto", {"n1": 20}),
("radiate", {"n1": 8}),
# logging.debug(f" Note ON: Note={msg.note}, Velocity={msg.velocity}, Channel={msg.channel}") # Changed to debug
# Bank1 patterns starting at MIDI note 36
pattern_bindings: list[str] = [
# Pulse patterns (row 1)
"pulse",
"sequential_pulse",
# Alternating patterns (row 2)
"alternating",
"alternating_phase",
# Chase/movement patterns (row 3)
"n_chase",
"rainbow",
# Effect patterns (row 4)
"flicker",
"radiate",
]
idx = msg.note - 36
if 0 <= idx < len(pattern_bindings):
pattern_name, extra = pattern_bindings[idx]
pattern_name = pattern_bindings[idx]
self.current_pattern = pattern_name
# Apply any immediate param tweaks from binding to local state
if "n1" in extra:
self.n1 = extra["n1"]
if "n2" in extra:
self.n2 = extra["n2"]
logging.info(f"[Select] Pattern selected via note {msg.note}: {self.current_pattern} (n1={self.n1}, n2={self.n2})")
# Send full parameters when pattern changes
await self._send_full_parameters()
else:
logging.debug(f"Note {msg.note} not bound to a pattern (base 36, {len(pattern_bindings)} entries)")
pass # Note not bound to patterns
case 'control_change':
match msg.control:
case 36:
self.n3 = max(1, msg.value) # Update n3 step rate
logging.info(f"n3 set to {self.n3} by MIDI controller (CC36)")
await self._request_param_update()
case 37:
self.delay = msg.value * 4 # Update instance delay
logging.info(f"Delay set to {self.delay} ms by MIDI controller") # Changed to info
logging.info(f"Delay set to {self.delay} ms by MIDI controller (CC37)")
await self._request_param_update()
case 38:
self.n1 = msg.value # pulse n1 for pulse patterns
logging.info(f"Pulse n1 set to {self.n1} by MIDI controller (CC38)")
await self._request_param_update()
case 39:
self.n2 = msg.value # pulse n2 for pulse patterns
logging.info(f"Pulse n2 set to {self.n2} by MIDI controller (CC39)")
await self._request_param_update()
case 40:
self.n1 = msg.value # n1 for alternating patterns
logging.info(f"Alternating n1 set to {self.n1} by MIDI controller (CC40)")
await self._request_param_update()
case 41:
self.n2 = msg.value # n2 for alternating patterns
logging.info(f"Alternating n2 set to {self.n2} by MIDI controller (CC41)")
await self._request_param_update()
case 42:
self.n1 = msg.value # radiate n1 for radiate patterns
logging.info(f"Radiate n1 set to {self.n1} by MIDI controller (CC42)")
await self._request_param_update()
case 43:
self.delay = msg.value * 4 # delay for radiate patterns
logging.info(f"Delay set to {self.delay} ms by MIDI controller (CC43)")
await self._request_param_update()
case 44:
self.knob7 = msg.value
logging.info(f"Knob7 set to {self.knob7} by MIDI controller (CC44)")
await self._request_param_update()
case 45:
self.knob8 = msg.value
logging.info(f"Knob8 set to {self.knob8} by MIDI controller (CC45)")
await self._request_param_update()
case 27:
if msg.value == 127:
self.beat_sending_enabled = True
@@ -239,24 +485,30 @@ class MidiHandler:
# Map 0-127 to 0-100 brightness scale
self.brightness = round((msg.value / 127) * 100)
logging.info(f"Brightness set to {self.brightness} by MIDI controller (CC33)")
await self._request_param_update()
case 30:
# Red 0-127 -> 0-255
self.color_r = round((msg.value / 127) * 255)
logging.info(f"Red set to {self.color_r}")
await self._request_param_update()
case 31:
# Green 0-127 -> 0-255
self.color_g = round((msg.value / 127) * 255)
logging.info(f"Green set to {self.color_g}")
await self._request_param_update()
case 32:
# Blue 0-127 -> 0-255
self.color_b = round((msg.value / 127) * 255)
logging.info(f"Blue set to {self.color_b}")
await self._request_param_update()
case 34:
self.n1 = int(msg.value)
logging.info(f"n1 set to {self.n1} by MIDI controller (CC34)")
await self._request_param_update()
case 35:
self.n2 = int(msg.value)
logging.info(f"n2 set to {self.n2} by MIDI controller (CC35)")
await self._request_param_update()
await asyncio.sleep(0.001) # Important: Yield control to asyncio event loop
@@ -271,6 +523,10 @@ class MidiHandler:
try:
await self.ws_client.connect()
logging.info(f"[MidiHandler] WebSocket client connected to {self.ws_client.uri}") # Changed to info
# List available MIDI ports for debugging
print(f"Available MIDI input ports: {mido.get_input_names()}")
print(f"Trying to open MIDI port index {self.midi_port_index}")
await asyncio.gather(
self._midi_listener(),
@@ -278,6 +534,9 @@ class MidiHandler:
)
except mido.PortsError as e:
logging.error(f"[MidiHandler] Error opening MIDI port: {e}") # Changed to error
print(f"MIDI Port Error: {e}")
print(f"Available MIDI ports: {mido.get_input_names()}")
print("Please check your MIDI device connection and port index")
except asyncio.CancelledError:
logging.info("[MidiHandler] Tasks cancelled due to program shutdown.") # Changed to info
except KeyboardInterrupt: