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)
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 = []
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, 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 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 = []
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])
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
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 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 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
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
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
def processResponse(self,inputDict, responseDict): inputId = inputDict['Id'] boundBehaviorIds = self.inputBehaviorRegistry[inputId] try: [compReg.getComponent(b).addInput(responseDict) for b in boundBehaviorIds] except: pass
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 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()
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 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)
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()
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, 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
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
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
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]]
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]]
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)
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)
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']])
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): 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 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']
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)
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 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']
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
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
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, [])
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, [])
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 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]
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, [])
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]
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)
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)
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)
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)
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: 0.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]
def behaviorInit(self): modifyParamArgs = {'ParamType': 'Sensor', 'ParamName':self['ParamName'],'ParamOp':self['Action']} self.locBounds = self['LocationRestriction'] self.paramModifier = ModifyParam(modifyParamArgs) 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): 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)
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)
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').getSize()): outDict['Dir'] *= -1 ret.append(outDict) ret += newResponses return (ret, ret)
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]
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
def initRenderer(self): self.hostname = self.argDict['Hostname'] self.port = int(self.argDict['Port']) if 'SourcePort' in self.argDict: self.orig_port = int(self.argDict['SourcePort']) else: self.orig_port = compReg.getComponent('Webserver').getPort() self.clients = [] self.clients_lock = threading.Lock() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', self.port)) self.sock.listen(1) self.connection_thread = threading.Thread(target=self.handle_connections) self.connection_thread.daemon = True self.connection_thread.start()
def initRenderer(self): self.hostname = self.argDict['Hostname'] self.port = int(self.argDict['Port']) if 'SourcePort' in self.argDict: self.orig_port = int(self.argDict['SourcePort']) else: self.orig_port = compReg.getComponent('Webserver').getPort() self.clients = [] self.clients_lock = threading.Lock() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', self.port)) self.sock.listen(1) self.connection_thread = threading.Thread( target=self.handle_connections) self.connection_thread.daemon = True self.connection_thread.start()
def processResponse(self, inputs, state): out = [] newstate = {} mappedinp = {} allinp = [] for behaviorId in self['BehaviorList']: mappedinp[behaviorId] = [] if behaviorId in state: behaviorState = state[behaviorId] else: behaviorState = [] for inp in inputs: inpId = inp['InputId'] if inpId in self.inputMap: for beh in self.inputMap[inpId]: mappedinp[beh].append(inp) else: allinp.append(inp) for behaviorId in self['BehaviorList']: behavior = compReg.getComponent(behaviorId) #print behaviorId, " ", str(inp), ",", str(behaviorState) output = behavior.immediateProcessInput( mappedinp[behaviorId] + list(allinp), behaviorState) (behaviorOutput, behaviorState) = output #print " -->", str(behaviorState), ",", str(behaviorOutput) newstate[behaviorId] = behaviorState out.extend(behaviorOutput) return (out, newstate)
def processResponse(self, sensorInputs, recursiveInputs): ret = [] if sensorInputs: data = sensorInputs[-1]#for data in sensorInputs: if data['Path'] == '/1/fader1': try: self.h = data['Value'][0] except: pdb.set_trace() elif data['Path'] == '/1/fader2': self.s = data['Value'][0] elif data['Path'] == '/1/fader3': self.v = data['Value'][0] elif data['Path'] == '/1/xy': val=data['Value'] ssize = compReg.getComponent('Screen').size[-2:] #896 x 310 self.xy = (val[1]*ssize[0], (1.0-val[0])*ssize[1]) else: main_log.error('Sensor Inputs: ' + str(sensorInputs)) ret.append({'Color':[i*255 for i in colorsys.hsv_to_rgb(self.h,self.s,self.v)],'Location':self.xy}) return (ret, [])
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)