Beispiel #1
0
    def processResponse(self, sensorInputs, recurInputs):
        ret = []
        for data in sensorInputs:
            #first time with behavior:
            data = dict(data)
            if not 'StartTime' in data:
                data['StartTime'] = timeOps.time()
                data['Period'] = self['Period']
                data['MaxHeight'] = self['MaxHeight']  #Consider just using +=
                if not 'Bottom' in data:
                    data['Bottom'] = data['Location'][1]
                if 'Width' in self:  #TODO: improve
                    data['Width'] = self['Width']
                    data['Left'] = data['Location'][0] - data['Width'] / 2.
                    data['Right'] = data['Location'][0] + data['Width'] / 2.
            currentTime = timeOps.time()
            deltaTime = currentTime - data['StartTime']
            #if data['Oscillate'] == True:
            data['Height'] = data['MaxHeight'] * math.sin(
                deltaTime / data['Period'] * (math.pi * 2))
            #else:
            #    data['Height'] = data['MaxHeight']
            #if (currentTime-data['StartTime']) > data['Period']:
            #    del data['StartTime']

            data['Location'] = "{x}>"+str(data['Left']) + ", " +\
            "{x}<"+str(data['Right'])+", {y}<" + str(data['Bottom']) + ",\
            {y}>"                 +str(data['Bottom']-data['Height'])

            ret.append(data)
        return (ret, [])
 def loadNextBehavior(self):
     print self['Id'], "loadNextBehavior"
     if self['Random']:
         behaviortemp = random.choice(self['Sequence'])
         while behavior == behaviortemp:
             behaviortemp = random.choice(self['Sequence'])
         behavior = behaviortemp
     else:
         behavior = self.iterator.next()
     print self['Id'], "   ", behavior
     self.behavior = behavior['Id']
     self.onChange = behavior['OnChange']
     if 'FadeInId' in behavior:
         self.transin = behavior['FadeInId']
         self.endTime = clock.time() + behavior['FadeInTime'] * 1000
         self.timeout = self.getTimeout(behavior['Timeout'])
     else:
         self.transin = None
         self.endTime = clock.time() + \
                         self.getTimeout(behavior['Timeout']) * 1000
     if 'FadeOutId' in behavior:
         self.transout = behavior['FadeOutId']
         self.fadetime = behavior['FadeOutTime']
     else:
         self.transout = None
         self.fadetime = 0
Beispiel #3
0
    def processResponse(self, sensorInputs, recurInputs):
        ret = []
        for data in sensorInputs:
            #first time with behavior:
            data = dict(data)
            if not 'StartTime' in data:
                data['StartTime'] = timeOps.time()
                data['Period'] = self['Period']
                data['MaxHeight'] = self['MaxHeight']  #Consider just using +=
                if not 'Bottom' in data:
                    data['Bottom'] = data['Location'][1]
                if 'Width' in self: #TODO: improve
                    data['Width'] = self['Width']
                    data['Left'] = data['Location'][0]-data['Width']/2.
                    data['Right'] = data['Location'][0]+data['Width']/2.
            currentTime = timeOps.time()
            deltaTime = currentTime-data['StartTime']
            #if data['Oscillate'] == True:
            data['Height'] = data['MaxHeight']*math.sin(deltaTime/data['Period']*(math.pi*2))
            #else:
            #    data['Height'] = data['MaxHeight']
            #if (currentTime-data['StartTime']) > data['Period']:
            #    del data['StartTime']

            data['Location'] = "{x}>"+str(data['Left']) + ", " +\
            "{x}<"+str(data['Right'])+", {y}<" + str(data['Bottom']) + ",\
            {y}>"+str(data['Bottom']-data['Height'])

            ret.append(data)
        return (ret, [])
 def loadNextBehavior (self):
     print self['Id'], "loadNextBehavior"
     if self['Random']:
         behaviortemp = random.choice(self['Sequence'])
         while behavior == behaviortemp:
             behaviortemp = random.choice(self['Sequence'])
         behavior = behaviortemp
     else:
         behavior = self.iterator.next()
     print self['Id'], "   ", behavior
     self.behavior = behavior['Id']
     self.onChange = behavior['OnChange']
     if 'FadeInId' in behavior:
         self.transin = behavior['FadeInId']
         self.endTime = clock.time() + behavior['FadeInTime'] * 1000
         self.timeout = self.getTimeout(behavior['Timeout'])
     else:
         self.transin = None
         self.endTime = clock.time() + \
                         self.getTimeout(behavior['Timeout']) * 1000
     if 'FadeOutId' in behavior:
         self.transout = behavior['FadeOutId']
         self.fadetime = behavior['FadeOutTime']
     else:
         self.transout = None
         self.fadetime = 0
Beispiel #5
0
 def mainLoop(self):
     lastLoopTime = clock.time()
     refreshInterval = 30 
     runCount = 0
     dieCount = -1 
     print 'Starting Main Loop'
     while not self.dieNow: #dieNow is set if one of its constituents sends a die request.
         runCount += 1
         dieCount -= 1
         if dieCount == 0:
             self.dieNow = True
         runCount = runCount % 30
         loopStart = clock.time()
         responses = self.evaluateBehaviors() 
         self.timer.start()
         [self.screen.respond(response) for response in responses if
                 response != []]
         self.screen.timeStep(loopStart)
         [r.render(self.screen, loopStart) for r in self.renderers]
         loopElapsed = clock.time()-loopStart
         if runCount == 0:
             print 'FPS: ', 1000 / loopElapsed
         sleepTime = max(0,refreshInterval-loopElapsed)
         #print 1000/loopElapsed
         if loopElapsed > 100:
             print 'SLOOOWWWW!', 1000 / loopElapsed
         main_log.debug('Loop complete in {0} ms.  Sleeping for {1} ms.'.format(loopElapsed, sleepTime))
         self.timer.stop()
         if sleepTime > 0:
             time.sleep(sleepTime/1000)
Beispiel #6
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)
Beispiel #7
0
 def processResponse(self, sensor, recurs):
     ret = []
     for loc in sensor:
         oploc = dict(loc)
         self.insertVelIfMissing(oploc)
         deltaT = timeOps.time() - oploc["EvalTime"]
         deltaLoc = (deltaT * oploc["XVel"], deltaT * oploc["YVel"])
         # print 'diff:',deltaLoc
         oploc["Location"] = Geo.addLocations(deltaLoc, oploc["Location"])
         oploc["EvalTime"] = timeOps.time()
         ret.append(oploc)
     return (ret, [])
Beispiel #8
0
 def processResponse(self, sensor, recurs):
     ret = []
     for loc in sensor:
         oploc = dict(loc)
         self.insertVelIfMissing(oploc)
         deltaT = timeOps.time() - oploc['EvalTime']
         deltaLoc = (deltaT * oploc['XVel'], deltaT * oploc['YVel'])
         #print 'diff:',deltaLoc
         oploc['Location'] = Geo.addLocations(deltaLoc, oploc['Location'])
         oploc['EvalTime'] = timeOps.time()
         ret.append(oploc)
     return (ret, [])
Beispiel #9
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)
    def processResponse (self, inputs, state):

        self.initialize()
        
        if self.interrupt.sensorResponseQueue != []:
            self.stopMain()
            self.last_interrupt = clock.time()

        if self.last_interrupt + self['Timeout'] * 1000 >= clock.time():
            outputs = self.interrupt.timeStep()
        else:
            self.startMain()
            outputs = self.main.timeStep()

        return (outputs, [True])
Beispiel #11
0
    def processResponse(self, inputs, state):

        self.initialize()

        if self.interrupt.sensorResponseQueue != []:
            self.stopMain()
            self.last_interrupt = clock.time()

        if self.last_interrupt + self['Timeout'] * 1000 >= clock.time():
            outputs = self.interrupt.timeStep()
        else:
            self.startMain()
            outputs = self.main.timeStep()

        return (outputs, [True])
Beispiel #12
0
 def state(self, currentTime=None): 
     """Combines all PixelEvents currently active and computes the current color of
     the pixel."""
     if currentTime == None:
         currentTime = timeops.time()
     if currentTime-self.lastRenderTime < 5:
         return self.lastRender
     if self.events == []:
         self.lastRenderTime = currentTime
         return (0,0,0)
     deadEvents = []
     resultingColor = (0,0,0)
     colors = []
     for eventObj in self.events: #TODO: right color weighting code
         if len(self.events) > 50:
             main_log.error('High pixel event count!  Investigate!')
         eventTime, zindex, scale, pixelEvent = eventObj
         eventResult = pixelEvent.state(currentTime-eventTime)
         if eventResult != None:
             scaledEvent = color.multiplyColor(eventResult,scale)
             if (scaledEvent[0] + scaledEvent[1] + scaledEvent[2]) < 5:
                 pass
                 #deadEvents.append(eventObj)
             else:
                 colors.append(scaledEvent)
         else:
             deadEvents.append(eventObj)
     
     resultingColor = color.combineColors(colors)
     [self.events.remove(event) for event in deadEvents]
     resultingColor = [int(round(c)) for c in resultingColor]
     self.lastRender = tuple(resultingColor)
     self.lastRenderTime = currentTime
     return tuple(resultingColor)
Beispiel #13
0
 def mainLoop(self):
     lastLoopTime = clock.time()
     refreshInterval = 30
     while not self.dieNow:  # dieNow is set if one of its constituents sends a die request.
         loopStart = clock.time()
         responses = self.evaluateBehaviors()
         self.timer.start()
         [self.screen.respond(response) for response in responses if response != []]
         self.screen.timeStep(loopStart)
         [r.render(self.screen, loopStart) for r in self.renderers]
         loopElapsed = clock.time() - loopStart
         sleepTime = max(0, refreshInterval - loopElapsed)
         main_log.debug("Loop complete in " + str(loopElapsed) + "ms.  Sleeping for " + str(sleepTime))
         self.timer.stop()
         if sleepTime > 0:
             time.sleep(sleepTime / 1000)
Beispiel #14
0
 def pruneCache(self, cache):
     currentTime = timeOps.time()
     rem = []
     for l, t in cache:
         if currentTime - t > 5000:
             rem.append((l, t))
     for r in rem:
         cache.remove(r)
Beispiel #15
0
 def pruneCache(self, cache):
     currentTime = timeOps.time()
     rem = []
     for l,t in cache:
         if currentTime-t > 5000:
             rem.append((l,t))
     for r in rem:
         cache.remove(r)
def composePixelStripData(pixelStrip,currentTime=timeops.time()):
    packet = bytearray()
    for light in pixelStrip:
        color = light.state(currentTime)
        for channel in color: #skip the last value, its an
            #alpha value
            packet.append(struct.pack('B', channel))
    return packet
Beispiel #17
0
 def sensingLoop(self): #TODO: move to params
     currentTime = clock.time()
     if currentTime - self['LastEvent'] > self['Interval']:
         if 'MinX' in self.argDict and 'MinY' in self.argDict:
             self.respond({Strings.LOCATION: Geo.randomLoc( (self['MaxX'],self['MaxY']), (self['MinX'],self['MinY']) )})
         else:
             self.respond({Strings.LOCATION: Geo.randomLoc((self['MaxX'],self['MaxY']))})
         self['LastEvent'] = currentTime
Beispiel #18
0
 def timeStep(self, currentTime=None):
     """Increments time -- This processes all queued responses, adding that to a queue that will
     be processed on the next time step."""
     if currentTime == None:
         currentTime = timeops.time()
     tempQueue = list(self.responseQueue)
     self.responseQueue = []
     for response in tempQueue:
         self.processResponse(response, currentTime)
Beispiel #19
0
 def init(self):
     #defaults:
     if not self['RefactoryTime']:
         self.RefactoryTime = 500
     if not self['DetectionRange']:
         self.DetectionRange = 15
     if not self['DetectionProbability']:
         self.DetectionProbability = 1
     self.lastDetection = timeOps.time() - self.RefactoryTime
     self.objLocHook = self['DataHook']
Beispiel #20
0
 def behaviorInit(self):
     self.keyIndex = 0
     self.currentBehaviorId = self['TimeMap'].keys()[self.keyIndex]
     self.behaviorStart = clock.time()
     self.inputMap = {}
     for inp in self['InputMap'].keys():
         if isinstance(self['InputMap'][inp], str):
             self.inputMap[inp] = [self['InputMap'][inp]]
         else:
             self.inputMap[inp] = self['InputMap'][inp]
Beispiel #21
0
 def behaviorInit(self):
     self.keyIndex = 0
     self.currentBehaviorId = self['TimeMap'].keys()[self.keyIndex]
     self.behaviorStart = clock.time()
     self.inputMap = {}
     for inp in self['InputMap'].keys():
         if isinstance(self['InputMap'][inp],str):
             self.inputMap[inp] = [self['InputMap'][inp]]
         else:
             self.inputMap[inp] = self['InputMap'][inp]
Beispiel #22
0
 def sensingLoop(self):  # TODO: move to params
     currentTime = clock.time()
     if currentTime - self["LastEvent"] > self["Interval"]:
         if "MinX" in self.argDict and "MinY" in self.argDict:
             self.respond(
                 {Strings.LOCATION: Geo.randomLoc((self["MaxX"], self["MaxY"]), (self["MinX"], self["MinY"]))}
             )
         else:
             self.respond({Strings.LOCATION: Geo.randomLoc((self["MaxX"], self["MaxY"]))})
         self["LastEvent"] = currentTime
 def render(self, lightSystem, currentTime=timeops.time()):
     # try:
     for pixelStrip in lightSystem.pixelStrips:
         stripId = pixelStrip.argDict["Id"]
         (ip, port) = self.stripLocations[stripId]
         if not ip in self.sockets:  # do we have a socket to this
             # strip? if not, spin off a new one
             self.sockets[ip] = network.getConnectedSocket(ip, sock_port)
         packet = composer.composePixelStripPacket(pixelStrip, port, currentTime)
         self.sockets[ip].send(packet, 0x00)
Beispiel #24
0
 def insertVelIfMissing(self, data):
     if not 'XVel' in data:
         data['XVel'] = self['XVel']
     if not 'YVel' in data:
         data['YVel'] = self['YVel']
     if data['XVel'] == None:
         data['XVel'] = 0
     if data['YVel'] == None:
         data['YVel'] = 0
     if not 'EvalTime' in data:
         data['EvalTime'] = timeOps.time()
Beispiel #25
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
Beispiel #26
0
 def render(self, lightSystem, currentTime=timeops.time()): 
     for pixelStrip in lightSystem.strips:
         stripId = str(pixelStrip.argDict['Id'])
         (ip, port) = self.stripLocations[stripId] 
         if not ip in self.sockets: #do we have a socket to this
             self.sockets[ip] = network.getConnectedSocket(ip,sock_port)
         packet = composer.composePixelStripPacket(pixelStrip.values, port)
         try:
             self.sockets[ip].send(packet, 0x00)
         except:
             pass
Beispiel #27
0
 def render(self, lightSystem, currentTime=timeops.time()):
     for pixelStrip in lightSystem.strips:
         stripId = str(pixelStrip.argDict['Id'])
         (ip, port) = self.stripLocations[stripId]
         if not ip in self.sockets:  #do we have a socket to this
             self.sockets[ip] = network.getConnectedSocket(ip, sock_port)
         packet = composer.composePixelStripPacket(pixelStrip.values, port)
         try:
             self.sockets[ip].send(packet, 0x00)
         except:
             pass
Beispiel #28
0
 def insertVelIfMissing(self, data):
     if not "XVel" in data:
         data["XVel"] = self["XVel"]
     if not "YVel" in data:
         data["YVel"] = self["YVel"]
     if data["XVel"] == None:
         data["XVel"] = 0
     if data["YVel"] == None:
         data["YVel"] = 0
     if not "EvalTime" in data:
         data["EvalTime"] = timeOps.time()
Beispiel #29
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
Beispiel #30
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])
Beispiel #31
0
 def initRenderer(self):
     pygame.init()
     if not 'Size' in self:
         size = (1000, 200)
     else:
         size = self['Size']
     self.screen = pygame.display.set_mode(size)
     self.background = pygame.Surface(self.screen.get_size())
     self.background = self.background.convert()
     self.background.fill(Color(0, 0, 0))
     self.stopwatch = timeops.Stopwatch()
     self.stopwatch.start()
Beispiel #32
0
    def sensingLoop(self):
        currentTime = timeOps.time()
        dataLocs = self.objLocHook.getLocs()

        for loc in dataLocs:
            if abs(loc - self.Location) < self.DetectionRange:
                if random.random(
                ) < self.DetectionProbability:  #TODO: refactory time
                    self.parentScope.processResponse({
                        'SensorId': self['Id'],
                        'Responding': currentTime
                    })
Beispiel #33
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 render(self, lightSystem, currentTime=timeops.time()):
        self.background.fill(Color(0,0,0))
        #print 'drawing color:',light.color
        for light in lightSystem:
            pygame.draw.circle(self.background, light.state(currentTime), light.location, \
                light.radius)

        self.screen.blit(self.background, (0,0))
        pygame.display.flip()
        self.stopwatch.stop()
        pygame.display.set_caption(str(int(1000/self.stopwatch.elapsed())))
        self.stopwatch.start()
Beispiel #35
0
    def processInput(self, inp):
        self.responses = inp
        self.pruneCache(self.cached)
        newCache = []
        for r in self.responses:
            bestMatch,t = self.findClosest(self.cached, r['Location'][0]) 
            r['Direction'] =  r['Location'][0]-bestMatch
            r['Velocity'] = r['Direction']/(timeOps.time()-t)
            newCache.append((r['Location'][0], r['Responding'])) 

        self.cached += newCache
        respCopy = list(self.responses)
        return respCopy 
Beispiel #36
0
    def processInput(self, inp):
        self.responses = inp
        self.pruneCache(self.cached)
        newCache = []
        for r in self.responses:
            bestMatch, t = self.findClosest(self.cached, r['Location'][0])
            r['Direction'] = r['Location'][0] - bestMatch
            r['Velocity'] = r['Direction'] / (timeOps.time() - t)
            newCache.append((r['Location'][0], r['Responding']))

        self.cached += newCache
        respCopy = list(self.responses)
        return respCopy
    def sensingLoop(self):
        self.pruneCache(self.cached)
        if not self.boundToInput:
            self.boundToInput = self.makeListener()
        newCache = []
        for r in self.responses:
            bestMatch,t = self.findClosest(self.cached, r['Location'][0]) 
            r['Direction'] =  r['Location'][0]-bestMatch
            r['Velocity'] = r['Direction']/(timeOps.time()-t)
            newCache.append((r['Location'][0], r['Responding'])) 

        self.cached += newCache
        self.respond(self.responses)
        self.responses = []
Beispiel #38
0
    def sensingLoop(self):
        self.pruneCache(self.cached)
        if not self.boundToInput:
            self.boundToInput = self.makeListener()
        newCache = []
        for r in self.responses:
            bestMatch, t = self.findClosest(self.cached, r['Location'][0])
            r['Direction'] = r['Location'][0] - bestMatch
            r['Velocity'] = r['Direction'] / (timeOps.time() - t)
            newCache.append((r['Location'][0], r['Responding']))

        self.cached += newCache
        self.respond(self.responses)
        self.responses = []
Beispiel #39
0
    def render(self, lightSystem, currentTime=timeops.time()):
        self.background.fill(Color(0, 0, 0))
        if 'Scale' in self:
            scale = self['Scale']
        else:
            scale = 1

        for loc, value in lightSystem:
            if not (all(value == (0, 0, 0))):
                pygame.draw.circle(self.background, value, loc * scale, scale)
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()
        self.stopwatch.stop()
        pygame.display.set_caption(str(int(1000 / self.stopwatch.elapsed())))
        self.stopwatch.start()
    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)
Beispiel #41
0
    def render(self, lightSystem, currentTime=timeops.time()):
        self.background.fill(Color(0,0,0))
        if 'Scale' in self:
            scale = self['Scale']
        else:
            scale = 1

        for loc, value in lightSystem:
	    if not(all(value == (0,0,0))):
            	pygame.draw.circle(self.background, value, loc*scale, scale)
        self.screen.blit(self.background, (0,0))
        pygame.display.flip()
        self.stopwatch.stop()
        pygame.display.set_caption(str(int(1000/self.stopwatch.elapsed())))
        self.stopwatch.start()
Beispiel #42
0
 def findClosest(self, cache, location):
     #TODO: numpyify
     #print len(cache)
     bestMatch = None
     bestDist = sys.maxint
     if cache == []:
         return location, timeOps.time()
     tcache = list(cache)
     tcache.reverse()
     for x, t in tcache:
         if bestMatch == None or abs(x - location) < bestDist:
             bestDist = abs(x - location)
             bestMatch = x
             bestTime = t
     cache.remove((bestMatch, bestTime))
     return bestMatch, t
Beispiel #43
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
 def findClosest(self, cache, location):
     #TODO: numpyify
     #print len(cache)
     bestMatch = None
     bestDist = sys.maxint
     if cache == []:
         return location,timeOps.time() 
     tcache = list(cache)
     tcache.reverse()
     for x,t in tcache:
         if bestMatch == None or abs(x-location)<bestDist:
             bestDist = abs(x-location)
             bestMatch = x
             bestTime = t 
     cache.remove((bestMatch,bestTime))
     return bestMatch,t
    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)
Beispiel #46
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()
Beispiel #47
0
    def render(self, lightSystem, currentTime=timeops.time()):
        self.background.fill(Color(0,0,0))
        #print 'drawing color:',light.color
        if 'Scale' in self:
            scale = self['Scale']
        else:
            scale = 1
        for light in lightSystem:
            scaledLoc = [l*scale for l in light.location] 
            pygame.draw.circle(self.background, light.state(currentTime), scaledLoc, \
                5)

        self.screen.blit(self.background, (0,0))
        pygame.display.flip()
        self.stopwatch.stop()
        pygame.display.set_caption(str(int(1000/self.stopwatch.elapsed())))
        self.stopwatch.start()
Beispiel #48
0
 def parseBinarySensorPacket(self, p, firstBitIndex):
     #print 'starting to parse'
     if len(p) != 5:
         print 'bad length'
     packet = []
     for i, hexByte in enumerate(p):
         bits = self.grabBits(hexByte)
         packet += bits
     output = []
     #print packet
     packet = map(int, packet)
     #print packet
     #print sum(packet)
     for j, b in enumerate(packet):
         if b == 1:
             #sensorId = firstBitIndex + i*8 + j
             output.append({'SensorId': j, 'Responding': timeOps.time()})
             print 'responding', j
         #send output as necessary
     #print 'done parsing'
     return output
Beispiel #49
0
 def parseSensorPacket(self, p):
     #sensorid:XXXX#sensorid:XXXX#sensorid:XXXX
     #Packet:
     #10 Bytes
     import pdb
     pdb.set_trace()
     packets = p.split('#')
     output = []
     for s in packets:
         if s != '':
             sensorId, packetData = s.split(':')
             for i, val in enumerate(packetData):
                 if val == '1':
                     #print 'responding:',i
                     output.append({
                         'SensorId':
                         int(sensorId) * len(packetData) + i,
                         'Responding':
                         timeOps.time()
                     })
                     #print 'output'
     return output
Beispiel #50
0
    def parseBinarySensorPacket(self,p, firstBitIndex):
        #print 'starting to parse'
        if len(p) != 5:
            print 'bad length'
        packet = []
        for i,hexByte in enumerate(p):
            bits = self.grabBits(hexByte)
            packet += bits
        output = []
        #print packet
        packet = map(int, packet)
        #print packet
        #print sum(packet)
	#import pdb; pdb.set_trace()
        for j,b in enumerate(packet):
            if b == 1:
                #sensorId = firstBitIndex + i*8 + j
                output.append({'SensorId':j, 'Responding':timeOps.time()})
                #print 'responding', j 
            #send output as necessary
        #print 'done parsing'
        return output
Beispiel #51
0
    def render(self, px=None, currentTime=timeops.time()):
        if px != None:
            self.pixels = px    

        # David C's mod to prevent queue overflow 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)
            lastevent = event

        if CONFIG.scale:
            scale = CONFIG.scale
        else:
            scale = 1
        for i in range(len(self.locs)):
            loc = array(self.locs[i])
            value = self.pixels[i]
            #if not(all(value == (0,0,0))):
            pygame.draw.circle(self.background, value, loc*scale, scale)
        self.screen.blit(self.background, (0,0))
        pygame.display.flip()
        self.stopwatch.stop()
        pygame.display.set_caption("fps: "+str(int(1000/self.stopwatch.elapsed())))
        self.stopwatch.start()
Beispiel #52
0
 def transitionIn (self): # switch out of fade in
     print self['Id'], "transitionIn ", self.transin
     self.transin = None
     self.transinState = []
     self.endTime = clock.time() + self.timeout * 1000
Beispiel #53
0
 def clockTick(self):
     return clock.time() - clock.t
Beispiel #54
0
 def inputInit(self):
     self['LastEvent'] = clock.time()
Beispiel #55
0
 def inputInit(self):
     self["LastEvent"] = clock.time()
Beispiel #56
0
 def transitionIn(self):  # switch out of fade in
     print self['Id'], "transitionIn ", self.transin
     self.transin = None
     self.transinState = []
     self.endTime = clock.time() + self.timeout * 1000