Example #1
0
 def transitionOut (self): #switch out of fade out
     print self['Id'], "transitionOut", self.transition
     if self.transOnChange == 'Pause':
         compReg.getComponent(self.transition).pauseInputs()
     self.transition = None
     self.transitionout = None
     self.transoutState = []
Example #2
0
    def processResponse(self, sensorInputs, recursiveInputs):        
	if self.mapper == None:
            try:
                self.mapper = compReg.getComponent('windgaussmap')
            except KeyError:
                pass
        if self.xymove == None:
            try:
                self.xymove = compReg.getComponent('xymove')
            except KeyError:
                pass

        outs = []
        for sensory in sensorInputs:
            #print sensory
            # input[0] is windspeed, [1] is dir
            if 'WindSpeed' in sensory and 'WindDir' in sensory:
                windSpeed = sensory['WindSpeed']
                windDir = sensory['WindDir']
                print 'speed', windSpeed
                print 'dir', windDir
                #self.mapper.Width = float(windSpeed)*2+15
                sensory['XVel'] = float(windSpeed)+10*random.random()
                sensory['YVel'] = float(windSpeed)/3.*random.uniform(-1,1)
                #self.xymove.XStep = float(windSpeed)+10*random.random();
                #self.xymove.YStep = float(windSpeed)/3.*random.uniform(-1,1); 
                #print 'Width: ' , self.mapper.Width
                #print 'xymove: (' , self.xymove.XStep, ', ', self.xymove.YStep, ')'
            else:
                outs.append(sensory)
        return (outs, [])
Example #3
0
    def processResponse(self, sensorInputs, recursiveInputs):
	if self.mapper == None:
            try:
                self.mapper = compReg.getComponent('windgaussmap')
            except KeyError:
                pass
        if self.xFor == None:
            try:
                self.xFor = compReg.getComponent('xfor')
            except KeyError:
                pass

        for sensory in sensorInputs:
            print sensory
            # input[0] is windspeed, [1] is dir
	    if 0 in sensory and 1 in sensory:
		    windSpeed = sensory[0]
		    windDir = sensory[1]
		    #print self.mapper.argDict
		    self.mapper.argDict['Width'] = self.mapper.argDict['Width']+float(windSpeed)*2+20
		    self.xFor.argDict['ParamOp'] = self.xFor.argDict['ParamOp']+float(windSpeed)*3+10*random.random(); 
		    #print 'Width: ' + str(self.mapper.argDict['Width'])
		    #print 'xFor: ' + str(self.xFor.argDict['ParamOp'])

	    elif 'Key' in sensory:
		    if sensory['Key'] == 273:
			    self.mapper.argDict['Width'] = self.mapper.argDict['Width']+10;
			    self.xFor.argDict['ParamOp'] = self.xFor.argDict['ParamOp']+5;
		   
		    elif sensory['Key'] == 274:
			    self.mapper.argDict['Width'] = self.mapper.argDict['Width']-10;
			    self.xFor.argDict['ParamOp'] = self.xFor.argDict['ParamOp']-5;

        return (sensorInputs, recursiveInputs)
Example #4
0
 def transitionOut(self):  #switch out of fade out
     print self['Id'], "transitionOut", self.transition
     if self.transOnChange == 'Pause':
         compReg.getComponent(self.transition).pauseInputs()
     self.transition = None
     self.transitionout = None
     self.transoutState = []
Example #5
0
    def processResponse(self, data, recurs):
        for packet in data:
            message = ""
            #try:
            if 1:
                if not 'OperationType' in packet:
                    packet['OperationType'] = 'Update'

                if packet['OperationType'] == 'Create':
                    raise Exception('Create is not supported')
                    compFactory.create(packet['Class'], packet['Args'])
                elif packet['OperationType'] == 'Read':
                    self.doRead(packet)
                elif packet['OperationType'] == 'Update':
                    cid = packet['ComponentId']
                    paramName = packet['ParamName']
                    newParamValue = attemptEval(str(packet['Value']))
                    currentObject = compReg.getComponent(cid)
                    self.doUpdate(cid, paramName, newParamValue, currentObject,
                                  packet['Callback'])
                    #TODO: consider adding lambda evaluation capabilities

                elif packet['OperationType'] == 'Destroy':
                    raise Exception('Destroy not supported')
                    compReg.removeComponent(packet['ComponentId'])
            try:
                print 1
            except Exception, e:
                print str(e)
                import pdb
                pdb.set_trace()
Example #6
0
    def processResponse(self, sensorInputs, recursiveInputs):
        if self.mapper == None:
            try:
                self.mapper = compReg.getComponent('windgaussmap')
            except KeyError:
                pass
        if self.xymove == None:
            try:
                self.xymove = compReg.getComponent('xymove')
            except KeyError:
                pass

        outs = []
        for sensory in sensorInputs:
            #print sensory
            # input[0] is windspeed, [1] is dir
            if 'WindSpeed' in sensory and 'WindDir' in sensory:
                windSpeed = sensory['WindSpeed']
                windDir = sensory['WindDir']
                print 'speed', windSpeed
                print 'dir', windDir
                #self.mapper.Width = float(windSpeed)*2+15
                sensory['XVel'] = float(windSpeed) + 10 * random.random()
                sensory['YVel'] = float(windSpeed) / 3. * random.uniform(-1, 1)
                #self.xymove.XStep = float(windSpeed)+10*random.random();
                #self.xymove.YStep = float(windSpeed)/3.*random.uniform(-1,1);
                #print 'Width: ' , self.mapper.Width
                #print 'xymove: (' , self.xymove.XStep, ', ', self.xymove.YStep, ')'
            else:
                outs.append(sensory)
        return (outs, [])
 def processResponse(self, data, recurs):
     for packet in data:
         message = ""
         #try:
         if 1:
             if not 'OperationType' in packet:
                 packet['OperationType'] = 'Update'
             
             if packet['OperationType'] == 'Create':
                 raise Exception('Create is not supported')
                 compFactory.create(packet['Class'], packet['Args'])
             elif packet['OperationType'] == 'Read':                    
                 self.doRead(packet)
             elif packet['OperationType'] == 'Update':
                 cid = packet['ComponentId']
                 paramName = packet['ParamName']
                 newParamValue = attemptEval(str(packet['Value']))
                 currentObject=compReg.getComponent(cid)
                 self.doUpdate(cid,paramName,newParamValue,currentObject,packet['Callback'])
                 #TODO: consider adding lambda evaluation capabilities
                 
             elif packet['OperationType'] == 'Destroy':
                 raise Exception('Destroy not supported')
                 compReg.removeComponent(packet['ComponentId'])
         try:
             print 1
         except Exception, e:
             print str(e)
             import pdb; pdb.set_trace()
Example #8
0
    def inputInit(self):

        if 'Repeat' not in self.argDict:
            self.Repeat = 1

        self.t = 0

        compReg.getLock().acquire()
        xmin, ymin, xmax, ymax = compReg.getComponent('Screen').size
        compReg.getLock().release()

        xlen = xmax - xmin
        ylen = ymax - ymin

        if self['useClock']:
            self.t = self.clock()
            self.getTime = self.clockTick
        else:
            self.t = 0
            self.getTime = self.callTick

        self.x_eqn = eval('lambda t:' + str(xmin) + '+' + str(xlen) + '*(' +
                          str(self['xEquation']) + ')')
        self.y_eqn = eval('lambda t:' + str(ymin) + '+' + str(ylen) + '*(' +
                          str(self['yEquation']) + ')')
 def configureInstallation(self, installationConfig):
     defaults = configGetter.generateArgDict(installationConfig.find('Defaults'))
     for defaultSelection in defaults:
         componentToMap = compReg.getComponent(defaults[defaultSelection])
         compReg.registerComponent(compReg.getComponent(defaults[defaultSelection]),\
             'Default'+defaultSelection)
         main_log.debug('Default Set: ' + defaultSelection + 'set to ' +\
             defaults[defaultSelection])
Example #10
0
 def configureInstallation(self, installationConfig):
     defaults = configGetter.generateArgDict(installationConfig.find('Defaults'))
     for defaultSelection in defaults:
         componentToMap = compReg.getComponent(defaults[defaultSelection])
         compReg.registerComponent(compReg.getComponent(defaults[defaultSelection]),\
             'Default'+defaultSelection)
         main_log.debug('Default Set: ' + defaultSelection + 'set to ' +\
             defaults[defaultSelection])
Example #11
0
 def setUp(self):
     b = ColorChangerBehavior({'Id': 'color', 'ColorList': [(255, 0, 0)]})
     i = ContinuousCenterInput({
         'Id': 'center',
         'parentScope': self,
         'RefreshInterval': 500
     })
     compReg.registerComponent(b)
     compReg.registerComponent(i)
Example #12
0
 def startBehavior(self):
     print self['Id'], "startBehavior", self.behavior
     if self.transin:
         self.transinState =  \
             compReg.getComponent(self.transin).behaviorInit()
     if self.onChange == 'Pause':
         compReg.getComponent(self.behavior).resumeInputs()
     elif self.onChange == 'Restart':
         compReg.getComponent(self.behavior).init()
    def inputInit(self):
        xvals = {}
        yvals = {}
        compReg.getLock().acquire()
        xvals['left'], yvals['bottom'], xvals['right'], yvals['top'] = compReg.getComponent('Screen').getSize()
        compReg.getLock().release()
        (xvals['center'], yvals['center']) = ((xvals['left']+xvals['right']) / 2, (yvals['top']+yvals['bottom']) / 2)

        self.location = (xvals[self['xloc']], yvals[self['yloc']])
Example #14
0
 def startBehavior (self):
     print self['Id'], "startBehavior", self.behavior
     if self.transin:
         self.transinState =  \
             compReg.getComponent(self.transin).behaviorInit()
     if self.onChange == 'Pause':
         compReg.getComponent(self.behavior).resumeInputs()
     elif self.onChange == 'Restart':
         compReg.getComponent(self.behavior).init()
    def inputInit(self):
        compReg.getLock().acquire()
        xmin, ymin, xmax, ymax = compReg.getComponent('Screen').size
        compReg.getLock().release()

        xlen = xmax-xmin
        ylen = ymax-ymin

        self.xloc = xmin + xlen * self['xPos']
        self.yloc = ymin + ylen * self['yPos']
Example #16
0
    def inputInit(self):
        compReg.getLock().acquire()
        xmin, ymin, xmax, ymax = compReg.getComponent('Screen').size
        compReg.getLock().release()

        xlen = xmax - xmin
        ylen = ymax - ymin

        self.xloc = xmin + xlen * self['xPos']
        self.yloc = ymin + ylen * self['yPos']
Example #17
0
    def inputInit(self):
        xvals = {}
        yvals = {}
        compReg.getLock().acquire()
        xvals['left'], yvals['bottom'], xvals['right'], yvals[
            'top'] = compReg.getComponent('Screen').size
        compReg.getLock().release()
        (xvals['center'],
         yvals['center']) = ((xvals['left'] + xvals['right']) / 2,
                             (yvals['top'] + yvals['bottom']) / 2)

        self.location = (xvals[self['xloc']], yvals[self['yloc']])
 def test_modify_components(self):
     modifier = SystemConfigMutator({'Id':'mutate'})
     modifier.immediateProcessInput({'OperationType':'Update',\
                                     'ComponentId':'color','ParamName':'ColorList',
                                     'Value':[(0,0,255)]})
     
     assert compReg.getComponent('color')['ColorList'] == [(0,0,255)]
     
     modifier.immediatedProcessInput({'OperationType':'Update',
                                      'ComponentId':'center',
                                      'ParamName':'RefreshInterva',
                                      'Value':800})
     
     assert compReg.getComponent('center')['RefreshInterval'] == 800
Example #19
0
 def test_modify_components(self):
     modifier = SystemConfigMutator({'Id':'mutate'})
     params = {'Value':(0,0,255)}
     modifier.immediateProcessInput([{'OperationType':'Assign',\
                                     'ComponentId':'color','ParamName':'ColorList',\
                                     'Value':[(0,0,255)]}],[])
     
     assert compReg.getComponent('color')['ColorList'] == [(0,0,255)]
     
     modifier.immediateProcessInput([{'OperationType':'Assign',
                                      'ComponentId':'center',
                                      'ParamName':'RefreshInterval',
                                      'Value':800}],[])
     assert compReg.getComponent('center')['RefreshInterval'] == 800
Example #20
0
 def inputInit(self):
     self.hostname = self.argDict['Hostname']
     self.port = int(self.argDict['Port'])
     compReg.registerComponent(self, 'Webserver')
     
     urls = ('/(.*)', 'WebHandler')
     env = globals()
     env['sys'].argv = []
     app = web.application(urls, env)
     
     self.server_thread = threading.Thread(target=app.run)
     self.server_thread.daemon = True
     self.server_thread.start()
     
     webbrowser.open('http://'+self.hostname+':'+str(self.port))
Example #21
0
 def behaviorInit(self):
     self.xMin, self.yMin, self.xMax, self.yMax = \
                                     compReg.getComponent('Screen').size
     self.gradients = self['Gradient']
     if isinstance(self.gradients,dict):
         self.gradients = [self.gradients]
     self.scrwid = self.xMax - self.xMin
Example #22
0
    def processResponse(self, responseInfo, currentTime=None): #we need to make a new dict for
        #each to prevent interference
        if currentTime == None:
            currentTime = timeops.time()
        if type(responseInfo) != type(dict()):
            pass
        if 'Mapper' in responseInfo:
            mapper = compReg.getComponent(responseInfo['Mapper']) 
        else:
            mapper = compReg.getComponent(Strings.DEFAULT_MAPPER)
        pixelWeightList = mapper.mapEvent(responseInfo['Location'], self)
        main_log.debug('Screen processing response.  ' + str(len(pixelWeightList)) + ' events\
generated')
        PixelEvent.addPixelEventIfMissing(responseInfo)
        for (pixel, weight) in pixelWeightList: 
            pixel.processInput(responseInfo['PixelEvent'], 0,weight, currentTime) #TODO: z-index
Example #23
0
 def behaviorInit(self):
     action = self['Action']
     modifyParamArgs = {
         'ParamType': 'Sensor',
         'ParamName': self['ParamName'],
         'ParamOp': self['Action']
     }
     self.locBounds = self['LocationRestriction']
     self.paramModifier = ModifyParam(modifyParamArgs)
     xmin, ymin, xmax, ymax = compReg.getComponent('Screen').getSize()
     replacementDict = {
         '{x}': 'l[0]',
         '{y}': 'l[1]',
         '{xmin}': str(xmin),
         '{xmax}': str(xmax),
         '{ymin}': str(ymin),
         '{ymax}': str(ymax)
     }
     if isinstance(self.locBounds, str):
         for key in replacementDict:
             self.locBounds = self.locBounds.replace(
                 key, replacementDict[key])
         self.locEval = eval('lambda l:' + self.locBounds)
     elif isinstance(self.locBounds, tuple):
         if len(self.locBounds) != 4:
             raise Exception('Must be in form (xmin,yin,xmax,ymax)')
         else:
             self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\
                     self.LocBounds)
Example #24
0
 def behaviorInit(self):
     self.xMin, self.yMin, self.xMax, self.yMax = \
                                     compReg.getComponent('Screen').size
     self.gradients = self['Gradient']
     if isinstance(self.gradients, dict):
         self.gradients = [self.gradients]
     self.scrwid = self.xMax - self.xMin
 def processResponse(self,inputDict, responseDict):
     inputId = inputDict['Id']
     boundBehaviorIds = self.inputBehaviorRegistry[inputId]
     try:
         [compReg.getComponent(b).addInput(responseDict) for b in boundBehaviorIds]
     except:
         pass
Example #26
0
 def makeListener(self):
     try:
         compReg.getLock().acquire()
         compReg.getComponent(self['SensorNetworkId']).addListener(self)
         compReg.getLock().release()
         return True
     except Exception as ex:
         compReg.getLock().release()
         return False
Example #27
0
    def __init__(self, configFileName):
        main_log.info("System Initialization began based on: " + str(configFileName))
        self.timer = clock.Stopwatch()
        self.timer.start()
        self.inputs = {} #dict of inputs and their bound behaviors, keyed by InputId
        self.behaviors = {}
        self.lock = thread.allocate_lock()
        self.behaviorOutputs = {} #key: [list of output destinations]
        self.behaviorInputs = {}
        self.componentDict = {}
        self.inputBehaviorRegistry = {} #inputid -> behaviors listening to that
        self.dieNow = False
        #input
        self.screen = Screen()
        compReg.initRegistry()
        compReg.registerComponent(self.screen, 'Screen') #TODO: move to constants file
       
        bqs.initBQS()   #initialize the behavior query system
        #read configs from xml
        config = configGetter.loadConfigFile(configFileName)
        
        rendererConfig = config.find('RendererConfiguration')
        self.initializeRenderers(rendererConfig)
        
        pixelConfig = config.find('PixelConfiguration')
        self.initializeScreen(pixelConfig)
        
        inputConfig = config.find('InputConfiguration')
        self.initializeInputs(inputConfig)
        
        behaviorConfig = config.find('BehaviorConfiguration')
        self.initializeBehaviors(behaviorConfig)
        
        mapperConfig = config.find('PixelMapperConfiguration')
        self.initializeMapper(mapperConfig)

        #inits
        main_log.info('All components initialized')
        #
        self.registerAllComponents()
        
        installationConfig = config.find('InstallationConfiguration')
        self.configureInstallation(installationConfig)
        #Done initializing.  Lets start this thing!
        self.timer.stop()
        #main_log.info('Initialization done.  Time: ', self.timer.elapsed(), 'ms')
        self.mainLoop()
Example #28
0
    def __init__(self, configFileName):
        main_log.info("System Initialization began based on: " + str(configFileName))
        self.timer = clock.Stopwatch()
        self.timer.start()
        self.inputs = {}  # dict of inputs and their bound behaviors, keyed by InputId
        self.behaviors = {}
        self.lock = thread.allocate_lock()
        self.behaviorOutputs = {}  # key: [list of output destinations]
        self.behaviorInputs = {}
        self.componentDict = {}
        self.inputBehaviorRegistry = {}  # inputid -> behaviors listening to that
        self.dieNow = False
        # input
        self.screen = Screen()
        compReg.initRegistry()
        compReg.registerComponent(self.screen, "Screen")  # TODO: move to constants file

        bqs.initBQS()  # initialize the behavior query system
        # read configs from xml
        config = configGetter.loadConfigFile(configFileName)

        rendererConfig = config.find("RendererConfiguration")
        self.initializeRenderers(rendererConfig)

        pixelConfig = config.find("PixelConfiguration")
        self.initializeScreen(pixelConfig)

        inputConfig = config.find("InputConfiguration")
        self.initializeInputs(inputConfig)

        behaviorConfig = config.find("BehaviorConfiguration")
        self.initializeBehaviors(behaviorConfig)

        mapperConfig = config.find("PixelMapperConfiguration")
        self.initializeMapper(mapperConfig)

        # inits
        main_log.info("All components initialized")
        #
        self.registerAllComponents()

        installationConfig = config.find("InstallationConfiguration")
        self.configureInstallation(installationConfig)
        # Done initializing.  Lets start this thing!
        self.timer.stop()
        # main_log.info('Initialization done.  Time: ', self.timer.elapsed(), 'ms')
        self.mainLoop()
 def makeListener(self):
     try:
         compReg.getLock().acquire()
         compReg.getComponent(self['LocSensorId']).addListener(self)
         compReg.getLock().release()
         return True
     except Exception as ex:
         compReg.getLock().release()
         return False
Example #30
0
 def behaviorInit(self):
     self.keymapping = {'q':[2,19], 'w':[22,36], 'e':[37,49], 'r':[52,69], 't':[76,91], 'y':[94,105],
     'u':[106,117], 'i':[123,154], 'o':[158,161], 'p':[164,167], '[':[172,184]}
     screenWidth = compReg.getComponent('Screen').getSize()[2] #(minx, miny,maxx, maxy)
     maxKey = max([max(self.keymapping[v]) for v in self.keymapping])
     mult = screenWidth / float(maxKey)
     for k in self.keymapping:
         self.keymapping[k] = [int(val*mult) for val in self.keymapping[k]]
Example #31
0
    def behaviorInit(self):
        self.xy = array((0, 0))
        self.v_xy = array((0, 0))
        self.v_decay = vel_decay

        self.start_hsv = [0, 1, 1]
        self.dest_hsv = [0, 1, 1]
        self.ssize = compReg.getComponent('Screen').size[-2:]  #896 x 310
Example #32
0
    def behaviorInit(self):
        self.xy = array((0,0))
        self.v_xy = array((0,0))
        self.v_decay = vel_decay

        self.start_hsv = [0,1,1] 
        self.dest_hsv = [0,1,1] 
        self.ssize = compReg.getComponent('Screen').getSize()[-2:] #896 x 310
Example #33
0
 def behaviorInit(self):
     self.keymapping = {'q':[2,19], 'w':[22,36], 'e':[37,49], 'r':[52,69], 't':[76,91], 'y':[94,105],
     'u':[106,117], 'i':[123,154], 'o':[158,161], 'p':[164,167], '[':[172,184]}
     screenWidth = compReg.getComponent('Screen').size[2] #(minx, miny,maxx, maxy)
     maxKey = max([max(self.keymapping[v]) for v in self.keymapping])
     mult = screenWidth / float(maxKey)
     for k in self.keymapping:
         self.keymapping[k] = [int(val*mult) for val in self.keymapping[k]]
Example #34
0
 def processResponse(self, sensors, recurs):
     if self.behaviorStart + self['TimeMap'][self.currentBehaviorId]*1000 <= clock.time():
         self.keyIndex += 1
         self.keyIndex = self.keyIndex % len(self['TimeMap'])
         self.currentBehaviorId = self['TimeMap'].keys()[self.keyIndex]
         self.behaviorStart = clock.time()
         main_log.info('Switching behaviors')
     sensors = [s for s in sensors if s['InputId'] == self['InputMap'][self.currentBehaviorId]]
     return compReg.getComponent(self.currentBehaviorId).immediateProcessInput(sensors, recurs)
Example #35
0
    def processResponse(self, sensorInputs, recursiveInputs):
        self.mapper = compReg.getComponent(self.argDict['MapperId'])
        #print 'CutoffDist: ' + str(self.mapper.argDict['CutoffDist']) + ', Width: ' + str(self.mapper.argDict['Width'])
        #print 'CutoffDist: ' + str(self.mapper.CutoffDist) + ', Width: ' + str(self.mapper.Width)

        self.mapper.CutoffDist = self.argDict['CutoffDistChange']
        self.mapper.Width = self.argDict['WidthChange']

        return (sensorInputs, recursiveInputs)
    def processResponse(self, sensorInputs, recursiveInputs):
        if self.mapper == None:
            try:
                self.mapper = compReg.getComponent('mobilegaussmap')
            except KeyError:
                pass

        #print sensorInputs
        for sInput in sensorInputs:
            if 'Shake' in sInput and sInput['Shake'] == 1:
                #print 'increase!'
                self.mapper.argDict['Width'] += 30
                #self.mapper.argDict['CutoffDist'] += 20                
                sInput['Shake'] = 0
                print 'Width:' + str(compReg.getComponent('mobilegaussmap').argDict['Width'])
                #print 'CutoffDist: '+ str(compReg.getComponent('mobilegaussmap').argDict['CutoffDist'])
                
        return (sensorInputs, recursiveInputs)
Example #37
0
    def processResponse(self, sensorInputs, recursiveInputs):
        self.mapper = compReg.getComponent(self.argDict["MapperId"])
        # print 'CutoffDist: ' + str(self.mapper.argDict['CutoffDist']) + ', Width: ' + str(self.mapper.argDict['Width'])
        # print 'CutoffDist: ' + str(self.mapper.CutoffDist) + ', Width: ' + str(self.mapper.Width)

        self.mapper.CutoffDist = self.argDict["CutoffDistChange"]
        self.mapper.Width = self.argDict["WidthChange"]

        return (sensorInputs, recursiveInputs)
Example #38
0
    def setUp(self):
        compReg.initRegistry()

        # add a test registry
        self.behavior1 = EchoBehavior({'Id': 'behavior1'})
        self.behavior2 = DebugBehavior({'Id': 'behavior2'})
        compReg.registerComponent(self.behavior1)
        compReg.registerComponent(self.behavior2)

        self.switchBehavior = SwitchBehavior({'Id': 'switch', 'PrefixToBehavior': '{"@": "behavior1", "#": "behavior2"}', 'DefaultBehavior': 'behavior1'})
        compReg.registerComponent(self.switchBehavior)
Example #39
0
    def processResponse(self, sensors, state):

        curTime = clock.time()

        if state == []:  # if processResponse has never been run
            for behavior in self['Sequence']:
                if behavior['OnChange'] == 'Pause':
                    compReg.getComponent(behavior['Id']).pauseInputs()
            self.startBehavior()

        if self.behavior:
            outputs = compReg.getComponent(self.behavior).timeStep()
            loadNext = False
            if len(outputs) > 0 and self.behaviorComplete == outputs[-1]:
                outputs[-1:] = None
                loadNext = True

            if self.transin:
                transin = compReg.getComponent(
                    self.transin).immediateProcessInput(
                        outputs, self.transinState)
                outputs = transin[0]
                self.transinState = transin[1]

        if self.transition and self.transitionout:
            transoutput = compReg.getComponent(self.transition).timeStep()
            transout = compReg.getComponent(
                self.transitionout).immediateProcessInput(
                    transoutput, self.transoutState)
            compReg.getComponent(self.transition).setLastOutput(transout[0])
            outputs.extend(transout[0])
            self.transoutState = transout[1]

        if self.endTime <= curTime or loadNext == True:

            try:
                if self.transin and not loadNext:
                    self.transitionIn()
                else:
                    self.stopBehavior()
                    self.loadNextBehavior()
                    self.startBehavior()
            except StopIteration:
                if self['Repeat']:
                    self.behaviorInit()
                    self.startBehavior()
                else:
                    self.behavior = None

        if self.transition and self.transTime <= curTime:
            self.transitionOut()

        return (outputs, [True])
Example #40
0
    def processResponse (self, sensors, state):

        curTime = clock.time()

        if state == []: # if processResponse has never been run
            for behavior in self['Sequence']:
                if behavior['OnChange'] == 'Pause':
                    compReg.getComponent(behavior['Id']).pauseInputs()
            self.startBehavior()

        if self.behavior:
            outputs = compReg.getComponent(self.behavior).timeStep()
            loadNext = False
            if len(outputs) > 0 and self.behaviorComplete == outputs[-1]:
                outputs[-1:] = None
                loadNext = True

            if self.transin:
                transin = compReg.getComponent(
                    self.transin).immediateProcessInput(
                                                outputs, self.transinState)
                outputs = transin[0]
                self.transinState = transin[1]

        if self.transition and self.transitionout:
            transoutput = compReg.getComponent(self.transition).timeStep()
            transout = compReg.getComponent(
                self.transitionout).immediateProcessInput(
                                            transoutput, self.transoutState)
            compReg.getComponent(self.transition).setLastOutput(transout[0])
            outputs.extend(transout[0])
            self.transoutState = transout[1]

        if self.endTime <= curTime or loadNext == True:

            try:
                if self.transin and not loadNext:
                    self.transitionIn()
                else:
                    self.stopBehavior()
                    self.loadNextBehavior()
                    self.startBehavior()
            except StopIteration:
                if self['Repeat']:
                    self.behaviorInit()
                    self.startBehavior()
                else:
                    self.behavior = None

        if self.transition and self.transTime <= curTime:
            self.transitionOut()

        return (outputs, [True])
    def processResponse(self, sensorInputs, recursiveInputs):
        if self.mapper == None:
            try:
                self.mapper = compReg.getComponent('mobilegaussmap')
            except KeyError:
                pass

        #print sensorInputs
        for sInput in sensorInputs:
            if 'Shake' in sInput and sInput['Shake'] == 1:
                #print 'increase!'
                self.mapper.argDict['Width'] += 30
                #self.mapper.argDict['CutoffDist'] += 20
                sInput['Shake'] = 0
                print 'Width:' + str(
                    compReg.getComponent('mobilegaussmap').argDict['Width'])
                #print 'CutoffDist: '+ str(compReg.getComponent('mobilegaussmap').argDict['CutoffDist'])

        return (sensorInputs, recursiveInputs)
Example #42
0
 def stopBehavior(self):
     print self['Id'], "stop Behavior", self.behavior
     if self.transout:
         self.transoutState = \
             compReg.getComponent(self.transout).behaviorInit()
     self.transition = self.behavior
     self.transitionout = self.transout
     self.transTime = clock.time() + self.fadetime * 1000
     self.transout = None
     self.transOnChange = self.onChange
     self.onChange = None
Example #43
0
 def stopBehavior (self):
     print self['Id'], "stop Behavior", self.behavior
     if self.transout:
         self.transoutState = \
             compReg.getComponent(self.transout).behaviorInit()
     self.transition = self.behavior
     self.transitionout = self.transout
     self.transTime = clock.time() + self.fadetime * 1000
     self.transout = None
     self.transOnChange = self.onChange
     self.onChange = None
Example #44
0
 def processResponse(self, sensors, recurs):
     ret = []
     if sensors and 'Image' in sensors[0]:
         dataPacket = sensors[0]
         screen = compReg.getComponent('Screen')
         im = dataPacket['Image'] 
         minX,minY,maxX,maxY = compReg.getComponent('Screen').size
         sWidth = maxX-minX
         sHeight = maxY-minY
         (imageWidth,imageHeight)=im.size
         for light in screen:
             lightLoc = light.location
             imageLoc = ((lightLoc[0]-minX)*(imageWidth-1) / sWidth, (lightLoc[1]-minY)*\
                         (imageHeight-1)/sHeight)
             try:
                 pixelColor = im.getpixel(imageLoc)
             except:
                 pdb.set_trace()
                 print lightLoc
             ret.append(dict(Location=lightLoc, Color=pixelColor))
     return (ret, [])
Example #45
0
    def processResponse(self, sensorInputs, recursiveInputs):
        response = sensorInputs
        for behaviorId in self['ChainedBehaviors']:
            behavior = compReg.getComponent(behaviorId)
            if behaviorId in self.feedback:
                recurrence = self.feedback[behaviorId]
            else:
                recurrence = []
            (response,recurrence) = behavior.immediateProcessInput(response,\
                    recurrence)

            if behaviorId in self.hooks: #process recursive hook if there is one
                hookBehavior = compReg.getComponent(self.hooks[behaviorId])
                #we feed its recurrence in as input to the behavior.  
                (recurrence, hookRecurrence) = \
                hookBehavior.immediateProcessInput(recurrence, \
                        [])
                if hookRecurrence != []:
                    main_log.warn('Hook recurrences are not currently supported.') 
            self.feedback[behaviorId] = recurrence 
        return (response, [])
Example #46
0
 def behaviorInit (self):
     self.xMin, self.yMin, self.xMax, self.yMax = \
                                     compReg.getComponent('Screen').size
     self.scrwid = self.xMax - self.xMin
     if 'Center' in self.argDict:
         self.center = self['Center'] * self.scrwid
     else:
         self.center = .5 * self.scrwid
     if 'tEquation' in self.argDict:
         self.tEq = eval("lambda t: " + self['tEquation'])
     else:
         self.tEq = lambda t: t / 90.0
     return [0]
Example #47
0
    def processResponse(self, sensorInputs, recursiveInputs):
        response = sensorInputs
        for behaviorId in self['ChainedBehaviors']:
            behavior = compReg.getComponent(behaviorId)
            if behaviorId in self.feedback:
                recurrence = self.feedback[behaviorId]
            else:
                recurrence = []
            (response,recurrence) = behavior.immediateProcessInput(response,\
                    recurrence)

            if behaviorId in self.hooks:  #process recursive hook if there is one
                hookBehavior = compReg.getComponent(self.hooks[behaviorId])
                #we feed its recurrence in as input to the behavior.
                (recurrence, hookRecurrence) = \
                hookBehavior.immediateProcessInput(recurrence, \
                        [])
                if hookRecurrence != []:
                    main_log.warn(
                        'Hook recurrences are not currently supported.')
            self.feedback[behaviorId] = recurrence
        return (response, [])
Example #48
0
 def behaviorInit(self):
     self.xMin, self.yMin, self.xMax, self.yMax = \
                                     compReg.getComponent('Screen').size
     self.scrwid = self.xMax - self.xMin
     if 'Center' in self.argDict:
         self.center = self['Center'] * self.scrwid
     else:
         self.center = .5 * self.scrwid
     if 'tEquation' in self.argDict:
         self.tEq = eval("lambda t: " + self['tEquation'])
     else:
         self.tEq = lambda t: t / 90.0
     return [0]
Example #49
0
    def setUp(self):
        compReg.initRegistry()

        # add a test registry
        self.behavior1 = EchoBehavior({'Id': 'behavior1'})
        self.behavior2 = DebugBehavior({'Id': 'behavior2'})
        compReg.registerComponent(self.behavior1)
        compReg.registerComponent(self.behavior2)

        self.switchBehavior = SwitchBehavior({
            'Id': 'switch',
            'PrefixToBehavior': '{"@": "behavior1", "#": "behavior2"}',
            'DefaultBehavior': 'behavior1'
        })
        compReg.registerComponent(self.switchBehavior)
    def inputInit(self):

        if 'Repeat' not in self.argDict:
            self.Repeat = 1

        self.t = 0

        compReg.getLock().acquire()
        xmin, ymin, xmax, ymax = compReg.getComponent('Screen').size
        compReg.getLock().release()

        xlen = xmax-xmin
        ylen = ymax-ymin

        if self['useClock']:
            self.t=self.clock()
            self.getTime = self.clockTick
        else:
            self.t=0
            self.getTime = self.callTick

        self.x_eqn = eval('lambda t:' + str(xmin) + '+' + str(xlen) + '*(' + str(self['xEquation']) + ')')
        self.y_eqn = eval('lambda t:' + str(ymin) + '+' + str(ylen) + '*(' + str(self['yEquation']) + ')')
Example #51
0
 def setUp(self):
     s = Screen()
     compReg.registerComponent(s, 'Screen')
     
     b = ColorChangerBehavior({'Id': 'color','ColorList':[(255,0,0)]})
     i = ContinuousCenterInput({'Id': 'center','parentScope':self,'RefreshInterval':500})
     
     compReg.registerComponent(b)
     compReg.registerComponent(i)
Example #52
0
 def recalc(self):
     self.locBounds = self['LocationRestriction']
     xmin,ymin,xmax,ymax = compReg.getComponent('Screen').size
     replacementDict = {'{x}':'l[0]','{y}':'l[1]', '{xmin}':str(xmin), '{xmax}':str(xmax),
                        '{ymin}':str(ymin),'{ymax}':str(ymax)}
     if isinstance(self.locBounds, str) or isinstance(self.locBounds, unicode):
         for key in replacementDict:
             self.locBounds = self.locBounds.replace(key, replacementDict[key])
         self.locEval = eval('lambda l:'+self.locBounds)
     elif isinstance(self.locBounds, tuple):
         if len(self.locBounds) != 4:
             raise Exception('Must be in form (xmin,yin,xmax,ymax)')
         else:
             self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\
                     self.LocBounds)
Example #53
0
 def processResponse(self, sensors, recurs):
     #print self['Id'], ": " , self.currentBehaviorId, ' ', str((clock.time() - self.behaviorStart)/1000)
     if self.behaviorStart + self['TimeMap'][
             self.currentBehaviorId] * 1000 <= clock.time():
         self.keyIndex += 1
         self.keyIndex = self.keyIndex % len(self['TimeMap'])
         self.currentBehaviorId = self['TimeMap'].keys()[self.keyIndex]
         self.behaviorStart = clock.time()
         main_log.info('Switching behaviors')
     sensors = [
         s for s in sensors
         if s['InputId'] in self.inputMap[self.currentBehaviorId]
     ]
     return compReg.getComponent(
         self.currentBehaviorId).immediateProcessInput(sensors, recurs)
Example #54
0
    def render(self, lightSystem, currentTime=timeops.time()):
        json_frame = [0]*len(lightSystem)
        i = 0
        for (loc, c) in lightSystem:
            if all(c < 0.05):
                continue
            cs = 'rgb({0},{1},{2})'.format(c)
            json_frame[i] = (map(int, loc), cs)
            i += 1

        json_frame = json_frame[0:i]
        size = compReg.getComponent('Screen').size
        
        json_data = json.dumps(dict(status='ok', size=map(int, size), frame=json_frame))
        self.client_push(json_data)
Example #55
0
    def render(self, lightSystem, currentTime=timeops.time()):
        json_frame = [0] * len(lightSystem)
        i = 0
        for (loc, c) in lightSystem:
            if all(c < 0.05):
                continue
            cs = 'rgb({0},{1},{2})'.format(c)
            json_frame[i] = (map(int, loc), cs)
            i += 1

        json_frame = json_frame[0:i]
        size = compReg.getComponent('Screen').size

        json_data = json.dumps(
            dict(status='ok', size=map(int, size), frame=json_frame))
        self.client_push(json_data)
Example #56
0
    def behaviorInit(self):
        self.xMin, self.yMin, self.xMax, self.yMax = \
                                        compReg.getComponent('Screen').size
        self.scrwid = self.xMax - self.xMin

        if 'Center' in self.argDict:
            if not isinstance(self['Center'], str):
                self['Center'] = str(self['Center'])
            self.center = eval("lambda t:" + self['Center'] + " * " + \
                                str(self.scrwid))
        else:
            self.center = lambda t: .5 * self.scrwid
        if 'Scale' in self.argDict:
            if not isinstance(self['Scale'], str):
                self['Scale'] = str(self['Scale'])
            self.scale = eval("lambda t: " + self['Scale'])
        else:
            self.scale = lambda t: 100 * math.sin((2 * math.pi * t) / 10000)
        return [0]
Example #57
0
 def processResponse(self, sensorInputs, recursiveInputs):
     newResponses = sensorInputs 
     ret = []
     ret += newResponses
     for recurInput in recursiveInputs:
         outDict = dict(recurInput)
         if not 'Dir' in outDict:
             outDict['Dir'] = 1 #to the right
         if not 'StepSize' in outDict:
             outDict['StepSize'] = self['StepSize']
         outDict['Location']= Geo.addLocations(outDict['Location'],
         (outDict['StepSize']*outDict['Dir'],0))
         
         if not Geo.pointWithinBoundingBox(outDict['Location'], \
             compReg.getComponent('Screen').size):
                 outDict['Dir'] *= -1
         ret.append(outDict)
     ret += newResponses
     return (ret, ret)
Example #58
0
 def processResponse(self,inputDict, responseDict):
     inputId = inputDict['Id']
     try:
         boundBehaviorIds = self.inputBehaviorRegistry[inputId]
     except KeyError:
         print "missing input"
         return
         
     if not isinstance(responseDict, list):
         responseDict = [responseDict]
     try:
         for r in responseDict:
             for b in boundBehaviorIds:
                 c = compReg.getComponent(b)
                 # Only accept inputs to rendering behaviors, since they can pile up
                 # MAY CAUSE DISCONTINUITY if behavior continuity is dependent on input continuity
                 if c['RenderToScreen'] or c['AcceptInputs']:
                     c.addInput(r)
     except:
         pass