From 2ba5115cc099262d39dbb0abda55a41f0cd4cd33 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Mon, 11 Oct 2021 05:40:02 +0200 Subject: [PATCH 1/7] Good amount of refactor --- mapping/midipagehandler.py | 239 +++++++++++++++++++++++++++++-------- mapping/miniDebug.py | 18 +++ mapping/panapulse.py | 8 +- mapping/utils.py | 73 +++++++++++ pythonAnalogWay | 2 +- 5 files changed, 289 insertions(+), 51 deletions(-) create mode 100644 mapping/miniDebug.py create mode 100644 mapping/utils.py diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index 2fb43c4..95a4c99 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -1,6 +1,6 @@ ########################### # IMPORTS - +import mido ########################### # FUNCTION DEFINES @@ -28,42 +28,49 @@ if _VERBOSE>=4: ########################### # CLASS DEFINES -class lightHandler(): - def __init__(self,statusList,listAssociations): - self.page=0 - self.output=None - self.statusList={} - self.statusAssociation={} - self.lastpress=(None,None) #Does only account for the 8x8 - self.selected_pulse=(None,None) - self.live_pulse=(None,None) - self.addStatusList(statusList) - self.initialiseColor() - self.associateColor(listAssociations) +class IOInterface(): + "Handle the IO actions between an external script and a midiPageHandler interface" + def __init__(self,pagehandler): + self._pageHandler=pagehandler + self._listActionsH={} + self._listActionsIO={} + self._pageHandler.IOInterface=self - def addStatusList(self,statusList): - 'Add a list of status' - self.statusList=statusList - self.maxStatus=max(self.statusList.values()) + def addActionH(self,matchName,action): + """Associate a function to a match to a message received + [externalP] -> Action -> [Handler] + """ + self._listActionsH[matchName]=action - def initialiseColor(self,default=0): - "Initialise the the colorstatus" - for status in range(self.maxStatus*2-1): - self.statusAssociation[status]=default + def addActionIO(self,name,action): + """Associate a function to match to a handler action + [Handler] -> Action -> [externalP] + """ + self._listActionsIO[name]=action - def associateColor(self,listAssociations): - "Associate a status combination with a color" - for status,color in listAssociations.items(): - self.statusAssociation[status]=color + def messageReceived(self,messageMatch,note,*args): + """Acknoledge a message and do the appropriate actions + [externalP] -> messageReceived -> Action -> [Handler] + """ + try: + self._listActionsH[messageMatch.groups("msg")](messageMatch,note,*args) + except KeyError: + wprint("The message type doesn't exits",messageMatch) - def lightcolor(self,col,row,color): - self.light(col,row,val=_COLORS[color]) + def noteReceived(self,note,val): + """Acknoledge a control received and do the appropriate actions + [internalMidiAction] -> [Handler] + """ + self.handler.noteReceived(note,val) - def light(self,col,row,val=1): - self.lightnote(self.findit(col,row),val) - - def lightnote(self,note,val=1): - self.output.send(mido.Message("note_on",note=note,velocity=val)) + def sendAction(self,name,*args): + """An action is to be sent to the external Program + [Handler] -> [externalP] + """ + try: + self._listActionsIO[name](*args) + except KeyError: + wprint("Can't send action request",name) class midiPageHandler(object): "Page Handler, with some methods to manage a midi remote more easily" @@ -77,14 +84,32 @@ class midiPageHandler(object): self._changedbasevalues=[] # Store the active values, not yet updated self._heightV=0 self._widthV=0 - self._changes=set() + self.IOInterface=None + self.newListChanges() self._listPossibleValues={None:0b0} + self.possibleStatus={} self.__maxV=0b1 self._page=0 self._maxpages=pages self._maxN=0 self._makeNotes(table) + ################### + # Important methods for Access + def addStatusPos(self,statusName,linecol,page=None): + "Apply a status to a position, applied when applyChanges is called" + + def getColorPos(self,linecol): + "Get the active color from a position" + + def listNoteChanges(self): + "Yield the list of (note,value) to update" + for pos in self.listChanges(): + yield self.posToNote(pos),self.colorFrom(pos) + + def noteReceived(self,note,val): + "A note has been received, do the appropriate actions" + pass #################### # Manage attributes def _makeNotes(self,table): @@ -126,6 +151,15 @@ class midiPageHandler(object): self.__maxV*=2 return True + # def makeAssociationTable(self): + # "Make a table to contain all associations" + # self.statusList=statusList + # self.maxStatus=max(self.statusList.values()) + # for status in range(self.maxStatus*2-1): + # self.statusAssociation[status]=default + # def addAssociation(self,status,color): + # "Add an association of status and color, must be used after makeAssociationTable" + def listStatus(self): "Return the list of all values" return self._listPossibleValues @@ -138,9 +172,10 @@ class midiPageHandler(object): #################### # Page Changes def changePage(self,page): - "Try to change page" + "Try to change page, warning all pending changes will be lost" try: self._activebasevalues=self._basevalues[page] + self.newListChanges() self.newChangedValues() self._redrawPageChange(self._page,page) self._page=page @@ -168,7 +203,6 @@ class midiPageHandler(object): if self._changedbasevalues[i][j]!=self._activebasevalues[i][j]: self.addChange((i,j)) - #################### # Modifiers methods @@ -180,12 +214,19 @@ class midiPageHandler(object): return 0 return self._listPossibleValues[namestatus] - def addStatuses(self,linecol,status): - "Add a status by name to a position" - for status in status: + # def addStatus(self,linecol,status): + # "Add a status by name to a position" + # self.addStatusId(linecol,self.statusId(status)) + + def addStatus(self,linecol,*statuses): + "Add a list of statuses by name to a position" + # if type(statuses)==str: + # self.addStatusId(linecol,self.statusId(statuses)) + for status in statuses: self.addStatusId(linecol,self.statusId(status)) - def removeStatuses(self,linecol,liststatus): + + def removeStatus(self,linecol,*liststatus): "Remove a list of status, by name" for status in liststatus: self.removeStatusId(linecol,self.statusId(status)) @@ -217,12 +258,25 @@ class midiPageHandler(object): for change in self._changes: yield change + def newListChanges(self): + "Add a new list of changes" + self._changes=set() + def applyChanges(self): "Apply all changes and erase them, then reload another _changedbasevalues" for i,j in self.listChanges(): self._activebasevalues[i][j]=self._changedbasevalues[i][j] - self._changes=set() + #self.newListChanges() + def colorFrom(self,linecol): + "Obtain color from the linecol" + return (self.possibleStatus[self.getTableElt(self._activebasevalues,linecol)]) + + def posToNote(self,linecol): + return self.noteFrom(linecol) + def noteFrom(self,linecol): + "Obtain note from the linecol" + return self.getTableElt(self._posToNote,linecol) ###################### # Table utilities @@ -251,6 +305,7 @@ class midiPageHandler(object): for i in range(len(values)): table[i][col]=values[i] + #################### # Operator definitions @@ -294,7 +349,7 @@ class AkaiAPCMini(midiPageHandler): self._updateSize() self.colors={"black":0,"green":1,"blinking_green":2,"red":3,"blinking_red":4,"yellow":5,"blinking_yellow":6} self.addPossibleValues(("Inactive","Active","Selected","Live")) - _INACTIVE,_ACTIVE,_LIVE,_SELECTED=self.statusId("Inactive"),self.statusId("Active"),self.statusId("Selected"),self.statusId("Live") + _INACTIVE,_ACTIVE,_LIVE,_SELECTED=self.statusId("Inactive"),self.statusId("Active"),self.statusId("Live"),self.statusId("Selected") self.possibleStatus={ 0: self.colors["black"], @@ -315,23 +370,93 @@ class AkaiAPCMini(midiPageHandler): _ACTIVE|_LIVE|_SELECTED: self.colors["blinking_red"], _ACTIVE|_INACTIVE|_LIVE: self.colors["blinking_red"], #Just live active _ACTIVE|_INACTIVE|_SELECTED:self.colors["blinking_green"], #Just selected active - _INACTIVE|_LIVE|_SELECTED: self.colors["blinking_red"], # Very debatable + _INACTIVE|_LIVE|_SELECTED: self.colors["blinking_red"], # Very debatable _ACTIVE|_LIVE|_INACTIVE|_SELECTED:self.colors["blinking_red"] #Just live active selected } - self.colorHandler=lightHandler(self.listStatus(),self.possibleStatus) - # self.changePage(0) + self.output=None + self.poslastpressed=(0,0) + self.idlastlayerpressed=0 + self.lastlayerpressed=(0,0) + self.idlastmemorypressed=0 + self.offset=0 # Offset on the lines + for j in range(3): + for i in range(8): + self.addStatus((j,i),"Inactive") + self.addStatus((3,0),"Inactive") + self.addStatus((3,1),"Active") + self.addStatus((3,2),"Live") + self.addStatus((3,3),"Selected") + self.addStatus((3,4),"Active","Live") + self.addStatus((3,5),("Active","Live","Selected")) + self.addStatus((3,6),("Inactive","Selected")) + self.addStatus((3,7),"Active") + + def noteReceived(self,note,val): + "A note has been received" + self.poslastpressed=self._noteToPos[note] + line,col=self.poslastpressed + print("Note received") + if line==0 or line==1: # It's a layer1/2 command + self.layerPress((line,col),line,val,0) + elif line==2: + self.idlastmemorypressed=col + elif line==7: + self.lastVPpressed=col + # elif line==8: + # lastpagewhateverpressed=col + + def layerPress(self,linecol,layer,val,liveprev): + "Adjust the color and info depending on the press" + self.idlastlayerpressed=layer + line,col=linecol + if layer==0: + self.removeStatus((0,self.lastlayerpressed[0]),"Selected") + # 0 is the Id of the first layer on the remote, having an offset would be a great idea + self.lastlayerpressed[0]=col + + else: + self.removeStatus((1,self.lastlayerpressed[1]),"Selected") + self.lastlayerpressed[1]=col + + + self.IOInterface.sendAction("layerchange",layer,col,liveprev) + self.addStatus((line,col),"Selected") + self.applyChanges() + self.applyColors() + + def addInterfaceOut(self,interfaceOut): + "Add one interface to send midi messages to, could be done another way" + self.output=interfaceOut + self.applyChanges() + self.applyColors() + + def applyColors(self): + 'Apply all the colorchanges' + for note,val in self.listNoteChanges(): + self.lightnote(note,val) + + def lightcolor(self,col,row,color): + self.light(col,row,val=_COLORS[color]) + + def light(self,col,row,val=1): + self.lightnote(self.findit(col,row),val) + + def lightnote(self,note,val=1): + self.output.send(mido.Message("note_on",note=note,velocity=val)) + + + _TEST=True if __name__ == '__main__': ak=AkaiAPCMini() ak.prettyPrint(ak._posToNote) - # ak.addPossibleValues(("Inactive","Active","Selected","Live")) for i,v in ak._listPossibleValues.items(): print("{}:{:b}".format(i,v)) - ak.addStatuses((2,1),("Active","Selected","Live")) + ak.addStatus((2,1),"Active","Selected","Live") ak.addStatusId((5,5),ak.statusId("Active")) ak.addStatusId((5,5),ak.statusId("Selected")) ak.addStatusId((5,7),ak.statusId("Live")) @@ -345,9 +470,25 @@ if __name__ == '__main__': ak.prettyPrint(ak._changedbasevalues) ak.removeStatusId((2,1),ak.statusId("Live")) ak.prettyPrint(ak._changedbasevalues) - ak.removeStatuses((5,5),("Active","Selected")) + ak.removeStatus((5,5),"Active","Selected") ak.prettyPrint(ak._changedbasevalues) print(ak.statusId(("Active","Selected","Live"))) - ak. - # light=lightHandler(ak.listStatus(),{}) + + ak.addStatus((3,3),"Active") + ak.addStatus((3,3),"Active") + ak.removeStatus((3,3),"Active") + ak.removeStatus((3,3),"Active") + ak.addStatus((3,3),"Active","Selected") + ak.removeStatus((3,3),"Active") + ak.addStatus((3,3),"Active","Live") + ak.removeStatus((3,3),"Live") + ak.prettyPrint(ak._changedbasevalues) + ak.prettyPrint(ak._activebasevalues) + ak.applyChanges() + ak.prettyPrint(ak._activebasevalues) + print(ak._changes) + + for note,val in ak.listNoteChanges(): + print (note,val) + print(ak.colorFrom((3,3)),ak.noteFrom((3,3))) diff --git a/mapping/miniDebug.py b/mapping/miniDebug.py new file mode 100644 index 0000000..d0ff03c --- /dev/null +++ b/mapping/miniDebug.py @@ -0,0 +1,18 @@ +#!/bin/python +# Mini debugging tool, will get his own project at some point + + +__DEBUG_LISTING={} +###################### +# The listing is supposed to be composed of : +# DEBUG[MODULE][SCOPE][FUNCTIONS]=(usage,cputimeused) + +def debugListing(function,scope=None): + "Add a function to the debug listing, on a custom category" + _name,_usage=function.__name__,0 + __DEBUG_LISTING[_name]=[_usage,0] + def returnFunction(*args,**kwargs): + _usage+=1 + __DEBUG_LISTING[_name]=[_usage,0] + function(*args,**kwargs) + return returnFunction diff --git a/mapping/panapulse.py b/mapping/panapulse.py index 97f76e5..0ba57bf 100644 --- a/mapping/panapulse.py +++ b/mapping/panapulse.py @@ -4,6 +4,7 @@ from mapping.midi import MessageParse from mapping.midi import Actions import sys +from mapping.utils import doublepress ########################### # FUNCTION DEFINES @@ -50,18 +51,23 @@ class pulseLink(object): def _onload(self): "Send a reset colors" import time,sys + handler.addInterfaceOut(self.interfaceOut(1)) + IOInterface=midiPageHandler.IOInterface(handler) #vars.output=self.outputs[vars.interface_nb] def pagepress(trigger,val,note,*params): "A key was pressed on the pagebuttons area" try: - print(handler._noteToPos[note]) + # print(handler._noteToPos[note]) + handler.noteReceived(note,val) except TypeError as e: eprint("[Error] : Unassigned pagebutton {} - Note {:2} ({:3})".format(trigger,note,val)) eprint(e) +@doublepress def quitpress(trigger,val,note,*params): + # handler. print("Quitting...") sys.exit() diff --git a/mapping/utils.py b/mapping/utils.py new file mode 100644 index 0000000..0977d18 --- /dev/null +++ b/mapping/utils.py @@ -0,0 +1,73 @@ +#!/bin/python + +from threading import Timer + +################ +# Print Functions + +############## +#Classes + +class emptyClass(object): + def __init__(self): + pass + + def __call__(self,*args,**kwargs): + return self + + def __repr__(self,*args,**kwargs): + return '' + + def __getattr__(self,*args,**kwargs): + return self + +class emptyVars(): + def __init__(self): + self.doublepressed_timer={} + self.doublepressed_prot={} + + def lightnote(self,note,val): + "Note to light" + print("Should light",note,val) +################ +# Decorators + +__DEFAULT_VARS=emptyVars() + +def doublepress(funct,vars=__DEFAULT_VARS):#Note,color vars.lightnote(vars.BASE_NOTE_ARM_TAKE,1) + "Offer a doublepress protection to a function" + # print("Building doublepress protection for",funct.__name__) + vars.doublepressed_prot[funct.__name__]=False + vars.doublepressed_timer[funct.__name__]=_NOTIMER + def _doubleProtected(*args,**kwargs): + if vars.doublepressed_prot[funct.__name__]: + # print("Launching function",funct.__name__,args,kwargs) + vars.doublepressed_prot[funct.__name__]=False + vars.doublepressed_timer[funct.__name__].cancel() + funct(*args,**kwargs) + else: + # print("Launching the timer for",funct.__name__,args,kwargs) + vars.doublepressed_timer[funct.__name__].cancel() + vars.doublepressed_timer[funct.__name__]=Timer(_TIMERTAKE, deactivate(funct.__name__)) + vars.doublepressed_prot[funct.__name__]=True + vars.doublepressed_timer[funct.__name__].start() + return _doubleProtected + +def deactivate(name,note=None,color=None,vars=__DEFAULT_VARS): + "Reset the press count of a button" + def _timedDesactivation(): + # print("Deactivating: ",name) + vars.doublepressed_timer[name].cancel() + vars.doublepressed_prot[name]=False + vars.doublepressed_timer[name]=_NOTIMER + if note!=None: + #if color==None: color=BASECOLOR[Note] + vars.lightnote(note,color) + + return _timedDesactivation + +############## +# Definitions +_NOTIMER=emptyClass() +_EMPTYVARS=emptyVars() +_TIMERTAKE=5 \ No newline at end of file diff --git a/pythonAnalogWay b/pythonAnalogWay index b244c75..5f63726 160000 --- a/pythonAnalogWay +++ b/pythonAnalogWay @@ -1 +1 @@ -Subproject commit b244c7542fd145a408b2eaaebb071c940472d8f9 +Subproject commit 5f637262359e1d7932ea6a07ddae2180b814db75 From 9b8e6ad0859cfdc6d013dc9505fc469ae4afdcf0 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Mon, 11 Oct 2021 06:11:50 +0200 Subject: [PATCH 2/7] Couple more on the handler --- mapping/midipagehandler.py | 47 +++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index 95a4c99..e61b674 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -378,30 +378,25 @@ class AkaiAPCMini(midiPageHandler): self.output=None self.poslastpressed=(0,0) self.idlastlayerpressed=0 - self.lastlayerpressed=(0,0) + self.lastlayerpressed=[0,0] self.idlastmemorypressed=0 self.offset=0 # Offset on the lines for j in range(3): for i in range(8): self.addStatus((j,i),"Inactive") - self.addStatus((3,0),"Inactive") - self.addStatus((3,1),"Active") - self.addStatus((3,2),"Live") - self.addStatus((3,3),"Selected") - self.addStatus((3,4),"Active","Live") - self.addStatus((3,5),("Active","Live","Selected")) - self.addStatus((3,6),("Inactive","Selected")) - self.addStatus((3,7),"Active") + + for j in range(3,8): + for i in range(8): + self.addStatus((j,i),None) - def noteReceived(self,note,val): + def noteReceived(self,note,val): # Just for testing, all theese orders come from the pulse "A note has been received" self.poslastpressed=self._noteToPos[note] line,col=self.poslastpressed - print("Note received") if line==0 or line==1: # It's a layer1/2 command self.layerPress((line,col),line,val,0) elif line==2: - self.idlastmemorypressed=col + self.memoryPress((line,col),val,0) elif line==7: self.lastVPpressed=col # elif line==8: @@ -411,21 +406,27 @@ class AkaiAPCMini(midiPageHandler): "Adjust the color and info depending on the press" self.idlastlayerpressed=layer line,col=linecol - if layer==0: - self.removeStatus((0,self.lastlayerpressed[0]),"Selected") - # 0 is the Id of the first layer on the remote, having an offset would be a great idea - self.lastlayerpressed[0]=col - - else: - self.removeStatus((1,self.lastlayerpressed[1]),"Selected") - self.lastlayerpressed[1]=col - - + self.removeStatus((line,self.lastlayerpressed[layer]),"Selected") + self.lastlayerpressed[layer]=col self.IOInterface.sendAction("layerchange",layer,col,liveprev) - self.addStatus((line,col),"Selected") + if liveprev==0: + self.addStatus(linecol,"Selected") + else: + self.addStatus(linecol,"Live") self.applyChanges() self.applyColors() + def memoryPress(self,linecol,val,liveprev): + """Adjust the color and info of a memory press (take or preview) + Should be Green if defined and Yellow if not, selecting makes it prev""" + line,col=linecol + # self.removeStatus((line,self.idlastmemorypressed),"Selected") + # self.idlastmemorypressed=col + # self.addStatus(linecol,"Selected") + self.IOInterface.sendAction("memorychange",col,liveprev) + # self.applyChanges() + # self.applyColors() + def addInterfaceOut(self,interfaceOut): "Add one interface to send midi messages to, could be done another way" self.output=interfaceOut From 757c43bb9f147c7356228ec733ae6b7e97f7aefb Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Mon, 11 Oct 2021 22:06:58 +0200 Subject: [PATCH 3/7] Couple updates on the interconnection --- README.md | 2 + mapping/midipagehandler.py | 132 ++++++++++++++++++++++++------------- mapping/panapulse.py | 12 ++-- pythonAnalogWay | 2 +- 4 files changed, 97 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 1ec7ff6..053b8c5 100644 --- a/README.md +++ b/README.md @@ -50,3 +50,5 @@ To do so add a custom patch (or use a currently defined one, but chances are pat * TODO: Pagehandler: make a note handler * TODO: Color management, get colors associated to all statuses * TODO: General decorators @armtake + +* URGENT : Fix the connection issue \ No newline at end of file diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index e61b674..6636db6 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -30,11 +30,12 @@ if _VERBOSE>=4: # CLASS DEFINES class IOInterface(): "Handle the IO actions between an external script and a midiPageHandler interface" - def __init__(self,pagehandler): + def __init__(self,pagehandler,remoteController): self._pageHandler=pagehandler self._listActionsH={} self._listActionsIO={} self._pageHandler.IOInterface=self + self._externalProgram=remoteController def addActionH(self,matchName,action): """Associate a function to a match to a message received @@ -274,6 +275,7 @@ class midiPageHandler(object): def posToNote(self,linecol): return self.noteFrom(linecol) + def noteFrom(self,linecol): "Obtain note from the linecol" return self.getTableElt(self._posToNote,linecol) @@ -339,6 +341,70 @@ class midiPageHandler(object): print(" "+lineM.format(*elt)) print(sep) + +class pulseController(object): + "Receive controls over a specific range and map them to commands to send" + def __init__(self,IOInterface,returnInterface,ranges={j:j for j in range(3)}): + self.ranges=ranges + self.retunRanges={i:j for j,i in ranges.items()} + _ALL_MESSAGE_TYPES=[ + "STATUS","LAYERINP","TAKE","TAKEALL","LOADMM","QUICKF" + ] + self.returnInterface=returnInterface + self.IOInterface=IOInterface + self.output=None + self.poslastpressed=(0,0) + self.idlastlayerpressed=0 + self.lastlayerpressed=[0,0] + self.idlastmemorypressed=0 + self.offset=0 # Offset on the lines + + def pressReceived(self,linecol,val): + "Received an order from the controller, the order must be associated with an actual command and send it to the IOController" + try: + line,col=linecol + trueline=self.ranges[line] + if trueline==0: # It's a press on layer A + self.layerPress((trueline,col),trueline,val,0) + elif trueline==1: # It's a press on layer B + self.layerPress((trueline,col),trueline,val,0) + elif trueline==2: # It's a memory press + self.memoryPress((trueline,col),val,0) + else: + pass # The pulse only takes 3 lines + except KeyError as e: + wprint("An error occured while the pulse was processing order",e) + + def layerPress(self,linecol,layer,val,liveprev): + "Adjust the color and info depending on the press" + self.idlastlayerpressed=layer + line,col=linecol + trueline=self.retunRanges[line] + truelinecol=(trueline,col) + self.returnInterface.removeStatus((trueline,self.lastlayerpressed[layer]),"Selected") + self.lastlayerpressed[layer]=col + self.IOInterface.sendAction("LAYERINP",layer,col,liveprev) + if liveprev==0: + self.returnInterface.addStatus(truelinecol,"Selected") + else: + self.returnInterface.addStatus(truelinecol,"Live") + self.returnInterface.applyChanges() + self.returnInterface.applyColors() + + def memoryPress(self,linecol,val,liveprev): + """Adjust the color and info of a memory press (take or preview) + Should be Green if defined and Yellow if not, selecting makes it prev""" + line,col=linecol + # self.removeStatus((line,self.idlastmemorypressed),"Selected") + # self.idlastmemorypressed=col + # self.addStatus(linecol,"Selected") + self.IOInterface.sendAction("LOADMM",col,liveprev) + # self.applyChanges() + # self.applyColors() + + def __repr__(self): + return("PulseController{} ({self.idlastlayerpressed},{self.idlastmemorypressed})".format(list(self.ranges.keys()),self=self)) + class AkaiAPCMini(midiPageHandler): "A specific implementation of the page handler" @@ -375,57 +441,32 @@ class AkaiAPCMini(midiPageHandler): _ACTIVE|_LIVE|_INACTIVE|_SELECTED:self.colors["blinking_red"] #Just live active selected } - self.output=None - self.poslastpressed=(0,0) - self.idlastlayerpressed=0 - self.lastlayerpressed=[0,0] - self.idlastmemorypressed=0 - self.offset=0 # Offset on the lines - for j in range(3): + self.listModules=[[None]*8] # Only one page and 8x8 for now + # self.pulse1=pulseController(self,IOInterface) + ########### + # For debug purposes + for j in range(5): for i in range(8): self.addStatus((j,i),"Inactive") - for j in range(3,8): + for j in range(5,8): for i in range(8): self.addStatus((j,i),None) - def noteReceived(self,note,val): # Just for testing, all theese orders come from the pulse - "A note has been received" - self.poslastpressed=self._noteToPos[note] - line,col=self.poslastpressed - if line==0 or line==1: # It's a layer1/2 command - self.layerPress((line,col),line,val,0) - elif line==2: - self.memoryPress((line,col),val,0) - elif line==7: - self.lastVPpressed=col - # elif line==8: - # lastpagewhateverpressed=col + def noteReceived(self,note,val): + line,col=self._noteToPos[note] + try: + self.listModules[self._page][line].pressReceived((line,col),val) + except Exception as e: + wprint("No module loaded for Line {line}: {e}".format(line=line,e=e)) + wprint("List of modules available on page {page} is : {modules}".format(page=self._page,modules=self.listModules[self._page])) - def layerPress(self,linecol,layer,val,liveprev): - "Adjust the color and info depending on the press" - self.idlastlayerpressed=layer - line,col=linecol - self.removeStatus((line,self.lastlayerpressed[layer]),"Selected") - self.lastlayerpressed[layer]=col - self.IOInterface.sendAction("layerchange",layer,col,liveprev) - if liveprev==0: - self.addStatus(linecol,"Selected") - else: - self.addStatus(linecol,"Live") - self.applyChanges() - self.applyColors() - - def memoryPress(self,linecol,val,liveprev): - """Adjust the color and info of a memory press (take or preview) - Should be Green if defined and Yellow if not, selecting makes it prev""" - line,col=linecol - # self.removeStatus((line,self.idlastmemorypressed),"Selected") - # self.idlastmemorypressed=col - # self.addStatus(linecol,"Selected") - self.IOInterface.sendAction("memorychange",col,liveprev) - # self.applyChanges() - # self.applyColors() + def addModule(self,rackmodule,rangeActive): + "Add a module to the controller, the range of control must be specified" + module=rackmodule(self.IOInterface,self,{i:j for i,j in zip(rangeActive,range(len(rangeActive)))}) + print({i:j for i,j in zip(rangeActive,range(len(rangeActive)))}) + for i in rangeActive: + self.listModules[self._page][i]=module def addInterfaceOut(self,interfaceOut): "Add one interface to send midi messages to, could be done another way" @@ -449,7 +490,6 @@ class AkaiAPCMini(midiPageHandler): - _TEST=True if __name__ == '__main__': ak=AkaiAPCMini() diff --git a/mapping/panapulse.py b/mapping/panapulse.py index 0ba57bf..24ba94a 100644 --- a/mapping/panapulse.py +++ b/mapping/panapulse.py @@ -5,6 +5,7 @@ from mapping.midi import Actions import sys from mapping.utils import doublepress +from pythonAnalogWay import bindings ########################### # FUNCTION DEFINES @@ -51,11 +52,14 @@ class pulseLink(object): def _onload(self): "Send a reset colors" import time,sys + HOSTS=[["127.0.0.1",3000]] # Test server + ctrl1=bindings.analogController(*HOSTS[0]) + ctrl1.connectionSequence() + #ctrl1.keepPinging() handler.addInterfaceOut(self.interfaceOut(1)) - IOInterface=midiPageHandler.IOInterface(handler) - - #vars.output=self.outputs[vars.interface_nb] - + IOInterface=midiPageHandler.IOInterface(handler,ctrl1) + handler.addModule(midiPageHandler.pulseController,[4,1,2]) + def pagepress(trigger,val,note,*params): "A key was pressed on the pagebuttons area" try: diff --git a/pythonAnalogWay b/pythonAnalogWay index 5f63726..b0ae5c3 160000 --- a/pythonAnalogWay +++ b/pythonAnalogWay @@ -1 +1 @@ -Subproject commit 5f637262359e1d7932ea6a07ddae2180b814db75 +Subproject commit b0ae5c321e411c1c7d8a24ba16c0cccb442b8d13 From 892f6a734b5d6500126d51d1ef5b432cdb561c14 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Mon, 11 Oct 2021 22:43:36 +0200 Subject: [PATCH 4/7] A little more interconnection --- README.md | 3 ++- mapping/midipagehandler.py | 21 ++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 053b8c5..8718aaf 100644 --- a/README.md +++ b/README.md @@ -51,4 +51,5 @@ To do so add a custom patch (or use a currently defined one, but chances are pat * TODO: Color management, get colors associated to all statuses * TODO: General decorators @armtake -* URGENT : Fix the connection issue \ No newline at end of file +* URGENT : Fix the connection issue +* TODO: Connect the IOHandler with handler, binding and vice-versa, check some. \ No newline at end of file diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index 6636db6..5eb3ed3 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -73,6 +73,20 @@ class IOInterface(): except KeyError: wprint("Can't send action request",name) +class IOInterfacePulse(IOInterface): + "Specialised pulse interface" + + def __init__(self,pagehandler,remoteController): + super(IOInterfacePulse,self).__init__(pagehandler,remoteController) + self.addActionIO("STATUS",self._externalProgram.getStatus) + self.addActionIO("LAYERINP",self._externalProgram.changeLayer) + self.addActionIO("TAKEALL",self._externalProgram.takeAll) + self.addActionIO("LOADMM",self._externalProgram.loadMM) + self.addActionIO("QUICKF",self._externalProgram.quickFrame) + self.addActionIO("FREEZE",self._externalProgram.freezeScreenAll) + + self.addActionH("LAYERINP",self._pageHandler.layerCommand) + class midiPageHandler(object): "Page Handler, with some methods to manage a midi remote more easily" @@ -359,6 +373,7 @@ class pulseController(object): self.idlastmemorypressed=0 self.offset=0 # Offset on the lines + def pressReceived(self,linecol,val): "Received an order from the controller, the order must be associated with an actual command and send it to the IOController" try: @@ -375,6 +390,10 @@ class pulseController(object): except KeyError as e: wprint("An error occured while the pulse was processing order",e) + def layerCommand(self,match): + "Received a layer command from the pulse, should be the only controller" + pass + def layerPress(self,linecol,layer,val,liveprev): "Adjust the color and info depending on the press" self.idlastlayerpressed=layer @@ -388,7 +407,7 @@ class pulseController(object): self.returnInterface.addStatus(truelinecol,"Selected") else: self.returnInterface.addStatus(truelinecol,"Live") - self.returnInterface.applyChanges() + self.returnInterface.applyChanges() self.returnInterface.applyColors() def memoryPress(self,linecol,val,liveprev): From ad7e0cf467044be93919c756c901e2d301628e37 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Tue, 12 Oct 2021 03:38:19 +0200 Subject: [PATCH 5/7] Added some interconection IO still to purge and a LOT of cleaning to do --- README.md | 4 +++- mapping/midipagehandler.py | 49 +++++++++++++++++++++----------------- mapping/panapulse.py | 21 ++++++++++++---- 3 files changed, 46 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 8718aaf..7ae2d04 100644 --- a/README.md +++ b/README.md @@ -52,4 +52,6 @@ To do so add a custom patch (or use a currently defined one, but chances are pat * TODO: General decorators @armtake * URGENT : Fix the connection issue -* TODO: Connect the IOHandler with handler, binding and vice-versa, check some. \ No newline at end of file +* TODO: More explicit midi output/input connection error (and backup or exit) +* TODO: CLEAN CONNECTION TO A RACK, ANYTHING BUT THIS CLUSTERF*CK +* TODO: Connect the IOHandler with handler, binding and vice-versa, check some. diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index 5eb3ed3..0d4ca73 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -34,29 +34,30 @@ class IOInterface(): self._pageHandler=pagehandler self._listActionsH={} self._listActionsIO={} - self._pageHandler.IOInterface=self + self._pageHandler._IOInterface=self self._externalProgram=remoteController - def addActionH(self,matchName,action): + def addActionIO(self,matchName,action): """Associate a function to a match to a message received [externalP] -> Action -> [Handler] """ self._listActionsH[matchName]=action - def addActionIO(self,name,action): + def addActionH(self,name,action): """Associate a function to match to a handler action [Handler] -> Action -> [externalP] """ self._listActionsIO[name]=action - def messageReceived(self,messageMatch,note,*args): + def messageReceived(self,typeM,messageMatch,*args): """Acknoledge a message and do the appropriate actions [externalP] -> messageReceived -> Action -> [Handler] """ try: - self._listActionsH[messageMatch.groups("msg")](messageMatch,note,*args) + dprint("Received the command {} from the pulse".format(messageMatch)) + self._listActionsH[typeM](messageMatch,*args) except KeyError: - wprint("The message type doesn't exits",messageMatch) + wprint("The message type doesn't exits",typeM) def noteReceived(self,note,val): """Acknoledge a control received and do the appropriate actions @@ -71,21 +72,25 @@ class IOInterface(): try: self._listActionsIO[name](*args) except KeyError: + print(self._listActionsIO) wprint("Can't send action request",name) class IOInterfacePulse(IOInterface): "Specialised pulse interface" - def __init__(self,pagehandler,remoteController): + def __init__(self,pagehandler,pulseModule,remoteController): super(IOInterfacePulse,self).__init__(pagehandler,remoteController) - self.addActionIO("STATUS",self._externalProgram.getStatus) + self._pulseModule=pulseModule + # Commands that should be sent to the pulse self.addActionIO("LAYERINP",self._externalProgram.changeLayer) self.addActionIO("TAKEALL",self._externalProgram.takeAll) self.addActionIO("LOADMM",self._externalProgram.loadMM) self.addActionIO("QUICKF",self._externalProgram.quickFrame) self.addActionIO("FREEZE",self._externalProgram.freezeScreenAll) - self.addActionH("LAYERINP",self._pageHandler.layerCommand) + # Command that are received from the pulse + self.addActionH("LAYERINP",self._pulseModule.layerCommand) + # self.addActionH("DETECTED",self._pulseModule.detected) class midiPageHandler(object): "Page Handler, with some methods to manage a midi remote more easily" @@ -99,7 +104,7 @@ class midiPageHandler(object): self._changedbasevalues=[] # Store the active values, not yet updated self._heightV=0 self._widthV=0 - self.IOInterface=None + self._IOInterface=None self.newListChanges() self._listPossibleValues={None:0b0} self.possibleStatus={} @@ -358,14 +363,13 @@ class midiPageHandler(object): class pulseController(object): "Receive controls over a specific range and map them to commands to send" - def __init__(self,IOInterface,returnInterface,ranges={j:j for j in range(3)}): + def __init__(self,returnInterface,ranges={j:j for j in range(3)}): self.ranges=ranges self.retunRanges={i:j for j,i in ranges.items()} _ALL_MESSAGE_TYPES=[ "STATUS","LAYERINP","TAKE","TAKEALL","LOADMM","QUICKF" ] self.returnInterface=returnInterface - self.IOInterface=IOInterface self.output=None self.poslastpressed=(0,0) self.idlastlayerpressed=0 @@ -373,7 +377,6 @@ class pulseController(object): self.idlastmemorypressed=0 self.offset=0 # Offset on the lines - def pressReceived(self,linecol,val): "Received an order from the controller, the order must be associated with an actual command and send it to the IOController" try: @@ -390,19 +393,21 @@ class pulseController(object): except KeyError as e: wprint("An error occured while the pulse was processing order",e) - def layerCommand(self,match): - "Received a layer command from the pulse, should be the only controller" - pass + def layerCommand(self,layer,col,liveprev): + "Received a layer command from the handler, will now translate it for the pulse TODO: CLEAN THIS HORRENDOUS THING" + dprint("Received command to change layer:{} to {} on {}(live/prev)".format(layer,col,liveprev)) + self.returnInterface._IOInterface._externalProgram.changeLayer(0,liveprev,layer,col) + # .changeLayer() def layerPress(self,linecol,layer,val,liveprev): - "Adjust the color and info depending on the press" + "Adjust the color and info depending on the press" # Bound to dissapear self.idlastlayerpressed=layer line,col=linecol trueline=self.retunRanges[line] truelinecol=(trueline,col) self.returnInterface.removeStatus((trueline,self.lastlayerpressed[layer]),"Selected") self.lastlayerpressed[layer]=col - self.IOInterface.sendAction("LAYERINP",layer,col,liveprev) + self.returnInterface._IOInterface.sendAction("LAYERINP",layer,col,liveprev) if liveprev==0: self.returnInterface.addStatus(truelinecol,"Selected") else: @@ -417,7 +422,7 @@ class pulseController(object): # self.removeStatus((line,self.idlastmemorypressed),"Selected") # self.idlastmemorypressed=col # self.addStatus(linecol,"Selected") - self.IOInterface.sendAction("LOADMM",col,liveprev) + self._IOInterface.sendAction("LOADMM",col,liveprev) # self.applyChanges() # self.applyColors() @@ -476,16 +481,16 @@ class AkaiAPCMini(midiPageHandler): line,col=self._noteToPos[note] try: self.listModules[self._page][line].pressReceived((line,col),val) - except Exception as e: + except AttributeError as e: wprint("No module loaded for Line {line}: {e}".format(line=line,e=e)) wprint("List of modules available on page {page} is : {modules}".format(page=self._page,modules=self.listModules[self._page])) def addModule(self,rackmodule,rangeActive): "Add a module to the controller, the range of control must be specified" - module=rackmodule(self.IOInterface,self,{i:j for i,j in zip(rangeActive,range(len(rangeActive)))}) - print({i:j for i,j in zip(rangeActive,range(len(rangeActive)))}) + module=rackmodule(self,{i:j for i,j in zip(rangeActive,range(len(rangeActive)))}) for i in rangeActive: self.listModules[self._page][i]=module + return module def addInterfaceOut(self,interfaceOut): "Add one interface to send midi messages to, could be done another way" diff --git a/mapping/panapulse.py b/mapping/panapulse.py index 24ba94a..3cc587d 100644 --- a/mapping/panapulse.py +++ b/mapping/panapulse.py @@ -53,12 +53,23 @@ def _onload(self): "Send a reset colors" import time,sys HOSTS=[["127.0.0.1",3000]] # Test server - ctrl1=bindings.analogController(*HOSTS[0]) - ctrl1.connectionSequence() - #ctrl1.keepPinging() + # The socket remote controller + controllerPulse=bindings.analogController(*HOSTS[0]) + + # Adding the midi interface to the controller handler.addInterfaceOut(self.interfaceOut(1)) - IOInterface=midiPageHandler.IOInterface(handler,ctrl1) - handler.addModule(midiPageHandler.pulseController,[4,1,2]) + + # The pulse module, bound to 3 lines + modulePulse=handler.addModule(midiPageHandler.pulseController,[4,1,2]) + + # The IO interface between the pulse and the controller, one IO is necessary per auxilliary application + IOInterface=midiPageHandler.IOInterfacePulse(handler,modulePulse,controllerPulse) + + # Finishing initialising the controller (Should be done in a thread to avoid locking) + controllerPulse.addFeedbackInterface(IOInterface) + controllerPulse.connectionSequence() + #controllerPulse.keepPinging() + def pagepress(trigger,val,note,*params): "A key was pressed on the pagebuttons area" From 945fcaaa52f49779ada74810ca198ccf81ca7fc5 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Tue, 12 Oct 2021 03:39:02 +0200 Subject: [PATCH 6/7] Update pythonAnalogWay --- pythonAnalogWay | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pythonAnalogWay b/pythonAnalogWay index b0ae5c3..8d7cf3e 160000 --- a/pythonAnalogWay +++ b/pythonAnalogWay @@ -1 +1 @@ -Subproject commit b0ae5c321e411c1c7d8a24ba16c0cccb442b8d13 +Subproject commit 8d7cf3e793b3cca67e51da6df4ed25c920845d29 From 24c2b19a5859b51b3f1036f08524b130635161c1 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Tue, 12 Oct 2021 03:57:13 +0200 Subject: [PATCH 7/7] Updating and fixing the binds --- mapping/midipagehandler.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/mapping/midipagehandler.py b/mapping/midipagehandler.py index 0d4ca73..e08e1f2 100644 --- a/mapping/midipagehandler.py +++ b/mapping/midipagehandler.py @@ -41,21 +41,21 @@ class IOInterface(): """Associate a function to a match to a message received [externalP] -> Action -> [Handler] """ - self._listActionsH[matchName]=action + self._listActionsIO[matchName]=action def addActionH(self,name,action): """Associate a function to match to a handler action [Handler] -> Action -> [externalP] """ - self._listActionsIO[name]=action + self._listActionsH[name]=action def messageReceived(self,typeM,messageMatch,*args): """Acknoledge a message and do the appropriate actions [externalP] -> messageReceived -> Action -> [Handler] """ try: - dprint("Received the command {} from the pulse".format(messageMatch)) - self._listActionsH[typeM](messageMatch,*args) + dprint("Received the command {} from the pulse ({})".format(typeM,messageMatch)) + self._listActionsIO[typeM](messageMatch,*args) except KeyError: wprint("The message type doesn't exits",typeM) @@ -69,10 +69,11 @@ class IOInterface(): """An action is to be sent to the external Program [Handler] -> [externalP] """ + dprint("Sending command {} with args {} to the pulse".format(name,args)) try: self._listActionsIO[name](*args) except KeyError: - print(self._listActionsIO) + print(self._listActionsH) wprint("Can't send action request",name) class IOInterfacePulse(IOInterface): @@ -393,10 +394,11 @@ class pulseController(object): except KeyError as e: wprint("An error occured while the pulse was processing order",e) - def layerCommand(self,layer,col,liveprev): + def layerCommand(self,screen,liveprev,layer,col): "Received a layer command from the handler, will now translate it for the pulse TODO: CLEAN THIS HORRENDOUS THING" dprint("Received command to change layer:{} to {} on {}(live/prev)".format(layer,col,liveprev)) - self.returnInterface._IOInterface._externalProgram.changeLayer(0,liveprev,layer,col) + # self.returnInterface._IOInterface._externalProgram.changeLayer(screen,liveprev,layer,col) + # Do the actual color changing # .changeLayer() def layerPress(self,linecol,layer,val,liveprev): @@ -407,7 +409,7 @@ class pulseController(object): truelinecol=(trueline,col) self.returnInterface.removeStatus((trueline,self.lastlayerpressed[layer]),"Selected") self.lastlayerpressed[layer]=col - self.returnInterface._IOInterface.sendAction("LAYERINP",layer,col,liveprev) + self.returnInterface._IOInterface.sendAction("LAYERINP",0,liveprev,layer,col) if liveprev==0: self.returnInterface.addStatus(truelinecol,"Selected") else: