Esempio n. 1
0
def main():
    controller = vController()
    handlers = dict()

    for handler in json.load(open("controller.json", "r"))["handlers"]:
        handler_command = handler["command"]
        handler_class = handler_types.get(handler["type"])
        handler_args = handler.get("args", [])
        handlers[handler_command] = handler_class(controller=controller,
                                                  **handler_args)

    pygame.midi.init()
    if pygame.midi.get_default_input_id() == -1:
        log.error("No MIDI input found (device ID is -1)!")
        exit(-1)

    log.info("Initializing MIDI input '%i'.",
             pygame.midi.get_default_input_id())
    midi = pygame.midi.Input(pygame.midi.get_default_input_id())
    log.info("Ready!")

    while True:
        try:
            if midi.poll():
                command = midi.read(1)[0][0]
                log.debug("Command is: '%s'", command)
                handler = handlers.get(command[1], None)
                if handler is not None:
                    handler.handle(command)
            time.sleep(0.001)
        except KeyboardInterrupt:
            exit(1)
Esempio n. 2
0
def logMIDI( filename ):
  f = open( filename, "w" )
  pygame.midi.init()
  inputID = pygame.midi.get_default_input_id() 
  print inputID
  midi = pygame.midi.Input( inputID ) 
  while True:
    if midi.poll():
      arr = midi.read(10)
      f.write( str(arr) + '\n' )
      assert len(arr) == 1, arr
      assert len(arr[0]) == 2, arr  # data and timestamp
      assert len(arr[0][0]) == 4, arr
      tmp, tone, cmd, zero = arr[0][0]
      if tone > 90:
        break
  del midi
  f.close()
  pygame.midi.quit()
Esempio n. 3
0
def joystick_run():
    # Process the configuration file
    if options.conf == None:
        print('Must specify a configuration file')
        return
    try:
        if options.verbose:
            print('Opening configuration file:', options.conf)
        (table, vids) = read_conf(options.conf)
    # print(table)
    # print(vids)
    except:
        print('Error processing the configuration file:', options.conf)
        return

    # Getting the MIDI device ready
    if options.midi == None:
        print('Must specify a MIDI interface to use')
        return
    try:
        if options.verbose:
            print('Opening MIDI device:', options.midi)
        midi = pygame.midi.Input(options.midi)
    except:
        print('Error opting MIDI device:', options.midi)
        return

    # Load vJoysticks
    try:
        # Load the vJoy library
        # Load the registry to find out the install location
        vjoyregkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                    'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{8E31F76F-74C3-47F1-9550-E041EEDC5FBB}_is1')
        installpath = winreg.QueryValueEx(vjoyregkey, 'InstallLocation')
        winreg.CloseKey(vjoyregkey)
        # print(installpath[0])
        dll_file = os.path.join(installpath[0], 'x64', 'vJoyInterface.dll')
        vjoy = ctypes.WinDLL(dll_file)
        # print(vjoy.GetvJoyVersion())

        # Getting ready
        for vid in vids:
            if options.verbose:
                print('Acquiring vJoystick:', vid)
            assert (vjoy.AcquireVJD(vid) == 1)
            assert (vjoy.GetVJDStatus(vid) == 0)
            vjoy.ResetVJD(vid)
    except:
        # traceback.print_exc()
        print('Error initializing virtual joysticks')
        return

    try:
        if options.verbose:
            print('Ready. Use ctrl-c to quit.')
        while True:
            while midi.poll():
                ipt = midi.read(1)
                # print(ipt)
                key = tuple(ipt[0][0][0:2])
                reading = ipt[0][0][2]
                # Check that the input is defined in table
                # print(key, reading)
                if not key in table:
                    continue
                opt = table[key]
                if options.verbose:
                    print(key, '->', opt, reading)
                if key[0] == 176:
                    if key[1] == 15:
                        # WE DOING SOME CRAZY STUFF UP IN HERE
                        vjoy.SetBtn(reading, opt[0], opt[1])
                        break
                        print(key[1])
                    # A slider input
                    # Check that the output axis is valid
                    # Note: We did not check if that axis is defined in vJoy
                    if not opt[1] in axis:
                        continue
                    reading = (reading + 1) << 8
                    vjoy.SetAxis(reading, opt[0], axis[opt[1]])
                elif key[0] == 144:
                    # A button input
                    vjoy.SetBtn(reading, opt[0], opt[1])
            time.sleep(0.1)
    except:
        # traceback.print_exc()
        pass

    # Relinquish vJoysticks
    for vid in vids:
        if options.verbose:
            print('Relinquishing vJoystick:', vid)
        vjoy.RelinquishVJD(vid)

    # Close MIDI device
    if options.verbose:
        print('Closing MIDI device')
    midi.close()
Esempio n. 4
0
def joystick_run():
    # Process the configuration file
    if options.conf == None:
        print('Must specify a configuration file')
        return
    try:
        if options.verbose:
            print('Opening configuration file:', options.conf)
        (table, vids) = read_conf(options.conf)
        print(table)
        print(vids)
    except:
        print('Error processing the configuration file:', options.conf)
        return

    # Getting the MIDI device ready
    if options.midi == None:
        print('Must specify a MIDI interface to use')
        return
    try:
        if options.verbose:
            print('Opening MIDI device:', options.midi)
        midi = pygame.midi.Input(options.midi)
    except:
        print('Error opting MIDI device:', options.midi)
        return

    release_queue = []
    removed_queue_indices = []

    # Load vJoysticks
    try:
        # Load the vJoy library
        # Load the registry to find out the install location
        #vjoyregkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{8E31F76F-74C3-47F1-9550-E041EEDC5FBB}_is1')
        #winreg.QueryValueEx(vjoyregkey, 'InstallLocation')
        installpath = ["C:\\Program Files\\vJoy\\"]
        #winreg.CloseKey(vjoyregkey)

        if options.verbose:
            print("VJoy install path", installpath[0])

        dll_file = os.path.join(installpath[0], 'x64', 'vJoyInterface.dll')
        vjoy = ctypes.WinDLL(dll_file)
        if options.verbose:
            print("VJoy version", vjoy.GetvJoyVersion())

        # Getting ready
        for vid in vids:
            if options.verbose:
                print('Acquiring vJoystick:', vid)
            assert (vjoy.AcquireVJD(vid) == 1)
            assert (vjoy.GetVJDStatus(vid) == 0)
            vjoy.ResetVJD(vid)
    except:
        traceback.print_exc()
        print('Error initializing virtual joysticks')
        return

    try:
        print('Ready. Use ctrl-c to quit.')
        while True:
            if len(release_queue) > 0:
                time_now = time.time()
                for i in range(len(release_queue)):
                    queue_item = release_queue[i]
                    if time_now > queue_item[4]:
                        if options.verbose:
                            print('button', queue_item[3], '->', 'release')
                        removed_queue_indices.insert(0, i)
                        vjoy.SetBtn(queue_item[0], queue_item[1],
                                    queue_item[2])

                if len(removed_queue_indices) > 0:
                    for removed_index in removed_queue_indices:
                        release_queue.pop(removed_index)
                    removed_queue_indices = []

            while midi.poll():
                ipt = midi.read(1)
                if options.verbose:
                    print(ipt)

                # slider key has 0 as 3rd element
                slider_key = (ipt[0][0][0], ipt[0][0][1], 0)
                if slider_key in table:
                    # A slider input
                    # Check that the output axis is valid
                    # Note: We did not check if that axis is defined in vJoy
                    opt = table[slider_key]
                    if opt[1] in axis:
                        reading = ipt[0][0][2]
                        if options.verbose:
                            print('slider', slider_key, '->', opt, reading)

                        reading = (reading + 1) << 8
                        vjoy.SetAxis(reading, opt[0], axis[opt[1]])

                # button key has 1 as 3rd element, if button value is not * then this value is 4th element
                button_key = (ipt[0][0][0], ipt[0][0][1], 1, ipt[0][0][2])
                # if no mapping for exact match
                if not button_key in table:
                    # set button key for "any" match (* in config)
                    button_key = (ipt[0][0][0], ipt[0][0][1], 1, -1)

                if button_key in table:
                    opt = table[button_key]

                    # A button input
                    if opt[2] == -1:
                        if options.verbose:
                            print('button', button_key, '->', opt,
                                  'press_and_release')

                        already_waiting_for_release = False
                        for rq_index in range(len(release_queue)):
                            if release_queue[rq_index][1] == opt[
                                    0] and release_queue[rq_index][2] == opt[1]:
                                already_waiting_for_release = True
                                if options.verbose:
                                    print(
                                        'button', button_key,
                                        'already pressed and waiting for release'
                                    )

                        if not already_waiting_for_release:
                            vjoy.SetBtn(1, opt[0], opt[1])
                            delay = 0.1  # in seconds
                            release_queue.append(
                                (0, opt[0], opt[1], button_key,
                                 time.time() + delay))
                    else:
                        if options.verbose:
                            print('button', button_key, '->', opt, opt[2])
                        vjoy.SetBtn(opt[2], opt[0], opt[1])

            time.sleep(0.01)
    except:
        traceback.print_exc()
        pass

    # Relinquish vJoysticks
    for vid in vids:
        print('Relinquishing vJoystick:', vid)
        vjoy.RelinquishVJD(vid)

    print('Closing MIDI device')
    midi.close()
Esempio n. 5
0
try:
    for i in range(0, pygame.midi.get_count()):
        interface = pygame.midi.get_device_info(i)

        # If this isn't an input, we're not interested
        if interface[2] != 1:
            continue

        # If this is one of the system MIDI interfaces, ignore it
        if interface[1] in MIDI_INTERFACES_TO_IGNORE:
            continue

        # We found an interface to open!
        print("Opening MIDI device %d (%s):" % (i, interface[1]))
        midi = pygame.midi.Input(i, 100)
        break
    else:
        raise RuntimeError("MIDI device not found!")

    while 1:
        if midi.poll():
            message = midi.read(1)
            pprint.pprint(message)
except RuntimeError as e:
    print "ERROR: ", e
except KeyboardInterrupt:
    pass

pygame.midi.quit()
sys.exit(0)
Esempio n. 6
0
def joystick_run():
    # Process the configuration file
    if options.conf == None:
        print('Must specify a configuration file')
        return
    try:
        if options.verbose:
            print('Opening configuration file:', options.conf)
        (table, vids) = read_conf(options.conf)
        #print(table)
        #print(vids)
    except:
        print('Error processing the configuration file:', options.conf)
        return

    # Getting the MIDI device ready
    if options.midi == None:
        print('Must specify a MIDI interface to use')
        return
    try:
        if options.verbose:
            print('Opening MIDI device:', options.midi)
        midi = pygame.midi.Input(options.midi)
    except:
        print('Error opting MIDI device:', options.midi)
        return

    # Load vJoysticks
    try:
        # Load the vJoy library
        # Load the registry to find out the install location
        vjoyregkey = winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{8E31F76F-74C3-47F1-9550-E041EEDC5FBB}_is1'
        )
        installpath = winreg.QueryValueEx(vjoyregkey, 'InstallLocation')
        winreg.CloseKey(vjoyregkey)
        #print(installpath[0])
        dll_file = os.path.join(installpath[0], 'x64', 'vJoyInterface.dll')
        vjoy = ctypes.WinDLL(dll_file)
        #print(vjoy.GetvJoyVersion())

        # Getting ready
        for vid in vids:
            if options.verbose:
                print('Acquiring vJoystick:', vid)
            assert (vjoy.AcquireVJD(vid) == 1)
            assert (vjoy.GetVJDStatus(vid) == 0)
            vjoy.ResetVJD(vid)
    except:
        #traceback.print_exc()
        print('Error initializing virtual joysticks')
        return

    try:
        if options.verbose:
            print('Ready. Use ctrl-c to quit.')
        #Initialise history
        previous_key = None
        previous_vjoy_device = None
        while True:
            while midi.poll():
                ipt = midi.read(1)
                #print(ipt)
                key = tuple(ipt[0][0][0:2])
                reading = ipt[0][0][2]
                # Filter out 248 clock messages.
                if key[0] != 248:
                    print(key, reading)
                # Check that the input is defined in table
                if not key in table:
                    # If key isn't in table, it may be cancelling a previous key.
                    # Ignore clock messages and check read value.
                    if key[0] != 248 and reading == 0 and previous_key and previous_vjoy_device:
                        vjoy.SetBtn(reading, previous_key,
                                    int(previous_vjoy_device))
                        print("Zeroing previous key press")
                    elif key[0] != 248:
                        print("Key not specified in conf file")
                    continue
                opt = table[key]
                if options.verbose:
                    print(key, '->', opt, reading)
                if key[0]:
                    # An input
                    # Check if it is configured as an axis or a button
                    # Note: We did not check if that axis is defined in vJoy
                    if not opt[1] in axis:
                        # A button input
                        vjoy.SetBtn(reading, opt[0], int(opt[1]))
                        print('Button value sent')
                        previous_key = opt[0]
                        previous_vjoy_device = opt[1]
                    elif opt[1] in axis:
                        # An Axis Input
                        reading = (reading + 1) << 8
                        vjoy.SetAxis(reading, opt[0], axis[opt[1]])
                        print('Axis value sent')
                print(opt)
            time.sleep(0.01)
    except:
        #traceback.print_exc()
        pass

    # Relinquish vJoysticks
    for vid in vids:
        if options.verbose:
            print('Relinquishing vJoystick:', vid)
        vjoy.RelinquishVJD(vid)

    # Close MIDI device
    if options.verbose:
        print('Closing MIDI device')
    midi.close()
Esempio n. 7
0
nextNote=random.randint(NOTEMIN, NOTEMAX)
task.setNote(nextNote, True)

bar=Bar(pygame.Rect(30, 20, 900, 20), (123, 123, 0), 30000, 30000)
score=0

bgcolor=(255, 255, 255)

try:
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
				sys.exit()

		for event in midi.read(100):
			if event[0][0] == 144:
				if event[0][2]:
					kbd.setNote(event[0][1], True)
					if event[0][1] == nextNote or (IGNOREOCTAVES and kbd.noteName(event[0][1]) == kbd.noteName(nextNote)):
						right.play()
						score+=1
						bar.val+=1000
						bgcolor=random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
						task.setNote(nextNote, False)
						nextNote=random.randint(NOTEMIN, NOTEMAX)
						task.setNote(nextNote, True)
					else:
						bar.val-=1000
						random.choice([wrong1]).play()
				else:
Esempio n. 8
0
def joystick_run():
    # Process the configuration file
    if options.conf == None:
        print('Must specify a configuration file')
        return
    try:
        if options.verbose:
            print('Opening configuration file:', options.conf)
        (table, vids) = read_conf(options.conf)
        #print(table)
        #print(vids)
    except:
        print('Error processing the configuration file:', options.conf)
        return

    # Getting the MIDI device ready
    if options.midi == None:
        print('Must specify a MIDI interface to use')
        return
    try:
        if options.verbose:
            print('Opening MIDI device:', options.midi)
        midi = pygame.midi.Input(options.midi)
    except:
        print('Error opting MIDI device:', options.midi)
        return

    # Load vJoysticks
    try:
        # Load the vJoy library
        # Load the registry to find out the install location
        # vjoyregkey = vjoy_reg_key()
        # installpath = winreg.QueryValueEx(vjoyregkey, 'InstallLocation')
        # winreg.CloseKey(vjoyregkey)
        installpath = ["C:\\Program Files\\vJoy\\"]
        if options.verbose:
            print("VJoy install path", installpath[0])

        dll_file = os.path.join(installpath[0], 'x64', 'vJoyInterface.dll')
        vjoy = ctypes.WinDLL(dll_file)
        #print(vjoy.GetvJoyVersion())

        # Getting ready
        for vid in vids:
            if options.verbose:
                print('Acquiring vJoystick:', vid)
            assert (vjoy.AcquireVJD(vid) == 1)
            assert (vjoy.GetVJDStatus(vid) == 0)
            vjoy.ResetVJD(vid)
    except:
        # traceback.print_exc()
        print('Error initializing virtual joysticks')
        return

    try:
        if options.verbose:
            print('Ready. Use ctrl-c to quit.')
        while True:
            while midi.poll():
                ipt = midi.read(1)
                # print(ipt)
                key = tuple(ipt[0][0][0:2])
                reading = ipt[0][0][2]
                # hacky fix for worlde special rotary button
                if key[0] == 192:
                    reading = key[1]
                    key = (key[0], 0)
                # Check that the input is defined in table
                # print(key, reading)
                if not key in table:
                    continue
                opt = table[key]
                if options.verbose:
                    print(key, '->', opt, reading)
                if key[0] == 144:
                    # A button input
                    vjoy.SetBtn(reading, opt[0], opt[1])
                else:
                    # A slider input
                    # Check that the output axis is valid
                    # Note: We did not check if that axis is defined in vJoy
                    if not opt[1] in axis:
                        continue
                    reading = (reading + 1) << 8
                    vjoy.SetAxis(reading, opt[0], axis[opt[1]])

            time.sleep(0.1)
    except:
        #traceback.print_exc()
        pass

    # Relinquish vJoysticks
    for vid in vids:
        if options.verbose:
            print('Relinquishing vJoystick:', vid)
        vjoy.RelinquishVJD(vid)

    # Close MIDI device
    if options.verbose:
        print('Closing MIDI device')
    midi.close()