Nearing completion, just to refine the matching

This commit is contained in:
Maximilien Rigaut 2019-05-06 04:48:22 +02:00
parent 613ad227fa
commit 6f5aeeed48
6 changed files with 146 additions and 37 deletions

View File

@ -5,7 +5,7 @@ To do so add a custom patch (or use a currently defined one, but chances are pat
# Depends
* Mostly mido (pip install mido) for the midi binding and rtmidi (sudo apt install python-rtmidi)
* test.py depends on the submodule minitest witch also depends on blessings (pip install blessings). test.py is not core of the program
* test.py depends on the submodule minitest witch also depends on blessings (pip install blessings). test.py is not a core part of the program
* This program is python3 compliant (as long as you install the python3 dependencies instead (pip3 install mido and install python3-rtmidi))
# Config Syntax

View File

@ -1,4 +1,4 @@
from mapping.base import BasicMessageParse,BasicAction,MatchError,BasicMidiInterface
from mapping.base import BasicMessageParse,BasicActions,MatchError,BasicMidiInterface
import mido
import re,configparser
@ -28,15 +28,34 @@ class MessageParse(BasicMessageParse):
# An Action object MUST be included in the file.
class Action(BasicAction):
class Actions(BasicActions):
"""The list of action to perform when a message is read"""
def __init__(self, interface):
super(Action, self).__init__(interface)
super(Actions, self).__init__(interface)
# This funtion is MANDATORY, it makes the link between MessageParse and Action
def __call__(self,match):
"Make the link between the regex and the action"
print(match)
action=commandlist[int(match.group('command'))]
id,value="1","1"
if action=="set":
data=match.group("data")
data=data.split(" ")
page=int(data[1])
id=int(data[0])
# value=int(data[2])/128+int(data[3])/1.28 the percent value
value=int(data[3]) # Just mapped from 0 to 127
elif action=="fire":
id=int(match.group("data")) # Can only be from 0 to 255 ?
value=""
#print(action,id,page)
try:
listact=self.findAction(action,id,page)
for act in listact:
act(value)
except:
# No action linked to the trigger
pass
# Same as above, import BasicMidiInterface as MidiInterface could be used instead

View File

@ -28,6 +28,14 @@ class BasicMidiInterface(object):
self.outputs[int(nb)]=self.openout(self.config["interface"][elt])
#self.outputs.append(self.config["interface"][elt])
def interfaceIn(self,number=1):
"Return the input interface, as of now number as no use"
return self.input
def interfaceOut(self,number):
"Return the output interface related to the number given"
return self.outputs[int(number)]
def openin(self,name):
"Try and open an output interface"
try:
@ -44,7 +52,15 @@ class BasicMidiInterface(object):
print("[ERROR] Impossible to open output {} (available are {})".format(name,mido.get_output_names()))
o=None
return o
def __delete__(self):
try:
for i in self.outputs:
i.close()
self.input.close
except:
pass
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"""
@ -57,15 +73,15 @@ class BasicMessageParse(object):
"""Take a midi SyxEx message and return a BasicAction (there can be many children of BasicAction to take more properly care of the cases)"""
return BasicMapping(self._mapping)
class BasicAction(object):
class BasicActions(object):
"""The list of action to perform when a message is read"""
def __init__(self,config):
def __init__(self,midiInterface):
"""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.config=midiInterface.config
self.interface=midiInterface
self.sections={}
self.outputs={} #Have every output in a dict THIS PART IS SUPPOSEDLY ALREADY TAKEN CARE OF
#self.outputs={} #Have every output in a dict THIS PART IS SUPPOSEDLY ALREADY TAKEN CARE OF
# 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)]
@ -75,7 +91,7 @@ class BasicAction(object):
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.outputs={1:self.config["interface"]["output1"], 2:self.config["interface"]["output2"]}
self.populateSections()
#self.prettyprint()
@ -150,9 +166,9 @@ class BasicAction(object):
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)]
return [BasicMidiTrigger(self.interface.interfaceOut(int(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()]))
print("[WARNING] Can't find interface {} for note {} action {}, legal interfaces are {}".format(interfaceout,note,action,[i for i in self.interface.output.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))
@ -216,6 +232,7 @@ class BasicMidiTrigger(object):
self.messagetype=messagetype
self.value=value
self.intensity=intensity
self.interface=interface
self.valuefn=None
message=RecognisedMessagesTypes[messagetype]
attributes={}
@ -247,7 +264,7 @@ class BasicMidiTrigger(object):
change=self.valtrue
else:
change=self.valfalse
if change!=self.value:
if change!=self.value and change != None and change !="":
self.value=change
self.valuetype[list(self.valuetype)[0]]=change
self.message=self.message.copy(**self.valuetype)
@ -256,7 +273,7 @@ class BasicMidiTrigger(object):
if self.toggle!=None:
self.toggle=not self.toggle
#print("SENDING:",self.message)
#self.interface.send(self.message) #Needs interface implementation
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"""

View File

@ -1,6 +1,26 @@
import mido
from mapping import GrandMA2
from test import toDec
import sys
if __name__ == '__main__':
o=mido.open_output("Midi Through Port-0")
print(o)
o.close()
Inter=GrandMA2.MidiInterface("patch/test.ini")
Par=GrandMA2.MessageParse()
Acts=GrandMA2.Actions(Inter)
#message=toDec("F0 7F 7F 02 7F 01 33 37 2E 32 30 30 00 35 20 31 F7")
#message=toDec("F0 7F 7F 02 7F 06 02 02 4C 39 F7")
try:
for msg in Inter.input:
print("Received {}".format(msg))
try:
match=Par(message)
res=Acts(match)
except GrandMA2.MatchError:
pass
except:
print("[Unexpected error] {}".format(sys.exc_info()[1]))
except KeyboardInterrupt:
print("[Keyboard Interrupt] : Exiting...")
del Inter
sys.exit()

View File

@ -1,7 +1,7 @@
[interface]
input=Midi Through Port-0
output1=Midi Through Port-0
output2=Akai Mix
output2=KMidimon
channelinput = 1
channelout1 = 1
channelout2 = 1
@ -20,6 +20,9 @@
56 = 1/note/127
# Function choosing the value to send, depending on the intensity received
56/val = lambda x: min(x,50)*2
[set/2]
1-100 = 1/cc/5;2/note/10
1-100/toggle = 10/124
[set/5]
1 = 1/cc/2;2/note/19/127

84
test.py
View File

@ -1,8 +1,7 @@
from minitest import minitest
import configparser,mido
#from mapping import GrandMA2
allTests=minitest.testGroup("Nominal test units",verbose=True,align=50)
class gmaPyTest(minitest.simpleTestUnit):
"""Testing the General interface"""
def __init__(self):
@ -36,7 +35,7 @@ class mappingTest(minitest.simpleTestUnit):
sucess=1
for X,D in zip(testX,testD):
#print("{} / {} : {} [{}]".format(X,D,self.toDec(X),D==self.toDec(X)))
if self.toDec(X)!=D:
if toDec(X)!=D:
self.addFailure("Can't convert Hex to Dec")
sucess=0
break
@ -51,7 +50,7 @@ class mappingTest(minitest.simpleTestUnit):
self.addSuccess()
self.currentTest("Test with well-formed message")
msg=self.toDec("F0 7F 7F 02 7F 01 32 31 2E 35 30 30 F7")
msg=toDec("F0 7F 7F 02 7F 01 32 31 2E 35 30 30 F7")
if self.testParse(msg):
self.addSuccess()
else:
@ -75,7 +74,19 @@ class mappingTest(minitest.simpleTestUnit):
self.currentTest("Loading Config")
try:
self.act=GrandMA2.Action("patch/test.ini")
class Emptyconfig():
def __init__(self,configfile):
self.config=configparser.ConfigParser()
self.config.read(configfile)
def interfaceOut(self,nb):
class EmptySender():
def __init__(self):
pass
def send(self,wev,**kwargs):
pass
return EmptySender()
self.act=GrandMA2.Actions(Emptyconfig("patch/test.ini"))
self.addSuccess()
except IOError:
self.addFailure("Can't load config file")
@ -158,15 +169,15 @@ class mappingTest(minitest.simpleTestUnit):
except:
self.addCritical("Can't parse (not supposed to happen)")
def toDec(self,message):
"Taken care of by mido, but testing needs to be done otherwise"
res=None
for hx in message.split(" "):
if res==None:
res=str(int(hx,16))
else:
res+=" "+str(int(hx,16))
return res
def toDec(message):
"Taken care of by mido, but testing needs to be done otherwise"
res=None
for hx in message.split(" "):
if res==None:
res=str(int(hx,16))
else:
res+=" "+str(int(hx,16))
return res
class ConfigTest(minitest.simpleTestUnit):
def __init__(self):
@ -178,6 +189,45 @@ class ConfigTest(minitest.simpleTestUnit):
GrandMA2.MidiInterface("patch/test.ini")
self.addSuccess()
allTests.addTest(mappingTest())
allTests.addTest(ConfigTest())
allTests.test()
class LiveTest(minitest.simpleTestUnit):
def __init__(self):
super(LiveTest, self).__init__("Live test")
def _testAll(self):
self.currentTest("Loading config")
from mapping import GrandMA2
Inter=GrandMA2.MidiInterface("patch/test.ini")
self.addSuccess()
self.currentTest("Loading message parser")
Par=GrandMA2.MessageParse()
self.addSuccess()
self.currentTest("Loading Patch")
Acts=GrandMA2.Actions(Inter)
self.addSuccess()
#Act.prettyprint()
self.currentTest("Trying match")
message=toDec("F0 7F 7F 02 7F 01 33 37 2E 32 30 30 00 35 20 31 F7")
message=toDec("F0 7F 7F 02 7F 06 02 02 4C 39 F7")
try:
match=Par(message)
self.addSuccess()
except GrandMA2.MatchError:
self.addFailure("Can't match '{}'".format(message))
except:
self.addFailure("Error while matching")
self.currentTest("Sending message")
match=Acts(match)
self.addSuccess()
if __name__ == '__main__':
allTests=minitest.testGroup("Nominal test units",verbose=True,align=50)
allTests.addTest(mappingTest())
allTests.addTest(ConfigTest())
allTests.addTest(LiveTest())
allTests.test()