-
Notifications
You must be signed in to change notification settings - Fork 14
/
serialmidi.py
195 lines (157 loc) · 5.54 KB
/
serialmidi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import time
import queue
import rtmidi
import serial
import threading
import logging
import sys
import time
import argparse
# Serial MIDI Bridge
# Ryan Kojima
parser = argparse.ArgumentParser(description = "Serial MIDI bridge")
parser.add_argument("--serial_name", type=str, required = True, help = "Serial port name. Required")
parser.add_argument("--baud", type=int, default=115200, help = "baud rate. Default is 115200")
parser.add_argument("--midi_in_name", type=str, default = "IAC Bus 1")
parser.add_argument("--midi_out_name", type=str, default = "IAC Bus 2")
parser.add_argument("--debug", action = "store_true", help = "Print incoming / outgoing MIDI signals")
parser.add_argument("--string", action = "store_true", help = "Print sysEx logging message (For Qun Mk2)")
args = parser.parse_args()
thread_running = True
# Arguments
serial_port_name = args.serial_name #'/dev/cu.SLAB_USBtoUART'
serial_baud = args.baud
given_port_name_in = args.midi_in_name #"IAC Bus 1"
given_port_name_out = args.midi_out_name #"IAC Bus 2"
if args.debug:
logging.basicConfig(level = logging.DEBUG)
else:
logging.basicConfig(level = logging.INFO)
midi_ready = False
midiin_message_queue = queue.Queue()
midiout_message_queue = queue.Queue()
def get_midi_length(message):
if len(message) == 0:
return 100
opcode = message[0]
if opcode >= 0xf4:
return 1
if opcode in [ 0xf1, 0xf3 ]:
return 2
if opcode == 0xf2:
return 3
if opcode == 0xf0:
if message[-1] == 0xf7:
return len(message)
opcode = opcode & 0xf0
if opcode in [ 0x80, 0x90, 0xa0, 0xb0, 0xe0 ]:
return 3
if opcode in [ 0xc0, 0xd0 ]:
return 2
return 100
def serial_writer():
while midi_ready == False:
time.sleep(0.1)
while thread_running:
try:
message = midiin_message_queue.get(timeout=0.4)
except queue.Empty:
continue
logging.debug(message)
value = bytearray(message)
ser.write(value)
def serial_watcher():
receiving_message = []
running_status = 0
while midi_ready == False:
time.sleep(0.1)
while thread_running:
data = ser.read()
if data:
for elem in data:
receiving_message.append(elem)
#Running status
if len(receiving_message) == 1:
if (receiving_message[0]&0xf0) != 0:
running_status = receiving_message[0]
else:
receiving_message = [ running_status, receiving_message[0] ]
message_length = get_midi_length(receiving_message)
if message_length <= len(receiving_message):
logging.debug(receiving_message)
midiout_message_queue.put(receiving_message)
if args.string:
if receiving_message[0] == 0xf0:
print_message = []
for elem in receiving_message:
if elem < 0xf0:
print_message.append(chr(elem))
print_message_str = ''.join(print_message)
print(print_message_str)
receiving_message = []
class midi_input_handler(object):
def __init__(self, port):
self.port = port
self._wallclock = time.time()
def __call__(self, event, data=None):
message, deltatime = event
self._wallclock += deltatime
#logging.debug("[%s] @%0.6f %r" % (self.port, self._wallclock, message))
midiin_message_queue.put(message)
def midi_watcher():
global midi_ready, thread_running
midiin = rtmidi.MidiIn()
midiout = rtmidi.MidiOut()
available_ports_out = midiout.get_ports()
available_ports_in = midiin.get_ports()
logging.info("IN : '" + "','".join(available_ports_in) + "'")
logging.info("OUT : '" + "','".join(available_ports_out) + "'")
logging.info("Hit ctrl-c to exit")
port_index_in = -1
port_index_out = -1
for i, s in enumerate(available_ports_in):
if given_port_name_in in s:
port_index_in = i
for i, s in enumerate(available_ports_out):
if given_port_name_out in s:
port_index_out = i
if port_index_in == -1:
print("MIDI IN Device name is incorrect. Please use listed device name.")
if port_index_out == -1:
print("MIDI OUT Device name is incorrect. Please use listed device name.")
if port_index_in == -1 or port_index_out == -1:
thread_running = False
midi_ready = True
sys.exit()
midiout.open_port(port_index_out)
in_port_name = midiin.open_port(port_index_in)
midi_ready = True
midiin.ignore_types(sysex = False, timing = False, active_sense = False)
midiin.set_callback(midi_input_handler(in_port_name))
while thread_running:
try:
message = midiout_message_queue.get(timeout = 0.4)
except queue.Empty:
continue
midiout.send_message(message)
try:
ser = serial.Serial(serial_port_name,serial_baud)
except serial.serialutil.SerialException:
print("Serial port opening error.")
midi_watcher()
sys.exit()
ser.timeout = 0.4
s_watcher = threading.Thread(target = serial_watcher)
s_writer = threading.Thread(target = serial_writer)
m_watcher = threading.Thread(target = midi_watcher)
s_watcher.start()
s_writer.start()
m_watcher.start()
#Ctrl-C handler
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Terminating.")
thread_running = False
sys.exit(0)