Distribute pyjack with freewheel-related functionality
[jack_freewheel_button.git] / pyjack-0.5.2 / demos / alsa_midi_busconnect.py
blob2471c0c40d3c360c854a95d71f9679ff4c8961f9
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
4 import re
5 import os
7 def _getClients(typeOfClient):
8 lines=[line.strip() for line in os.popen("LANG=C aconnect -%s" % typeOfClient).readlines()]
9 listOfClients=[]
10 temporalList=[]
11 for line in lines:
12 if line.find("client ")==0:
13 listOfClients.append(dict())
14 listOfClients[-1]["clientName"]=re.search("'(.*)'",line).group(1)
15 listOfClients[-1]["clientNumber"]=int(re.search("client (.*):",line).group(1))
16 if len(temporalList)>0:
17 listOfClients[-2]["ports"]=temporalList
18 temporalList=[]
19 else:
20 line=re.search("'(.*)'",line).group(1)
21 temporalList.append(line)
22 listOfClients[-1]["ports"]=temporalList
23 return listOfClients
25 def _getClientPorts(name,typeOfClient):
26 listOfClients=_getClients(typeOfClient)
27 try:
28 index=[client['clientName'] for client in listOfClients].index(name)
29 except:
30 print "WARNING: trying to get ports of client %s, which doesn't exist. Returning an empty list." % name
31 return []
32 if index == -1:
33 return None
34 client=listOfClients[index]
35 return [ "%s:%i" % (client["clientNumber"],client["ports"].index(port)) for port in client["ports"] ]
37 def getInputClients():
38 return _getClients("o")
40 def getOutputClients():
41 return _getClients("i")
43 def getClientInputPorts(name):
44 return _getClientPorts(name,"o")
46 def getClientOutputPorts(name):
47 return _getClientPorts(name,"i")
49 def connect(source,target):
50 os.system("aconnect %s %s" % (source,target))
52 def bus_connect(source, target):
53 """
54 Connects two lists of ports. The arguments can be a list or a string. If the latter, all the available ports of the client will be used.
55 """
56 sources = source if type(source) == type([]) else getClientOutputPorts(source)
57 targets = target if type(target) == type([]) else getClientInputPorts(target)
58 num_connections = min(len(sources), len(targets))
59 print 'Doing %i connections. Client has %i out ports and target has %i in ports' % (num_connections, len(sources), len(targets))
60 for i in xrange(num_connections) :
61 print 'connect', sources[i], targets[i]
62 connect(sources[i], targets[i])
63 return num_connections != 0
65 def main():
66 print "input clients: "
67 print getInputClients()
68 print "output ones: "
69 print getOutputClients()
70 print "Midi Through:"
71 print getClientInputPorts("Midi Through")
72 print "Midi Through outputs:"
73 print getClientOutputPorts("Midi Through")
74 bus_connect("Midi Through","Midi Through")
76 if __name__ == '__main__':
77 main()