From 4b0e71561584a86a1562707da7e793c5895944c4 Mon Sep 17 00:00:00 2001 From: dosas Date: Thu, 9 May 2024 21:17:49 +0200 Subject: [PATCH] Fix serial port midi disconnet bug disconnecting the serialport midi caused a program crash now the connection can be hot plugged --- samplerbox.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/samplerbox.py b/samplerbox.py index 7da715d..7552052 100644 --- a/samplerbox.py +++ b/samplerbox.py @@ -384,13 +384,23 @@ def display(s): if USE_SERIALPORT_MIDI: import serial - ser = serial.Serial(SERIALPORT_PORT, baudrate=SERIALPORT_BAUDRATE) def MidiSerialCallback(): message = [0, 0, 0] + ser = None while True: + if ser is None: + try: + ser = serial.Serial(SERIALPORT_PORT, baudrate=SERIALPORT_BAUDRATE) + except serial.serialutil.SerialException: + continue i = 0 - while i < 3: - data = ord(ser.read(1)) # read a byte + while i < 3 and ser is not None: + try: + data = ord(ser.read(1)) # read a byte + except serial.serialutil.SerialException: + ser = None + message = [0, 0, 0] + break if data >> 7 != 0: i = 0 # status byte! this is the beginning of a midi message: http://www.midi.org/techspecs/midimessages.php message[i] = data