Opening of interfaces is working, only thing left to do is to link them

This commit is contained in:
Maximilien Rigaut 2019-05-05 17:52:59 +02:00
parent f0709021b5
commit cef1fa7dc2
8 changed files with 342 additions and 268 deletions

View File

@ -1,36 +0,0 @@
import mido
# Load the config and return an action class
class Binding(object):
"""Binding class, simple binding between note and actions"""
def __init__(self, config):
self.config=config
self.loadConfig()
def loadConfig(self):
pass
#Detect config error
#Bind all actions to a return message
#Make a easy list to acess list of actions
def read(gmaMessage):
"""Read the gmaMessage and return a list of action"""
#Readmessage
#Parse message with config
#Handle Errors
#Return Action or ActionList that can be .run
return ActionList()
class ActionList(object):
"""List of action to play after a message is receaved"""
def __init__(self,list):
"""Takes the list of actions detected and """
pass
class Action(object):
"""Action itself, a mapper for the midi library"""
def __init__(self,actiontype):
"""Take one action and bind the correct midi message"""
self.actiontype=actiontype

View File

@ -1,5 +0,0 @@
import mido
from config import *
if __name__ == '__main__':
main()

View File

@ -1,4 +1,4 @@
from mapping.base import BasicMessageParse,BasicAction,MatchError
from mapping.base import BasicMessageParse,BasicAction,MatchError,BasicMidiInterface
import mido
import re,configparser
@ -26,219 +26,16 @@ class MessageParse(BasicMessageParse):
else:
raise MatchError
#An Action object MUST be included in the file.
#Called first with a config file, will be callable to launch an action with the matched regex as an argument
class Action(BasicAction):
"""The list of action to perform when a message is read"""
def __init__(self,config):
"""Parse the config and ready all return actions"""
# Load config, in a near future, the config will be preloaded beforehand, but for right now, practicallity will prevail
self.config=configparser.ConfigParser()
self.config.read(config)
self.sections={}
self.outputs={} #Have every output in a dict THIS PART IS SUPPOSEDLY ALREADY TAKEN CARE OF
# This funtion is MANDATORY, it makes the link between MessageParse and Action
def CallAction(match,ActionObj):
"Make the link between the regex and the action"
pass
# Very cheesy way to figure out notes from control, I should find a better way, but I can't be bothered to
self.dec10=[str(x) for x in range(10)]
# An Action object MUST be included in the file.
# Interitance and method override can be used, but aren't needed here
# Action(config)
Action=BasicAction
# Parse config & check sanity
if "interface" not in self.config:
raise IOError #You must define an interface to connect to
#TODO WARNING; THIS IS SUPPOSEED TO BE TAKEN CARE BY THE FUNCTION CALLING Action()
self.outputs={1:self.config["interface"]["output1"], 2:self.config["interface"]["output2"]}
self.populateSections()
#self.prettyprint()
def populateSections(self):
"Create all the call setups"
for elt in self.config.sections():
if elt !="interface":
if "/" in elt:
selt=elt.split("/")
if selt[0] not in self.sections:
self.sections[selt[0]]={}
self.sections[selt[0]].update({selt[1]:self.makeTriggers(self.config[elt])})
else:
if elt in self.sections:
if "*" not in self.sections[elt]:
self.sections[elt]["*"]=self.makeTriggers(self.config[elt])
# This means you will override any "/x" config
else:
self.sections[elt]={"*":self.makeTriggers(self.config[elt])}
def makeTriggers(self,conf):
"Take a section of a config and put all triggers in a dict"
keys={}
for key in conf: # Reading every mapping and liking it to the appropriate Trigger
if "/" in key: # There is a condition to an action
note,atype=key.split("/")
if "-" in note:
nmin,nmax=note.split("-")
nmin,nmax=int(nmin),int(nmax)
for i in range(nmin,nmax):
for trigger in (keys[int(i)]):
trigger.addspecial(atype,conf[key])
else:
for trigger in keys[int(note)]:
trigger.addspecial(atype,conf[key])
elif "-" in key: # There is a range of values to map
nmin,nmax=key.split("-")
nmin,nmax=int(nmin),int(nmax)
for i in range(nmin,nmax):
keys[i]=self.makeAllKeys(i,conf[key],startkey=nmin,stopkey=nmax) #Do a different trigger for every ; and link to a different interface for every n/
else: # Nothing fancy
keys[int(key)]=self.makeAllKeys(int(key),conf[key])
return keys
def makeAllKeys(self,key,action,startkey=0,stopkey=0):
"""Make all the actions associated with the key
startkey and stopkey indicate if an interpolation over the values is to be made"""
#Check if there are multiple actions to do
if ';' in action:
allactions=[]
for a in action.split(";"):
allactions+=self.makeAllKeys(key,a,startkey,stopkey)
return allactions
try:
pack=action.split("/")
if len(pack)==4:
interfaceout,midiaction,note,intensity=pack
elif len(pack)==2:
midiaction,note=pack
interfaceout,intensity=1,127
elif len(pack)==3:
if pack[0][0] not in self.dec10:
midiaction,note,intensity=pack
interfaceout=1
else:
interfaceout,midiaction,note=pack
intensity=127
else:
raise ValueError
intensity,interfaceout=int(intensity),int(interfaceout)
except:
print("Config key {} is incorrect, values {} can't be unpacked".format(key,action))
try:
return [MidiTrigger(self.outputs[interfaceout],midiaction,self.findNote(key,startkey,stopkey,note),intensity)]
except (KeyError):
print("Can't find interface {} for note {} action {}, legal interfaces are {}".format(interfaceout,note,action,[i for i in self.outputs.keys()]))
return [] #This choice is not necessary the best, but I figure it's easier that forcing the config to be perfect
except ValueError:
print("Incorrect values given to the midi message {}".format(action))
return []
def findNote(self,key,startkey,stopkey,note):
"Find the note to bind to the received one"
if startkey!=stopkey: #do an interpolation over the values
if "-" in note: #there is a range to interpolate over to
nmin,nmax=note.split("-")
nmin,nmax=int(nmin),int(nmax)
else:
nmin=int(note)
nmax=nmin+stopkey-startkey #Just do the interpolation linearly
if nmax-nmin!=stopkey-startkey:
pad=int((nmax-nmin)/(stopkey-startkey))
else:
pad=1
return nmin+(key-startkey)*pad
return int(note)
def findAction(self,command,number,page):
"Find the correct Action when a command is received"
try:
return self.sections[command][str(page)][int(number)]
except:
return self.sections[command]["*"][int(number)]
def __call__(self,match):
"""Launch the action depending on the config, the config format is supposed to be as canon as possible
but since the actual implementation is custom made... go wild ?"""
# Try a predefined action
pass
def __repr__(self):
return(self.sections)
def prettyprint(self):
for sect in self.sections:
for subsect in self.sections[sect]:
print("[{}] > {}".format(sect,subsect))
for elt in self.sections[sect][subsect]:
print(" {} : {}".format(elt,self.sections[sect][subsect][elt]))
FTrue=lambda x: True
RecognisedMessagesTypes={
"note":["note_on","note","velocity"],
"sysex":["sysex","data"],
"cc":["control_change","control","value"],
"on":["note_on","note","velocity"],
"off":["note_off","note","velocity"],
"pc":["program_change","program"]}
class MidiTrigger(object):
"""A midi trigger, will do a specific action when called"""
def __init__(self,interface,messagetype,value,intensity):
self.output=interface
self.messagetype=messagetype
self.value=value
self.intensity=intensity
self.valuefn=None
message=RecognisedMessagesTypes[messagetype]
attributes={}
self.toggle=None
attributes[message[1]]=value
self.valuetype={message[1]:0}
try:
attributes[message[2]]=intensity
except IndexError:
pass
self.message=mido.Message(RecognisedMessagesTypes[messagetype][0],**attributes)
def __call__(self,val):
"""Execute the call if the condition is true"""
#for cond in self.conditions:
# if not cond(val):
# return #A condition isn't met, returning
if self.valuefn:
val=self.valuefn(val)
if self.toggle!=None:
if self.toggle:
val=self.valtrue
else:
val=self.valfalse
print(val)
self.message.copy()
return self.sendmessage()
def sendmessage(self):
print("SENDING: ")
print(self.message)
def addspecial(self,typ,val):
"""Affect a specific action (usually a condition) to the execution of the event"""
if typ == "val":
self.addvalfn(val)
elif typ == "toggle":
valt,valf=val.split("/")
self.addstate(int(valt),int(valf))
def addvalfn(self,fn):
"Add a special function to calculate the value"
try:
self.valuefn=eval(fn)
#print(self.valuegn(42))
except:
print("Cant evaluate funtion {}".format(fn))
def addstate(self,valtrue,valfalse):
"The message will now send two state values intead"
self.toggle=True
self.valtrue=valtrue
self.valfalse=valfalse
def __repr__(self):
return "<MT>({}/{}/{})@{}".format(self.messagetype,self.value,self.intensity,self.output)
# Same as above, import BasicMidiInterface as MidiInterface could be used instead
# MidiInterface(config)
MidiInterface=BasicMidiInterface

View File

@ -1,5 +1,49 @@
# This is the basic mapping of a midi message, all subsequent messages must either be children of this or implement those methods
import configparser
import mido,re
class BasicMidiInterface(object):
"Basic midi interface"
def __init__(self,configfile):
"Try to open the defined interfaces in the config"
self.config=configparser.ConfigParser()
self.config.read(configfile)
# Parse config & check sanity
if "interface" not in self.config:
raise IOError #You must define an interface to connect to
self.input=""
self.outputs={}
#self.outchannels #not as of now, maybe later
outputmatch=re.compile("output(?P<outnb>\d+)")
for elt in self.config["interface"]:
if elt=="input":
self.input=self.openin(self.config["interface"][elt])
else:
match=outputmatch.match(elt)
if match:
nb=match.group('outnb')
self.outputs[int(nb)]=self.openout(self.config["interface"][elt])
#self.outputs.append(self.config["interface"][elt])
def openin(self,name):
"Try and open an output interface"
try:
o=mido.open_input(name)
except:
print("[ERROR] Impossible to open input {} (available are {})".format(name,mido.get_input_names()))
o=None
return o
def openout(self,name):
"Try and open an input interface"
try:
o=mido.open_output(name)
except:
print("[ERROR] Impossible to open output {} (available are {})".format(name,mido.get_output_names()))
o=None
return o
class BasicMessageParse(object):
"""Classic System Specific Midi Message as Hex (BasicSyHexParse).
Uses one method, parseMidi to parse the message and return a BasicMapping object with the mapping of the message inside"""
@ -13,16 +57,227 @@ class BasicMessageParse(object):
return BasicMapping(self._mapping)
class BasicAction(object):
"""A basic reading of the message, propreties are initialised depending on the way the SyEx message is formed,
this objet will need the configuration to read and understand the message"""
"""The list of action to perform when a message is read"""
def __init__(self,config):
"""Parse the config and ready all return actions"""
# Load config, in a near future, the config will be preloaded beforehand, but for right now, practicallity will prevail
self.config=configparser.ConfigParser()
self.config.read(config)
self.sections={}
self.outputs={} #Have every output in a dict THIS PART IS SUPPOSEDLY ALREADY TAKEN CARE OF
def __init__(self,dictmapping):
'Barebone init'
self._mapping=dictmapping
# Very cheesy way to figure out notes from control, I should find a better way, but I can't be bothered to
self.dec10=[str(x) for x in range(10)]
def __call__(self,config):
"""Resolve the current action, all actions will be performed depending on what's inside the mapping and the config"""
# Parse config & check sanity
if "interface" not in self.config:
raise IOError #You must define an interface to connect to
#TODO WARNING; THIS IS SUPPOSEED TO BE TAKEN CARE BY THE FUNCTION CALLING Action()
self.outputs={1:self.config["interface"]["output1"], 2:self.config["interface"]["output2"]}
self.populateSections()
#self.prettyprint()
def populateSections(self):
"Create all the call setups"
for elt in self.config.sections():
if elt !="interface":
if "/" in elt:
selt=elt.split("/")
if selt[0] not in self.sections:
self.sections[selt[0]]={}
self.sections[selt[0]].update({selt[1]:self.makeTriggers(self.config[elt])})
else:
if elt in self.sections:
if "*" not in self.sections[elt]:
self.sections[elt]["*"]=self.makeTriggers(self.config[elt])
# This means you will override any "/x" config
else:
self.sections[elt]={"*":self.makeTriggers(self.config[elt])}
def makeTriggers(self,conf):
"Take a section of a config and put all triggers in a dict"
keys={}
for key in conf: # Reading every mapping and liking it to the appropriate Trigger
if "/" in key: # There is a condition to an action
note,atype=key.split("/")
if "-" in note:
nmin,nmax=note.split("-")
nmin,nmax=int(nmin),int(nmax)
for i in range(nmin,nmax):
for trigger in (keys[int(i)]):
trigger.addspecial(atype,conf[key])
else:
for trigger in keys[int(note)]:
trigger.addspecial(atype,conf[key])
elif "-" in key: # There is a range of values to map
nmin,nmax=key.split("-")
nmin,nmax=int(nmin),int(nmax)
for i in range(nmin,nmax):
keys[i]=self.makeAllKeys(i,conf[key],startkey=nmin,stopkey=nmax) #Do a different trigger for every ; and link to a different interface for every n/
else: # Nothing fancy
keys[int(key)]=self.makeAllKeys(int(key),conf[key])
return keys
def makeAllKeys(self,key,action,startkey=0,stopkey=0):
"""Make all the actions associated with the key
startkey and stopkey indicate if an interpolation over the values is to be made"""
#Check if there are multiple actions to do
if ';' in action:
allactions=[]
for a in action.split(";"):
allactions+=self.makeAllKeys(key,a,startkey,stopkey)
return allactions
try:
pack=action.split("/")
if len(pack)==4:
interfaceout,midiaction,note,intensity=pack
elif len(pack)==2:
midiaction,note=pack
interfaceout,intensity=1,127
elif len(pack)==3:
if pack[0][0] not in self.dec10:
midiaction,note,intensity=pack
interfaceout=1
else:
interfaceout,midiaction,note=pack
intensity=127
else:
raise ValueError
intensity,interfaceout=int(intensity),int(interfaceout)
except:
print("[WARNING] Config key {} is incorrect, values {} can't be unpacked".format(key,action))
try:
return [BasicMidiTrigger(self.outputs[interfaceout],midiaction,self.findNote(key,startkey,stopkey,note),intensity)]
except (KeyError):
print("[WARNING] Can't find interface {} for note {} action {}, legal interfaces are {}".format(interfaceout,note,action,[i for i in self.outputs.keys()]))
return [] #This choice is not necessary the best, but I figure it's easier that forcing the config to be perfect
except ValueError:
print("[WARNING] Incorrect values given to the midi message {}".format(action))
return []
def findNote(self,key,startkey,stopkey,note):
"Find the note to bind to the received one"
if startkey!=stopkey: #do an interpolation over the values
if "-" in note: #there is a range to interpolate over to
nmin,nmax=note.split("-")
nmin,nmax=int(nmin),int(nmax)
else:
nmin=int(note)
nmax=nmin+stopkey-startkey #Just do the interpolation linearly
if nmax-nmin!=stopkey-startkey:
pad=int((nmax-nmin)/(stopkey-startkey))
else:
pad=1
return nmin+(key-startkey)*pad
return int(note)
def findAction(self,command,number,page):
"Find the correct Action when a command is received"
try:
return self.sections[command][str(page)][int(number)]
except:
return self.sections[command]["*"][int(number)]
def __call__(self,match):
"""Launch the action depending on the config, the config format is supposed to be as canon as possible
but since the actual implementation is custom made... go wild ?"""
# Try a predefined action
pass
def __repr__(self):
return(self.sections)
def prettyprint(self):
for sect in self.sections:
for subsect in self.sections[sect]:
print("[{}] > {}".format(sect,subsect))
for elt in self.sections[sect][subsect]:
print(" {} : {}".format(elt,self.sections[sect][subsect][elt]))
FTrue=lambda x: True
RecognisedMessagesTypes={
"note":["note_on","note","velocity"],
"sysex":["sysex","data"],
"cc":["control_change","control","value"],
"on":["note_on","note","velocity"],
"off":["note_off","note","velocity"],
"pc":["program_change","program"]}
class MatchError(Exception):
pass
class BasicMidiTrigger(object):
"""A midi trigger, will do a specific action when called"""
def __init__(self,interface,messagetype,value,intensity):
self.output=interface
self.messagetype=messagetype
self.value=value
self.intensity=intensity
self.valuefn=None
message=RecognisedMessagesTypes[messagetype]
attributes={}
self.toggle=None
attributes[message[1]]=value
try:
attributes[message[2]]=intensity
self.valuetype={message[2]:0}
except IndexError:
self.valuetype={}
self.message=mido.Message(RecognisedMessagesTypes[messagetype][0],**attributes)
def __call__(self,val):
"""Change the value (if necessary) and send the message"""
self.changevalue(val)
return self.sendmessage()
def changevalue(self,val):
"Change the value (depending on the toggles etc...)"
#for cond in self.conditions:
# if not cond(val):
# return #A condition isn't met, returning
change=self.value
if self.valuefn:
change=self.valuefn(val)
if self.toggle!=None:
if self.toggle:
change=self.valtrue
else:
change=self.valfalse
if change!=self.value:
self.value=change
self.valuetype[list(self.valuetype)[0]]=change
self.message=self.message.copy(**self.valuetype)
def sendmessage(self):
if self.toggle!=None:
self.toggle=not self.toggle
#print("SENDING:",self.message)
#self.interface.send(self.message) #Needs interface implementation
def addspecial(self,typ,val):
"""Affect a specific action (usually a condition) to the execution of the event"""
if typ == "val":
self.addvalfn(val)
elif typ == "toggle":
valt,valf=val.split("/")
self.addstate(int(valt),int(valf))
def addvalfn(self,fn):
"Add a special function to calculate the value"
try:
self.valuefn=eval(fn)
#print(self.valuegn(42))
except:
print("[ERROR] Cant evaluate funtion {}".format(fn))
def addstate(self,valtrue,valfalse):
"The message will now send two state values intead"
self.toggle=True
self.valtrue=valtrue
self.valfalse=valfalse
def __repr__(self):
return "<MT>({}/{}/{})@{}".format(self.messagetype,self.value,self.intensity,self.output)

6
midiRebind.py Normal file
View File

@ -0,0 +1,6 @@
import mido
if __name__ == '__main__':
o=mido.open_output("Midi Through Port-0")
print(o)
o.close()

View File

@ -1,6 +1,6 @@
[interface]
input="Scarlett i6"
output1="Scarlett i6"
input="Midi Through Port-0"
output1="Midi Through Port-0"
output2="Akai Mix"
inputchanel = 1
outputchannel1 = 1

40
patch/test.ini Normal file
View File

@ -0,0 +1,40 @@
[interface]
input=Midi Through Port-0
output1=Midi Through Port-0
output2=Akai Mix
channelinput = 1
channelout1 = 1
channelout2 = 1
# Will fetch GrandMA2.py in the mappings
mapping = GrandMA2
#Patching faders: Patches layer 1 patch:2 would patch layer 2 and so on
[set/1]
#Send (midi) control change (10) with value mapped to the fader (1) value (fader 1 => cc 10) on output 1
1 = 1/cc/10
#Map the faders 5-50 to the control change 11-45 (Straight patch) on output 1
5-50 = 1/cc/11
# Will map linearly 57 to 12; 58 to 14 etc on output 1
57-67 = 1/cc/12-32
#Map fader 56 to note 152 on output 2
56 = 1/note/127
# Function choosing the value to send, depending on the intensity received
56/val = lambda x: min(x,50)*2
[set/5]
1 = 1/cc/2;2/note/19/127
#No layer specified
[fire]
13 = 1/note/10
#Send control change with value 127
15 = 1/cc/44/127
# Send control change 45-55 with value 127
17-27 = cc/45/127
# Will map 29 to 37 to 46
29-37 = cc/46-46/127
#(Stack the action to link to)
38 = 1/cc/65/124;2/cc/79/100;note/25
38/toggle = 0/127
[fire/5]
15 = 1/cc/2;2/note/19/127

23
test.py
View File

@ -75,7 +75,7 @@ class mappingTest(minitest.simpleTestUnit):
self.currentTest("Loading Config")
try:
self.act=GrandMA2.Action("patch/default.ini")
self.act=GrandMA2.Action("patch/test.ini")
self.addSuccess()
except IOError:
self.addFailure("Can't load config file")
@ -128,11 +128,11 @@ class mappingTest(minitest.simpleTestUnit):
acts=self.act.findAction("fire",38,"1")
for act in acts:
if not act.toggle:
self.addFailure("Trigger isn't true")
self.addFailure("Trigger isn't assigned")
st=False
break
except:
self.addFailure("Toggle for key 38 isn't working")
self.addFailure("Toggle for key 38 isn't assigned")
if st:
self.addSuccess()
else:
@ -142,6 +142,11 @@ class mappingTest(minitest.simpleTestUnit):
acts=self.act.findAction("fire",38,"1")
for act in acts:
act(12)
st=act.toggle
act(12)
st1=act.toggle
if st==st1:
self.addFailure("State not changing after a call")
#self.act.prettyprint()
def testParse(self,message):
@ -162,5 +167,17 @@ class mappingTest(minitest.simpleTestUnit):
else:
res+=" "+str(int(hx,16))
return res
class ConfigTest(minitest.simpleTestUnit):
def __init__(self):
super(ConfigTest, self).__init__("Testing the config loader")
def _testAll(self):
self.currentTest("Loading config")
from mapping import GrandMA2
GrandMA2.MidiInterface("patch/test.ini")
self.addSuccess()
allTests.addTest(mappingTest())
allTests.addTest(ConfigTest())
allTests.test()