Beispiel #1
0
def test_runFunctionAndReturns():
    caller = FunctionCaller('testCallerName')

    def function():
        return 1

    caller.addFunction('testFunction', function)
    assert caller.runFunction('testFunction') == 1
Beispiel #2
0
def test_runFunctionException():
    caller = FunctionCaller('testCallerName')

    def function():
        a = 1 / 0

    caller.addFunction('testFunction', function)
    assert caller.runFunction('testFunction') == None
Beispiel #3
0
def prepare():
    host = FunctionCaller('host')
    factHost = TCPReceiver(2232)
    factHost.parts[host.name] = host

    client = FunctionCaller('client')
    factClient = TCPClient('127.0.0.1', 2232)
    factClient.parts[client.name] = client
Beispiel #4
0
    def __init__(self, name:str):
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging')
        
        self.player = mpv.MPV(log_handler=print)
        self.player.set_loglevel('fatal')
    
        self.player.ontop=True
        self.player.volume=100
        self.player.image_display_duration=10
        self.player.border=False
        self.player.keep_open=True
        self.player.keep_open_pause=False
        self.player.screen=0
        self.player.geometry='500x500+700+500'
        self.fadingDelta=0
        self.fadingF=0.05
        self.rightChannel=True
        self.leftChannel=True

        #player.fullscreen=True
        #player.fs_screen=0
        self.caller=FunctionCaller(name)        
        @self.player.property_observer('eof-reached')
        def eof_reached(name,state):
            if state==True:
                self.caller.runFunction('end_file',str(self.player.filename))
        
        #Happens right before a new file is loaded. When you receive this, the player is loading the file (or possibly already done with it).
        @self.player.event_callback('start-file')
        def start_file(name):
            self.caller.runFunction('start_file',str(self.player.filename))
        
        def fade():
            try:
                prop = self.player._get_property('vf')
                brightness = float(prop[0]['params']['romax'])
                logging.debug("fade " + str(brightness))
                if self.fadingDelta != 0:
                    newBrightness=brightness+self.fadingDelta
                    if newBrightness >= 1.0:
                        self.fadingDelta=0
                        newBrightness=1.0
                        self.setBrightness(newBrightness)
                        self.caller.runFunction('unfaded',str(self.player.filename))
                    elif newBrightness <= 0:
                        self.fadingDelta=0
                        newBrightness=0#
                        self.setBrightness(newBrightness)
                        self.caller.runFunction('faded',str(self.player.filename))
                    else:
                        self.setBrightness(newBrightness)
            except Exception as e:
                logging.debug('Fade returned exception \'' + str(e) + '\'')
        self.setBrightness(1)
        self.loopCall = task.LoopingCall(fade)
Beispiel #5
0
def test_runNonExistantFunctionProcessor():
    caller = FunctionCaller('testCallerName')
    extname = ''

    def nameProcessor(name: str, arg1):
        nonlocal extname
        extname = name
        assert arg1 == 1
        assert name == 'unknownFunctionName'

    caller.unknownFunctionProcessor = nameProcessor
    caller.runFunction('unknownFunctionName', 1)
    assert extname == 'unknownFunctionName'
Beispiel #6
0
def test_runFunctionPositionalArgsTooManyArgs():
    caller = FunctionCaller('testCallerName')
    extvar1 = 0
    extvar2 = 0
    extvar3 = 0

    def function(arg1, arg2):
        nonlocal extvar1
        extvar1 = 1
        assert False
        return 1

    caller.addFunction('testFunction', function)
    res = caller.runFunction('testFunction', 1, 2, 3)
    assert res == None
    assert extvar1 == 0
Beispiel #7
0
def test_runFunctionErrorProcessor():
    caller = FunctionCaller('testCallerName')
    extvar1 = 0
    extvar2 = 0
    extvar3 = 0

    def function(arg1, arg2):
        nonlocal extvar1, extvar2, extvar3
        extvar1 = arg1
        extvar2 = arg2
        assert False

    caller.addFunction('testFunction', function)
    res = caller.runFunction('testFunction', arg2=2, arg1=1, arg3=3)
    assert res == None
    assert extvar1 == 0 and extvar2 == 0 and extvar3 == 0
Beispiel #8
0
class LoopPlayer:
    def __init__(self, name: str):
        self.names = []
        self.splayer = MpvSimple(name + '.simplePlayer')
        self.caller = FunctionCaller(name)
        self.splayer.caller.on_end_file(self.next)

    def next(self, filename):
        ind = self.names.index(filename)
        if ind == len(self.names) - 1:
            newInd = 0
        else:
            newInd = ind + 1
        self.splayer.player.loadfile(self.names[newInd])
        self.caller.runFunction('end_file', str(self.splayer.player.filename))

    def start(self, i: int = 0):
        self.splayer.player.loadfile(self.names[i])
Beispiel #9
0
 def __init__(self, factory ):
     LineReceiver.__init__(self)
     self.__factory=factory
     self.__parts=factory.parts
     self.setLineMode()
     self.__current_command_id: int = 3
     self.__issued_command_storage = {}
     self.__commandRE = re.compile('(\[(\S+)\])?([\S]+)\.(\S+)\((.*)\)')
     self.delimiter = b'\r'
     self.__parts['sys'] = FunctionCaller('sys')
Beispiel #10
0
def test_removeFunction():
    caller = FunctionCaller('testCallerName')

    def empty():
        pass

    caller.addFunction('emptyFunctionName', empty)
    caller.removeFunction('emptyFunctionName')
    assert 'emptyFunctionName' not in caller.getFunctionDict()
Beispiel #11
0
 def test_optimisation_asynchronous(self):
   """ Test optimisation. """
   self.report('Testing GA Optimiser with four workers asynchronously.')
   worker_manager = SyntheticWorkerManager(4, time_distro='halfnormal')
   func_caller = FunctionCaller(mlp_syn_func1, self.nn_domain)
   options, options_clone, reporter, _, mutation_op = self._get_optimiser_args('mlp')
   opt_val, opt_pt, history = ga_optimiser.ga_optimise_from_args(
     func_caller, worker_manager, 20, 'asy', mutation_op,
     options=options, reporter=reporter)
   self._test_optimiser_results(opt_val, opt_pt, history, options, options_clone)
   self.report('')
Beispiel #12
0
 def test_ga_optimisation_single(self):
   """ Test optimisation. """
   self.report('Testing GA Optimiser with just one worker.')
   worker_manager = SyntheticWorkerManager(1, time_distro='const')
   func_caller = FunctionCaller(cnn_syn_func1, self.nn_domain)
   options, options_clone, reporter, _, mutation_op = self._get_optimiser_args('cnn')
   opt_val, opt_pt, history = ga_optimiser.ga_optimise_from_args(
     func_caller, worker_manager, 20, 'asy', mutation_op,
     options=options, reporter=reporter)
   self._test_optimiser_results(opt_val, opt_pt, history, options, options_clone)
   self.report('')
Beispiel #13
0
 def test_instantiation(self):
   """ Test creation of object. """
   self.report('Testing GA Optimiser instantiation.')
   func_caller = FunctionCaller(cnn_syn_func1, self.nn_domain)
   worker_manager = SyntheticWorkerManager(1, time_distro='const')
   optimiser = ga_optimiser.GAOptimiser(func_caller,
     worker_manager, self.cnn_mutation_op, reporter='silent')
   self.report('Instantiated GAOptimiser object.')
   for attr in dir(optimiser):
     if not attr.startswith('_'):
       self.report('optimiser.%s = %s'%(attr, str(getattr(optimiser, attr))),
                   'test_result')
Beispiel #14
0
def test_sendClient():
    host = FunctionCaller('host')
    factHost = TCPReceiver(2232)
    factHost.parts[host.name] = host
    factHost.begin()

    def initClient():
        client = FunctionCaller('client')
        factClient = TCPClient('127.0.0.1', 2232)
        factClient.parts[client.name] = client
        factClient.begin()

    reactor.callLater(3.5, initClient)
    reactor.run()
Beispiel #15
0
def test_runFunctionNoArgs():
    caller = FunctionCaller('testCallerName')
    extvar = 0

    def function():
        nonlocal extvar
        extvar = 1

    caller.addFunction('testFunction', function)
    caller.runFunction('testFunction')
    assert extvar == 1
Beispiel #16
0
def test_runFunctionExceptionProcessor():
    caller = FunctionCaller('testCallerName')

    def function():
        a = 1 / 0

    caller.addFunction('testFunction', function)
    extName = ''
    extException = ''

    def checkException(name, exc):
        nonlocal extName, extException
        extName = name
        extException = str(exc)

    caller.functionErrorProcessor = checkException
    caller.runFunction('testFunction')
    assert extName == 'testFunction' and extException == 'division by zero'
Beispiel #17
0
def test_runFunctionPositionalArgs():
    caller = FunctionCaller('testCallerName')
    extvar1 = 0
    extvar2 = 0
    extvar3 = 0

    def function(arg1, arg2, arg3):
        nonlocal extvar1, extvar2, extvar3
        extvar1 = arg1
        extvar2 = arg2
        extvar3 = arg3

    caller.addFunction('testFunction', function)
    caller.runFunction('testFunction', 1, 2, 3)
    assert extvar1 == 1 and extvar2 == 2 and extvar3 == 3
Beispiel #18
0
def test_addNonFunction():
    caller = FunctionCaller('testCallerName')
    with pytest.raises(TypeError):
        caller.addFunction('returnerFunctionName', 'str')
Beispiel #19
0
                    return 'err'
        return 'ok'

    def runProcess():
        os.popen('sh ~/autorun.sh')
        return 'ok'

    def osRestart():
        os.system("sudo reboot")
        return

    def delayedSend(x):
        def f(x):
            fact.sendAll("somevent")

        reactor.callLater(3.5, f, "hello, world")

    dem = FunctionCaller("dem")
    dem.on_init(checkProcess)
    dem.on_check(checkProcess)
    dem.on_switch_off(closeProcess)
    dem.on_switch_on(runProcess)
    dem.on_restart(osRestart)
    dem.on_ds(delayedSend)

    fact = TCPReceiver(8007)
    fact.parts[dem.name] = dem
    fact.begin()

    reactor.run()
Beispiel #20
0
 def initClient():
     client = FunctionCaller('client')
     factClient = TCPClient('127.0.0.1', 2232)
     factClient.parts[client.name] = client
     factClient.begin()
Beispiel #21
0
class MpvSimple:

    def __init__(self, name:str):
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging')
        
        self.player = mpv.MPV(log_handler=print)
        self.player.set_loglevel('fatal')
    
        self.player.ontop=True
        self.player.volume=100
        self.player.image_display_duration=10
        self.player.border=False
        self.player.keep_open=True
        self.player.keep_open_pause=False
        self.player.screen=0
        self.player.geometry='500x500+700+500'
        self.fadingDelta=0
        self.fadingF=0.05
        self.rightChannel=True
        self.leftChannel=True

        #player.fullscreen=True
        #player.fs_screen=0
        self.caller=FunctionCaller(name)        
        @self.player.property_observer('eof-reached')
        def eof_reached(name,state):
            if state==True:
                self.caller.runFunction('end_file',str(self.player.filename))
        
        #Happens right before a new file is loaded. When you receive this, the player is loading the file (or possibly already done with it).
        @self.player.event_callback('start-file')
        def start_file(name):
            self.caller.runFunction('start_file',str(self.player.filename))
        
        def fade():
            try:
                prop = self.player._get_property('vf')
                brightness = float(prop[0]['params']['romax'])
                logging.debug("fade " + str(brightness))
                if self.fadingDelta != 0:
                    newBrightness=brightness+self.fadingDelta
                    if newBrightness >= 1.0:
                        self.fadingDelta=0
                        newBrightness=1.0
                        self.setBrightness(newBrightness)
                        self.caller.runFunction('unfaded',str(self.player.filename))
                    elif newBrightness <= 0:
                        self.fadingDelta=0
                        newBrightness=0#
                        self.setBrightness(newBrightness)
                        self.caller.runFunction('faded',str(self.player.filename))
                    else:
                        self.setBrightness(newBrightness)
            except Exception as e:
                logging.debug('Fade returned exception \'' + str(e) + '\'')
        self.setBrightness(1)
        self.loopCall = task.LoopingCall(fade)
        
    def setBrightness(self,x:int):
        self.player._set_property("vf",'colorlevels=romax='+str(x)+':gomax='+str(x)+':bomax='+str(x))

    def fade(self,time:int,finish:int = 0):
        prop = self.player._get_property('vf')
        brightness = float(prop[0]['params']['romax'])
        self.fadingDelta=(finish-brightness)/time*self.fadingF
        if not self.loopCall.running:
            reactor.callFromThread(self.loopCall.start,self.fadingF)

    def setSoundChannels(self,left:bool,right:bool):
        initStr=''
        if left:initStr+='|c0=c0'
        if right:initStr+='|c1=c1'
        self.leftChannel=left
        self.rightChannel=right
        logging.debug('Sound channels: left=' + str(self.leftChannel) + ',right='+str(self.rightChannel))
        self.player._set_property("af", "lavfi=[pan='stereo"+left+right+"']") 

        
    def play(self,filename:str):
        #logging.debug('Player ' + self.caller.name + ' begins playing file ' + filename)
        self.setBrightness(1)
        self.fadingDelta=0
        self.player.loadfile(filename)


        # @player.property_observer('time-pos')
        # def time_observer(_name, value):
            # caller.runFunction('time-pos')
            
        # @player.property_observer('filename')
        # def filename_observer(_name, value):
            # print('Filename ' + value)    
            
        # #Current position on playlist. The first entry is on position 0. Writing to this property may start playback at the new position.
        # @self.player.property_observer('playlist-pos')
        # def playlist(_name, value):
            # print(self)
            # self.caller.runFunction('playlist-pos',self.player.playlist_pos)   
                    
        #Happens after a file was unloaded. Typically, the player will load the next file right away, or quit if this was the last file.
        # @self.player.event_callback('end-file')
        # def end_observer(event):
            # self.caller.runFunction('end_file',str(event),str(self.player.filename),self.player._get_property("playlist-pos"))
            
        # #Start of playback after seek or after file was loaded
        # @self.player.event_callback('playback-restart')
        # def st_observer(name):
            # self.caller.runFunction('playback_restart',str(self.player.filename),self.player._get_property("playlist-pos"))
        
        # @self.player.property_observer('playlist-pos')
        # def my_handler(arg,arg2):
            # logging.debug("playlist-pos property " + str(arg) + ' ' + str(arg2))
            # self.caller.runFunction('playlist_pos',str(self.player.filename),self.player._get_property("playlist-pos"))

        # @self.player.event_callback('file-loaded')
        # def my_handler1(arg):
            # self.caller.runFunction('file_loaded',str(self.player.filename))
        
        #prop = mpv.player._get_property('vf')


            # print("file-loaded " + str(name))    
            
        #Start of playback after seek or after file was loaded.
        # @player.event_callback('playback-restart')
        # def ps_observer(name):
            # #if player.loop_file == 'inf':
            # #    changed(dict(code='playback-restart',oldFile=str(player.filename),newFile=str(player.filename))
            # logging.debug('playback-restart triggered')
            # logging.debug('filename:' + str(player.filename))
            # logging.debug('position in playlist:' + str(player.playlist_pos))
            
        #print(player.audio_device_list)
        #print(player.brightness)# = (-100)
        #player.contrast=100
        #print(player.brightness)# = (-100)
        #self.loadfile
        #player.command("vf","add","fade=type=out:start_time=1:duration=1")
        #player.command("vf","clr","")
        #player.command("vf","clr","")
        #this triggers only playback-restart
        #self.player.loop_file = 'inf'

        #player._set_property("vf",'eq=brightness=-0.5')
        #player.vf_add("fade=type=in:start_time=2:duration=1")
        #player.playlist_pos=1
        
        # DEBUG:root:function test.playback_restart added
        # DEBUG:root:playing 0
        # DEBUG:root:playlist-pos property playlist-pos 0
        # DEBUG:root:function test.playlist_pos not found - skipping
        # DEBUG:root:function test.start_file not found - skipping
        # DEBUG:root:running function test.playback_restart args 'sp.jpeg', 0

        # DEBUG:root:function test.end_file not found - skipping
        # DEBUG:root:function test.start_file not found - skipping
        # DEBUG:root:playlist-pos property playlist-pos 1
        # DEBUG:root:function test.playlist_pos not found - skipping
        # DEBUG:root:running function test.playback_restart args 'drop.avi', 1
        
        # DEBUG:root:function test.end_file not found - skipping
        # DEBUG:root:function test.start_file not found - skipping
        # DEBUG:root:playlist-pos property playlist-pos 2
        # DEBUG:root:function test.playlist_pos not found - skipping
        # DEBUG:root:running function test.playback_restart args 'bird.avi', 2
        
        #SINGLE FILE IN PLAYLIST
        # 05:32:36.625: playlist-pos property playlist-pos 0
        # 05:32:36.625: function test.playlist_pos not found - skipping
        # 05:32:37.245: function test.file_loaded not found - skipping
        # 05:32:37.477: function test.playback_restart not found - skipping
        # 05:32:43.543: running function test.end_file args "{'event_id': 7, 'error': 0, 'reply_userdata': 0, 'event': {'reason': 0, 'error': 0}}", 'drop.avi', 0
        # 05:32:43.543: function test.start_file not found - skipping
        # 05:32:43.576: function test.file_loaded not found - skipping
        # 05:32:43.618: function test.playback_restart not found - skipping
        
        #SINGLE FILE WITH RECALL
        # 05:37:49.354: playlist-pos property playlist-pos 0
        # 05:37:49.355: function test.playlist_pos not found - skipping
        # 05:37:49.356: function test.start_file not found - skipping
        # 05:37:49.727: function test.file_loaded not found - skipping
        # 05:37:49.947: function test.playback_restart not found - skipping
        # 05:37:56.013: running function test.end_file args "{'event_id': 7, 'error': 0, 'reply_userdata': 0, 'event': {'reason': 0, 'error': 0}}", 'drop.avi', 0
        # 05:37:56.014: function test.start_file not found - skipping
        # 05:37:56.015: running function test.end_file args "{'event_id': 7, 'error': 0, 'reply_userdata': 0, 'event': {'reason': 2, 'error': 0}}", 'bird.avi', 0
        # 05:37:56.015: function test.start_file not found - skipping
        # 05:37:56.016: running function test.end_file args "{'event_id': 7, 'error': 0, 'reply_userdata': 0, 'event': {'reason': 2, 'error': 0}}", 'bird.avi', 0
        # 05:37:56.016: function test.start_file not found - skipping
                    
Beispiel #22
0
 def __init__(self, name: str):
     self.names = []
     self.splayer = MpvSimple(name + '.simplePlayer')
     self.caller = FunctionCaller(name)
     self.splayer.caller.on_end_file(self.next)
Beispiel #23
0
 logging.debug('logging')
 
 #mpv = MpvSimple('test')
 #pl = LoopPlayer('loop')
 #pl.names.append('drop.avi')
 #pl.names.append('bird.avi')
 #pl.names.append('sp.jpeg')
 #pl.start()
 logging.debug(sys.argv[1])
 vid = LoopPlayer('player')
 vid.names.append('drop.avi')
 vid.names.append('bird.avi')
 vid.start()
 
 if sys.argv[1] == 'host':
     main = FunctionCaller('host')
     fact = TCPReceiver(8007)
     fact.parts[main.name]=main
     fact.begin()
     def sendSync(fn):
         fact.sendAll('cl.sync('+fn+')')
     vid.caller.on_end_file(sendSync)
 if sys.argv[1] == 'cl':
     cl = FunctionCaller('cl')
     def restartPlayer(fn):
         vid.next(fn)
         return 'cl:ok'
     cl.on_sync(vid.next)
     fact = TCPClient('127.0.0.1',8007)
     fact.parts[cl.name]=cl
     fact.begin()
Beispiel #24
0
def test_runNonExistantFunction(caplog):
    caller = FunctionCaller('testCallerName')
    assert caller.runFunction('returnerFunctionName') == None
Beispiel #25
0
def test_removeNonExistantFunction():
    caller = FunctionCaller('testCallerName')
    with pytest.raises(KeyError):
        caller.removeFunction('function')
Beispiel #26
0
def test_addFunction():
    caller = FunctionCaller('testCallerName')
    caller.addFunction('returnerFunctionName', returner)
    assert 'returnerFunctionName' in caller.getFunctionDict()
Beispiel #27
0
        logging.debug(sstory.leftChannel)
        if not sstory.leftChannel:
            fadeBackgroundAndPlay()
            sstory.setSoundChannels(left=False, right=True)
        else:
            sstory.setSoundChannels(left=True, right=True)

    def rightEarDown():
        if not sstory.leftChannel:
            goBackToBackground()
        else:
            sstory.setSoundChannels(left=True, right=False)

    sstory.play('background.jpeg')

    fakeArduino = FunctionCaller("fa")
    fakeArduino.on_0(leftEarUp)
    fakeArduino.on_1(leftEarDown)
    fakeArduino.on_2(rightEarUp)
    fakeArduino.on_3(rightEarDown)

    def on_press(key):
        logging.debug(key)
        if key.char == 'k':
            sstory.setFadeTime(1, finish=1)
        if key.char == 'l':
            sstory.setFadeTime(1)
        if key.char in ['0', '1', '2', '3']:
            fakeArduino.runFunction(str(key.char))

    listener = keyboard.Listener(on_press=on_press)
Beispiel #28
0
def test_addNonStrKeyFunction():
    caller = FunctionCaller('testCallerName')
    with pytest.raises(TypeError):
        caller.addFunction(1, 'str')