import mido
from socketer import MASM

inPort = None
doReadInput = False

def Start():
	global inPort
	try:
		print(f"MIDI inputs: {mido.get_input_names()}")
		inPort = mido.open_input()
		print(f"MIDI input open: {inPort}")
	except Exception as e:
		inPort = None
		print(f"Could not open MIDI input: {e}")

def Update():
	global inPort
	global doReadInput
	if inPort is not None:
		if doReadInput and MASM.hasDataBool("MIDI_STOP"):
			doReadInput = False
		elif not doReadInput and MASM.hasDataBool("MIDI_START"):
			doReadInput = True
		for msg in inPort.iter_pending():
			if MASM.hasDataCheck("MIDI_KEYMAPKEY"):
				bytes = msg.bytes()
				if len(bytes) >= 3:
					MASM.hasDataBool("MIDI_KEYMAPKEY")
					MASM.sendData("MIDI_KEY", bytes[1])
			elif doReadInput: # We want to clear old pending messages but not send them if input is disabled
				bytes = msg.bytes()
				if len(bytes) >= 3:
					if bytes[0] == 144 and bytes[2] > 0:
						MASM.sendData(f"MIDI_NOTE.{bytes[1]}", bytes[2])
					elif bytes[0] == 128 or bytes[2] == 0:
						MASM.sendData(f"MIDI_NOTE.{bytes[1]}", 0)
[((11, 11, 11, 28), 'mido.open_input', 'mido.open_input', ({}, {}), '()', False, 'import mido\n'), ((21, 21, 21, 50), 'socketer.MASM.hasDataBool', 'MASM.hasDataBool', ({(21, 38, 21, 49): '"""MIDI_STOP"""'}, {}), "('MIDI_STOP')", False, 'from socketer import MASM\n'), ((26, 6, 26, 41), 'socketer.MASM.hasDataCheck', 'MASM.hasDataCheck', ({(26, 24, 26, 40): '"""MIDI_KEYMAPKEY"""'}, {}), "('MIDI_KEYMAPKEY')", False, 'from socketer import MASM\n'), ((23, 27, 23, 57), 'socketer.MASM.hasDataBool', 'MASM.hasDataBool', ({(23, 44, 23, 56): '"""MIDI_START"""'}, {}), "('MIDI_START')", False, 'from socketer import MASM\n'), ((10, 24, 10, 46), 'mido.get_input_names', 'mido.get_input_names', ({}, {}), '()', False, 'import mido\n'), ((29, 5, 29, 39), 'socketer.MASM.hasDataBool', 'MASM.hasDataBool', ({(29, 22, 29, 38): '"""MIDI_KEYMAPKEY"""'}, {}), "('MIDI_KEYMAPKEY')", False, 'from socketer import MASM\n'), ((30, 5, 30, 40), 'socketer.MASM.sendData', 'MASM.sendData', ({(30, 19, 30, 29): '"""MIDI_KEY"""', (30, 31, 30, 39): 'bytes[1]'}, {}), "('MIDI_KEY', bytes[1])", False, 'from socketer import MASM\n'), ((35, 6, 35, 54), 'socketer.MASM.sendData', 'MASM.sendData', ({(35, 20, 35, 43): 'f"""MIDI_NOTE.{bytes[1]}"""', (35, 45, 35, 53): 'bytes[2]'}, {}), "(f'MIDI_NOTE.{bytes[1]}', bytes[2])", False, 'from socketer import MASM\n'), ((37, 6, 37, 47), 'socketer.MASM.sendData', 'MASM.sendData', ({(37, 20, 37, 43): 'f"""MIDI_NOTE.{bytes[1]}"""', (37, 45, 37, 46): '(0)'}, {}), "(f'MIDI_NOTE.{bytes[1]}', 0)", False, 'from socketer import MASM\n')]