midi: add CC29 tempo reset, CC37 brightness; local beat flag; logging\nsound: add control server with RESET_TEMPO; logging; always send BPM

This commit is contained in:
2025-09-14 04:53:24 +12:00
parent 3b869851b8
commit 9ff38aa875
2 changed files with 417 additions and 210 deletions

View File

@@ -1,132 +1,253 @@
import mido
import asyncio
import networking # <--- This will now correctly import your module
import networking
import socket
import json
import logging # Added logging import
# Configure logging
DEBUG_MODE = True # Set to False for INFO level logging
logging.basicConfig(level=logging.DEBUG if DEBUG_MODE else logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def midi_to_websocket_listener(midi_port_index: int, websocket_uri: str):
"""
Listens to a specific MIDI port and sends data to a WebSocket server
when Note 32 (and 33) is pressed.
"""
delay = 100 # Default delay value
# TCP Server Configuration
TCP_HOST = "127.0.0.1"
TCP_PORT = 65432
# 1. Get MIDI port name
# Sound Control Server Configuration (for sending reset)
SOUND_CONTROL_HOST = "127.0.0.1"
SOUND_CONTROL_PORT = 65433
class MidiHandler:
def __init__(self, midi_port_index: int, websocket_uri: str):
self.midi_port_index = midi_port_index
self.websocket_uri = websocket_uri
self.ws_client = networking.WebSocketClient(websocket_uri)
self.delay = 100 # Default delay value, controlled by MIDI controller
self.brightness = 100 # Default brightness value, controlled by MIDI controller
self.tcp_host = TCP_HOST
self.tcp_port = TCP_PORT
self.beat_sending_enabled = True # New: Local flag for beat sending
self.sound_control_host = SOUND_CONTROL_HOST
self.sound_control_port = SOUND_CONTROL_PORT
async def _send_reset_to_sound(self):
try:
reader, writer = await asyncio.open_connection(self.sound_control_host, self.sound_control_port)
cmd = "RESET_TEMPO\n".encode('utf-8')
writer.write(cmd)
await writer.drain()
resp = await reader.read(100)
logging.info(f"[MidiHandler - Control] Sent RESET_TEMPO, response: {resp.decode().strip()}")
writer.close()
await writer.wait_closed()
except Exception as e:
logging.error(f"[MidiHandler - Control] Failed to send RESET_TEMPO: {e}")
async def _handle_tcp_client(self, reader, writer):
addr = writer.get_extra_info('peername')
logging.info(f"[MidiHandler - TCP Server] Connected by {addr}") # Changed to info
try:
while True:
data = await reader.read(4096) # Read up to 4KB of data
if not data:
logging.info(f"[MidiHandler - TCP Server] Client {addr} disconnected.") # Changed to info
break
message = data.decode().strip()
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)
# Construct JSON message using the current MIDI-controlled delay and brightness
json_message = {
"names": ["0"],
"settings": {
"pattern": "pulse",
"delay": self.delay, # Use MIDI-controlled delay
"colors": ["#00ff00"],
"brightness": self.brightness,
"num_leds": 200,
},
}
logging.debug(f"[MidiHandler - TCP Server] Forwarding BPM-derived JSON message to WebSocket with delay {self.delay}, brightness {self.brightness}: {json_message}") # Changed to debug
await self.ws_client.send_data(json_message)
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
except asyncio.CancelledError:
logging.info(f"[MidiHandler - TCP Server] Client handler for {addr} cancelled.") # Changed to info
except Exception as e:
logging.error(f"[MidiHandler - TCP Server] Error handling client {addr}: {e}") # Changed to error
finally:
logging.info(f"[MidiHandler - TCP Server] Closing connection for {addr}") # Changed to info
writer.close()
await writer.wait_closed()
async def _midi_tcp_server(self):
server = await asyncio.start_server(
lambda r, w: self._handle_tcp_client(r, w), self.tcp_host, self.tcp_port)
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
logging.info(f"[MidiHandler - TCP Server] Serving on {addrs}") # Changed to info
async with server:
await server.serve_forever()
async def _midi_listener(self):
logging.info("Midi function") # Changed to info
"""
Listens to a specific MIDI port and sends data to a WebSocket server
when Note 32 (and 33) is pressed.
"""
# 1. Get MIDI port name
port_names = mido.get_input_names()
if not port_names:
logging.warning("No MIDI input ports found. Please connect your device.") # Changed to warning
return
if not (0 <= self.midi_port_index < len(port_names)):
logging.error(f"Error: MIDI port index {self.midi_port_index} out of range. Available ports: {port_names}") # Changed to error
logging.info("Available ports:") # Changed to info
for i, name in enumerate(port_names):
logging.info(f" {i}: {name}") # Changed to info
return
midi_port_name = port_names[self.midi_port_index]
logging.info(f"Selected MIDI input port: {midi_port_name}") # Changed to info
try:
with mido.open_input(midi_port_name) as port:
logging.info(f"MIDI port '{midi_port_name}' opened. Press Ctrl+C to stop.") # Changed to info
while True:
msg = port.receive(block=False) # Non-blocking read
if msg:
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
pattern_name = "Unknown"
match msg.note:
case 48: # Original Note 48 for 'pulse'
pattern_name = "pulse"
await self.ws_client.send_data({
"names": ["0"],
"settings": {
"pattern": pattern_name,
"delay": self.delay, # Use MIDI-controlled delay
"colors": ["#00ff00"],
"brightness": self.brightness,
"num_leds": 120,
}
})
case 49: # Original Note 49 for 'theater_chase'
pattern_name = "theater_chase"
await self.ws_client.send_data({
"names": ["0"],
"settings": {
"pattern": pattern_name,
"delay": self.delay, # Use MIDI-controlled delay
"colors": ["#00ff00"],
"brightness": self.brightness,
"num_leds": 120,
"on_width": 10,
"off_width": 10,
"n1": 0,
"n2": 100
}
})
case 50: # Original Note 50 for 'alternating'
pattern_name = "alternating"
logging.debug("Triggering Alternating Pattern") # Changed to debug
await self.ws_client.send_data({
"names": ["0"],
"settings": {
"pattern": pattern_name,
"delay": self.delay, # Use MIDI-controlled delay
"colors": ["#00ff00", "#0000ff"],
"brightness": self.brightness,
"num_leds": 120,
"n1": 10,
"n2": 10
}
})
case 'control_change':
match msg.control:
case 36:
self.delay = msg.value * 4 # Update instance delay
logging.info(f"Delay set to {self.delay} ms by MIDI controller") # Changed to info
case 27:
if msg.value == 127:
self.beat_sending_enabled = True
logging.info("[MidiHandler - Listener] Beat sending ENABLED by MIDI control.") # Changed to info
elif msg.value == 0:
self.beat_sending_enabled = False
logging.info("[MidiHandler - Listener] Beat sending DISABLED by MIDI control.") # Changed to info
case 29:
if msg.value == 127:
logging.info("[MidiHandler - Listener] RESET_TEMPO requested by control 29.")
await self._send_reset_to_sound()
case 37:
# 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")
await asyncio.sleep(0.001) # Important: Yield control to asyncio event loop
except mido.PortsError as e:
logging.error(f"Error opening MIDI port '{midi_port_name}': {e}") # Changed to error
except asyncio.CancelledError:
logging.info(f"MIDI listener cancelled.") # Changed to info
except Exception as e:
logging.error(f"An unexpected error occurred in MIDI listener: {e}") # Changed to error
async def run(self):
try:
await self.ws_client.connect()
logging.info(f"[MidiHandler] WebSocket client connected to {self.ws_client.uri}") # Changed to info
await asyncio.gather(
self._midi_listener(),
self._midi_tcp_server()
)
except mido.PortsError as e:
logging.error(f"[MidiHandler] Error opening MIDI port: {e}") # Changed to error
except asyncio.CancelledError:
logging.info("[MidiHandler] Tasks cancelled due to program shutdown.") # Changed to info
except KeyboardInterrupt:
logging.info("\n[MidiHandler] Program interrupted by user.") # Changed to info
finally:
logging.info("[MidiHandler] Main program finished. Closing WebSocket client...") # Changed to info
await self.ws_client.close()
logging.info("[MidiHandler] WebSocket client closed.") # Changed to info
def print_midi_ports():
logging.info("\n--- Available MIDI Input Ports ---") # Changed to info
port_names = mido.get_input_names()
if not port_names:
print("No MIDI input ports found. Please connect your device.")
return
if not (0 <= midi_port_index < len(port_names)):
print(f"Error: MIDI port index {midi_port_index} out of range. Available ports: {port_names}")
print("Available ports:")
logging.warning("No MIDI input ports found.") # Changed to warning
else:
for i, name in enumerate(port_names):
print(f" {i}: {name}")
return
midi_port_name = port_names[midi_port_index]
print(f"Selected MIDI input port: {midi_port_name}")
# 2. Initialize WebSocket client (using your actual networking.py)
ws_client = networking.WebSocketClient(websocket_uri)
try:
# 3. Connect WebSocket
await ws_client.connect()
print(f"WebSocket client connected to {ws_client.uri}")
# 4. Open MIDI port and start listening loop
with mido.open_input(midi_port_name) as port:
print(f"MIDI port '{midi_port_name}' opened. Press Ctrl+C to stop.")
while True:
msg = port.receive(block=False) # Non-blocking read
if msg:
match msg.type:
case 'note_on':
print(f" Note ON: Note={msg.note}, Velocity={msg.velocity}, Channel={msg.channel}")
# Add pattern_name variable to update a GUI later if needed.
pattern_name = "Unknown"
match msg.note:
case 48: # Original Note 48 for 'pulse'
pattern_name = "pulse"
await ws_client.send_data({
"names": ["1"],
"settings": {
"pattern": pattern_name,
"delay": delay,
"colors": ["#00ff00"],
"brightness": 100,
"num_leds": 120, # Corrected to 120
}
})
case 49: # Original Note 49 for 'theater_chase'
pattern_name = "theater_chase"
await ws_client.send_data({
"names": ["1"],
"settings": {
"pattern": pattern_name,
"delay": delay,
"colors": ["#00ff00"],
"brightness": 100,
"num_leds": 120,
"on_width": 10,
"off_width": 10,
"n1": 0,
"n2": 100
}
})
case 50: # Original Note 50 for 'alternating'
pattern_name = "alternating"
print("Triggering Alternating Pattern")
await ws_client.send_data({
"names": ["1"],
"settings": {
"pattern": pattern_name,
"delay": delay,
"colors": ["#00ff00", "#0000ff"],
"brightness": 100,
"num_leds": 120,
"n1": 10,
"n2": 10
}
})
# Potentially add logic here to use pattern_name if a GUI update is desired in the future
case 'control_change':
match msg.control:
case 36:
delay = msg.value * 4
print(f"Delay set to {delay} ms")
await asyncio.sleep(0.001) # Important: Yield control to asyncio event loop
except mido.PortsError as e:
print(f"Error opening MIDI port '{midi_port_name}': {e}")
except asyncio.CancelledError:
print(f"MIDI listener cancelled.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# 5. Disconnect WebSocket and clean up
# This assumes your WebSocketClient has a ._connected attribute or similar way to check state.
# If your client's disconnect method is safe to call even if not connected, you can simplify.
await ws_client.close()
print("MIDI listener stopped and cleaned up.")
logging.info(f" {i}: {name}") # Changed to info
logging.info("----------------------------------") # Changed to info
async def main():
print_midi_ports()
# --- Configuration ---
MIDI_PORT_INDEX = 1 # <--- IMPORTANT: Change this to the correct index for your device
WEBSOCKET_SERVER_URI = "ws://192.168.4.1:80/ws"
# --- End Configuration ---
try:
await midi_to_websocket_listener(MIDI_PORT_INDEX, WEBSOCKET_SERVER_URI)
except KeyboardInterrupt:
print("\nProgram interrupted by user.")
finally:
print("Main program finished.")
midi_handler = MidiHandler(MIDI_PORT_INDEX, WEBSOCKET_SERVER_URI)
await midi_handler.run()
if __name__ == "__main__":
asyncio.run(main())