Exemplo n.º 1
0
    def set_device(self, device):
        """
        Selects the MIDI device to be polled.

        @param device: The device number to choose.
        @type device: int
        @rtype: bool
        @return: Success or not
        """
        #check if device exist
        dev_list = [
            self.midi_device_list[i][0]
            for i in range(len(self.midi_device_list))
        ]
        if device in dev_list:  # if the number is not in list of input devices
            self.midi_device = device
            if self.midi_in is not None:
                #delete old midi device if present
                del self.midi_in
            #Initializing midi input stream
            self.midi_in = pypm.Input(self.midi_device)
            if self.verbose:
                line = "  Midi device in: " + str(self.get_device_info()[1])
                print line
            return True
        else:
            print "INPUT: Invalid midi device selected"
            print dev_list
            return False
Exemplo n.º 2
0
 def __init__(self, parent, device, notes, cc):
     pypm.Initialize()
     pypm.CountDevices()
     self.MidiIn = pypm.Input(device)
     self.parent = parent
     self.notes = notes
     self.cc = cc
Exemplo n.º 3
0
    def run(self):
        self.running = True
        pypm.Initialize()
        self.in_device = pypm.Input(self.in_device_id)
        self.out_device = pypm.Output(self.out_device_id)

        self.clear()

        #    try:
        #      while self.running:
        #        self.read_buttons()
        #    finally:
        #      print("Shutting down.")
        #      self.in_device.Close()
        #      self.out_device.Close()
        #      pypm.Terminate()
        #
        #    return

        try:
            while self.running:
                self.set_pattern(0)
                time.sleep(self.wait)
                self.set_pattern(1)
                time.sleep(self.wait)

        finally:
            print("Shutting down.")
            self.clear()
            self.in_device.Close()
            self.out_device.Close()
            pypm.Terminate()
Exemplo n.º 4
0
    def __init__(self, deviceId=None):
        init()

        if deviceId is None:
            deviceId = findTriggerFinger()

        assert deviceId is not None

        self.stream = pypm.Input(deviceId)
Exemplo n.º 5
0
    def __init__(self, in_device_id, out_device_id):
        print "Opening devices:"

        self.in_device = pypm.Input(in_device_id)
        print "\tin: {0}, {1}".format(in_device_id, self.in_device)

        self.out_device = pypm.Output(out_device_id)
        print "\tin: {0}, {1}".format(out_device_id, self.out_device)
        self.write_queue = []
Exemplo n.º 6
0
def TestInput():
    PrintDevices(INPUT)
    dev = int(raw_input("Type input number: "))
    MidiIn = pypm.Input(dev)
    print "Midi Input opened. Reading ",NUM_MSGS," Midi messages..."
#    MidiIn.SetFilter(pypm.FILT_ACTIVE | pypm.FILT_CLOCK)
    for cntr in range(1,NUM_MSGS+1):
        while not MidiIn.Poll(): pass
        MidiData = MidiIn.Read(1) # read only 1 message at a time
        print "Got message ",cntr,": time ",MidiData[0][1],", ",
        print  MidiData[0][0][0]," ",MidiData[0][0][1]," ",MidiData[0][0][2], MidiData[0][0][3]
        # NOTE: most Midi messages are 1-3 bytes, but the 4 byte is returned for use with SysEx messages.
    del MidiIn
Exemplo n.º 7
0
 def getInput(cls, dev):
     """
     Get an input with devive number 'dev' - dev may also be string matching
     the target device. If the input was previously loaded this will return
     the cached device.
     """
     no = dev
     if isinstance(dev, basestring):
         no = cls.deviceMap[dev]['input']
     key = ('input', no)
     if key not in cls._channels:
         cls._channels[key] = pypm.Input(no)
     return cls._channels[key]
Exemplo n.º 8
0
    def recv_real(recv_conn, indev, msgfilter=[], debug=False):
        signal.signal(signal.SIGINT,signal.SIG_IGN)
        MidiIn = pypm.Input(indev)
        # does not seem to work, leave at default (FILT_ACTIVE)
        #MidiIn.SetFilter(pypm.FILT_ACTIVE | pypm.FILT_CLOCK)
        bufsize=10
        sysex = []
        sysex_timestamp = None
        while True:
            try:
                if recv_conn.poll():
                    (timestamp, msg) = recv_conn.recv()
                    if timestamp < 0:
                        break
            except EOFError:
                break
            
            #while not MidiIn.Poll(): pass
            # sleep 1ms to keep CPU usage down
            time.sleep(1e-3)
            MidiData = MidiIn.Read(bufsize)
            nev = len(MidiData)
            for msg in MidiData:
                msgtype = msg[0][0]
                timestamp = msg[1]
                ignore = False
                for f in msgfilter:
                    for i in xrange(min(len(f),len(msg[0]))):
                        if f[i] != msg[0][i]:
                            break
                    else:
                        ignore = True
                if ignore:
                    continue

                if msgtype == 0xF0:
                    sysex = msg[0]
                    sysex_timestamp = timestamp
                elif sysex_timestamp == timestamp:
                    sysex += msg[0]
                    if 0xF7 in sysex:
                        sysex = sysex[:sysex.index(0xF7)+1]
                        if debug:
                            print "Received SysEx:", sysex_timestamp, \
                                [hex(b) for b in sysex ]
                        recv_conn.send( (sysex_timestamp, sysex))
                        sysex = []
                        sysex_timestamp = None
                else:
                    recv_conn.send( (timestamp, msg[0]))
        del MidiIn
Exemplo n.º 9
0
def find_device():
  count = pypm.CountDevices()
  print 'Found {0} devices'.format(count)
  in_dev, out_dev = (None, None)
  for i in range(count):
    info = pypm.GetDeviceInfo(i)
    print info
    if info[1] == 'Launchpad Mini':
      if info[2] == 1:
        print 'Opening input {0}'.format(i)
        in_dev = pypm.Input(i)
      if info[3] == 1:
        print 'Opening output {0}'.format(i)
        out_dev = pypm.Output(i)
  return (in_dev, out_dev)
Exemplo n.º 10
0
    def __init__(self, target=MIDIIN_DEFAULT):
        pypm.Initialize()
        self.midi = None

        for n in range(pypm.CountDevices()):
            info = pypm.GetDeviceInfo(n)
            name = info[1]
            print "[%d] %s %s" % (n, name, info)
            isInput = info[2]
            if name == target and isInput == 1:
                self.midi = pypm.Input(n)
                print "found target input: %s" % target

        if self.midi is None:
            raise Exception, "Could not find MIDI source: %s" % target
Exemplo n.º 11
0
 def __init__(self):
     self.outd = pypm.Output(0, 0)
     self.ind = pypm.Input(1)  #@TODO: select from dropdown.
     self.pyCallback = lambda a, b, c: None  # do nothing
     self.echo = True
Exemplo n.º 12
0
 def __init__(self, idIn, idOut):
     self._midiIn = pypm.Input(idIn)
     self._midiOut = pypm.Output(idOut, 0)
 def __init__(self, **kwargs):
     tempfile.TemporaryFile.__init__(self)
     self.pypm_index = kwargs.get('index')
     self.device = pyportmidi.Input(self.pypm_index)
 def build_device(self, **kwargs):
     return pyportmidi.Input(self.dev_info.index)
Exemplo n.º 15
0
 def __init__(self, input_device, output_device):
     self.input_device = input_device
     self.output_device = output_device
     self.I = pypm.Input(self.input_device)
     self.O = pypm.Output(self.output_device)
     self.reading = -1
Exemplo n.º 16
0
def SysexTest( deviceInput, deviceOutput, queryBlockAddress, latency ):
	#midiInput = None
	midiInput = pypm.Input( int( deviceInput ), 1024 )
	midiOutput = pypm.Output( int( deviceOutput ), latency )
	
	##################################################
	# Cycle through buttons
#	for i in range(1,100):
#		msg = SysexMessage( ord('s'), 0, 1, [ i % 4 ] )
#		midiOutput.WriteSysEx( 0, str( bytearray( msg ) ) )
#		time.sleep(0.01)
	#'''

	##################################################
	# Set ICB
	#msg = SysexMessage( ord('i'), 67, 16, [ 0x00, 0x00, 0x41, 0x41, 0x41, 0x00, 0x08, 0x00, 0x00, 0xC4, 0x48, 0x55, 0x4D, 0x41, 0x4E, 0x4D ] )
	#midiOutput.WriteSysEx( 0, str( bytearray( msg ) ) )
	
	##################################################
	# Get ICB
	msg = SysexMessage( ord('r'), queryBlockAddress, 1, [ ord('i') ] )
	
	# Switch control key to B
	#msg = SysexMessage( ord('s'), 0, 1, [ 1 ] )

	# Get Instrument Control Block at address 66
	#msg = SysexMessage( ord('r'), 66, 1, [ ord('i') ] )
	
	# Get VCF parameters
	#msg = SysexMessage( ord('r'), queryBlockAddress, 1, [ ord('v') ] )
	
	# Get Amplitude envelope at address 65
	#msg = SysexMessage( ord('r'), 65, 1, [ BlockIdentifier.AMPL ] )
	
	# Get fixed wavetable
	#msg = SysexMessage( ord('r'), queryBlockAddress, 1, [ BlockIdentifier.FIXWAVE ] )
	
	# Get relative wavetable
	#msg = SysexMessage( ord('r'), queryBlockAddress, 1, [ BlockIdentifier.RELWAVE ] )
	
	# Change VCF parameters at address 64
	#msg = SysexMessage( ord('v'), 64, 10, [ 3, 0, 11, 149, 232, 232, 0, 49, 0, 49 ] )
	
	# Change Amplitude envelope at address 65
	'''
	msg = SysexMessage( ord('a'), 65, 44, [ 0x20, 0xb1, 0x0a, 0x20, 0x00, 0x00, 0xef, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x85, 0x00, 0x00, 0xa2, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x08, 0x20, 0x20, 0xdf, 0x4b, 0x20, 0x07, 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] )
	# '''
	
	# Test
	#msg = SysexMessage( ord('f'), 65, 32, [ 0x11 ] * 32 )
	
	# Change Frequency envelope at address 65
	#msg = SysexMessage( BlockIdentifier.FREQ, 65, 16, [ 0x02,0xFF,  0xA0,0x00,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0,  0,0 ] )
	##################################################
	
	# Print output message
	print 'Out:'
	print ' '.join('0x%02X    ' % b for b in msg)
	#print ' '.join((bin(b)[2:]).zfill(8) for b in msg)
	
	# Write message to MIDI
	midiOutput.WriteSysEx( 0, str( bytearray( msg ) ) )
	
	# Poll for MIDI input
	readTimeout = 0.5
	if midiInput:
		readTimeStart = time.time()
		readReady = True
		msg = []
		while readReady:
			if not midiInput.Poll():
				# Check timeout
				if (time.time() - readTimeStart) > readTimeout:
					# Timeout exceeded, abort reading
					readReady = False
			else:
				# Read data
				MidiData = midiInput.Read(1024)
				# Append data to buffer
				for m in MidiData:
					for n in m[0]:
						msg.append( n )
		if msg:
			# Parse SysEx header
			headerSize = 9
			if msg[0] == 0xF0 and msg[1] == 0x25 and msg[2] == 0x01 and len( msg ) > headerSize:
				# Wersi MK1 SysEx message
				#
				# 11110000: MIDI SysEx identifier
				# 00100101: Wersi identifier
				# 00000001: MK1 identifier
				# 011NXXXX: Block identifier (hi/lo)
				# 010NXXXX: Block address (hi/lo)
				# 001NXXXX: Block length (hi/lo)
				# 000NXXXX: Data (hi/lo)
				blockIdentifier = ConvertFromNibbles( [ msg[3], msg[4] ] )[0]
				blockAddress = ConvertFromNibbles( [ msg[5], msg[6] ] )[0]
				blockLength = ConvertFromNibbles( [ msg[7], msg[8] ] )[0]
				data = msg[9:]
				# Always one byte missing :(
				# Probably due to a crappy MIDI SysEx ROM implementation in the Wersi.
				if (len( data ) / 2) >= ( blockLength - 1 ):
					print "* Received Wersi MK1 SysEx message, length %u" % len(msg)
					print "Block identifier: %s (%u)" % ( chr( blockIdentifier ), blockIdentifier )
					print "Block address: %u (0x%02X)" % ( blockAddress, blockAddress )
					print "Block length: %u bytes" % ( blockLength )
					print "Data (got %u bytes):" % ( len( data ) / 2 )
					print ' '.join('0x%02X    ' % b for b in ConvertFromNibbles( data ))
					print ' '.join('(%s)     ' % (chr( b ) if b >= 32 else '?') for b in ConvertFromNibbles( data ))
					print ' '.join('%08u' % b for b in ConvertFromNibbles( data ))
					print ' '.join((bin(b)[2:]).zfill(8) for b in ConvertFromNibbles( data ))
				else:
					print "Received message was too short (got %u, expected %u). Try again." % ( (len( data ) / 2), blockLength - 1 )
		del midiInput
	
	# Cleanup
	del midiOutput
Exemplo n.º 17
0
 def InitializeMidiInput(self):
     print("The following MIDI input devices are detected on your system: ")
     self.ListMidiInputDevices()
     dev = int(input("Please type a device number from the list: "))
     self.MidiIn = pypm.Input(dev)
     print("Midi Input opened. Waiting for chords of 3 notes or more...")
Exemplo n.º 18
0
                else:
                    bar_size = size

                DrawBar(MidiOut, input_pos, bar_size)


# main code begins here
pypm.Initialize(
)  # always call this first, or OS may crash when you try to open a stream

PrintDevices(OUTPUT)
dev = int(raw_input("Type output number: "))
MidiOut = pypm.Output(dev, 0)
PrintDevices(INPUT)
dev = int(raw_input("Type input number: "))
MidiIn = pypm.Input(dev)
# turn off internal LED finger tracking
SetLEDsIgnoreTouch(MidiOut)
# set initial column
SendColumn(MidiOut, 45)
# turn on pressure output
EnablePressureOutput(MidiOut)

demo_choice = int(
    raw_input("""
Choose a demo:
1) Cursor tracks finger position
2) Cursor size adjusts based on pressure
3) Monitor CPU level
4) Binary Counter
5) Binary Clock