Esempio n. 1
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)
Esempio n. 2
0
    def initializeComponent(self, config):
        components = []
        if config != None:
            for configItem in config.getchildren():
                try:
                    [module, className] = configItem.find("Class").text.split(".")
                except:
                    main_log.error("Module must have Class element")
                    continue
                try:
                    exec("from " + module + "." + className + " import *")
                    main_log.debug(module + "." + className + "imported")
                except Exception as inst:
                    main_log.error(
                        "Error importing "
                        + module
                        + "."
                        + className
                        + ".  Component not\
                    initialized."
                    )
                    main_log.error(str(inst))
                    continue
                args = configGetter.pullArgsFromItem(configItem)
                args["parentScope"] = self
                try:
                    new_component = eval(className + "(args)")
                    new_component.addDieListener(self)
                    components.append(new_component)
                    main_log.info(className + "initialized with args " + str(args))
                except Exception as inst:
                    main_log.error("Failure while initializing " + className + " with " + str(args))
                    main_log.error(str(inst))

        return components
 def initializeComponent(self, config):
     components = []
     if config != None:
         for configItem in config.getchildren():
             try:
                 [module,className] = configItem.find('Class').text.split('.')
             except:
                 main_log.error('Module must have Class element')
                 continue
             try:
                 exec('from ' + module+'.'+className + ' import *')
                 main_log.debug(module +'.' +className + 'imported')
             except Exception as inst:
                 main_log.error('Error importing ' + module+'.'+className+ '.  Component not\
                 initialized.')
                 main_log.error(str(inst)) 
                 continue 
             args = configGetter.pullArgsFromItem(configItem)
             args['parentScope'] = self 
             try:
                 new_component = eval(className+'(args)')
                 new_component.addDieListener(self)
                 components.append(new_component) 
                 main_log.info(className + 'initialized with args ' + str(args))
             except Exception as inst:
                 main_log.error('Failure while initializing ' + className + ' with ' + str(args))
                 main_log.error(str(inst)) 
             
     return components
Esempio n. 4
0
 def initializeComponent(self, config):
     components = []
     if config != None:
         for configItem in config.getchildren():
             try:
                 [module,className] = configItem.find('Class').text.split('.')
             except:
                 main_log.error('Module must have Class element')
                 continue
             try:
                 exec('from ' + module+'.'+className + ' import *')
                 main_log.debug(module +'.' +className + 'imported')
             except Exception as inst:
                 main_log.error('Error importing ' + module+'.'+className+ '.  Component not\
                 initialized.')
                 main_log.error(str(inst)) 
                 continue 
             args = configGetter.pullArgsFromItem(configItem)
             args['parentScope'] = self 
             try:
                 new_component = eval(className+'(args)')
                 new_component.addDieListener(self)
                 components.append(new_component) 
                 main_log.info(className + 'initialized with args ' + str(args))
             except Exception as inst:
                 main_log.error('Failure while initializing ' + className + ' with ' + str(args))
                 main_log.error(str(inst)) 
             
     return components
Esempio n. 5
0
    def processResponse(self, sensorInputs, recursiveInputs):
        debug_string = "DebugBehavior<" + self['Id'] + ">\n"

        if sensorInputs == [] and 'Quiet' in self.argDict and self['Quiet']:
            return ([], [])

        if sensorInputs == []:
            debug_string += "\tNO INPUTS"
        else:
            for sensorInput in sensorInputs:
                debug_string += '\t' + str(sensorInput) + '\n'

        if 'Output' in self.argDict:
            if self['Output'] == 'print':
                print debug_string
            elif self['Output'] == 'error':
                main_log.error(debug_string)
            elif self['Output'] == 'debug':
                main_log.debug(debug_string)
            elif self['Output'] == 'info':
                main_log.info(debug_string)
        else:
            if sensorInputs != []:
                main_log.error('Sensor Inputs: ' + str(sensorInputs))

        if 'PassThrough' in self.argDict:
            if self['PassThrough']:
                return (sensorInputs, [])
            else:
                return ([], [])

        return ([], [])
Esempio n. 6
0
 def processResponse(self, sensorInputs, recursiveInputs):
     ret = []
     if sensorInputs:
         data = sensorInputs[-1]#for data in sensorInputs:
         if data['Path'] == '/sixaxis/xy':
             #try:
                 x = data['Value'][0]
                 y = data['Value'][1]
                 if y < 0:
                     self.start_hsv[1] = 1.0+y #s
                 else:
                     self.start_hsv[2] = 1.0-y
                 self.start_hsv[0] = (x+1)/2.   
         elif data['Path'] == '/sixaxis/lrud':
             val=data['Value']
             vy = val[3]-val[2]
             vx = val[1]-val[0] 
             #pdb.set_trace()
             #self.v_xy = (val[1]*ssize[0], (1.0-val[0])*ssize[1])
             self.v_xy = array((vx, vy)) * speedfactor
         else:
             main_log.error('Sensor Inputs: ' + str(sensorInputs))
     self.xy = self.xy + self.v_xy
     constrainLocation(self.xy,self.ssize)
     self.v_xy *= self.v_decay
     ret.append({'Color':[i*255. for i in colorsys.hsv_to_rgb(*self.start_hsv)],'Location':(int(self.xy[0]), int(self.xy[1]))})
 
     return (ret, [])
Esempio n. 7
0
    def processResponse(self, sensorInputs, recursiveInputs):
        ret = []
        if sensorInputs:
            data = sensorInputs[-1]  #for data in sensorInputs:
            if data['Path'] == '/sixaxis/xy':
                #try:
                x = data['Value'][0]
                y = data['Value'][1]
                if y < 0:
                    self.start_hsv[1] = 1.0 + y  #s
                else:
                    self.start_hsv[2] = 1.0 - y
                self.start_hsv[0] = (x + 1) / 2.
            elif data['Path'] == '/sixaxis/lrud':
                val = data['Value']
                vy = val[3] - val[2]
                vx = val[1] - val[0]
                #pdb.set_trace()
                #self.v_xy = (val[1]*ssize[0], (1.0-val[0])*ssize[1])
                self.v_xy = array((vx, vy)) * speedfactor
            else:
                main_log.error('Sensor Inputs: ' + str(sensorInputs))
        self.xy = self.xy + self.v_xy
        constrainLocation(self.xy, self.ssize)
        self.v_xy *= self.v_decay
        ret.append({
            'Color': [i * 255. for i in colorsys.hsv_to_rgb(*self.start_hsv)],
            'Location': (int(self.xy[0]), int(self.xy[1]))
        })

        return (ret, [])
Esempio n. 8
0
def getConnectedSocket(ip,port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        sock.connect((ip, port))
        return sock
    except Exception as inst:
        main_log.error('Network down.  All network based renderers and sensors will not function.',
            inst)
Esempio n. 9
0
def getConnectedSocket(ip, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        sock.connect((ip, port))
        return sock
    except Exception as inst:
        main_log.error(
            'Network down.  All network based renderers and sensors will not function.',
            inst)
Esempio n. 10
0
 def behaviorInit(self):
     [module, className] = self['Class'].split('.')
     try:
         exec('from ' + module+'.'+className + ' import *', globals())
     except Exception as inst:
         main_log.error('Error importing ' + module+'.'+className+ '.  Component not\
         initialized.')
         main_log.error(str(inst)) 
     self.eventGenerator = eval('lambda args:'+className+'(args)') 
Esempio n. 11
0
 def behaviorInit(self):
     [module, className] = self['Class'].split('.')
     try:
         exec('from ' + module + '.' + className + ' import *', globals())
     except Exception as inst:
         main_log.error('Error importing ' + module + '.' + className +
                        '.  Component not\
         initialized.')
         main_log.error(str(inst))
     self.eventGenerator = eval('lambda args:' + className + '(args)')
Esempio n. 12
0
 def processResponse(self, sensorInputs, recursiveInputs):
     ret = []
     for data in sensorInputs:
         if data['Path'].find('horizontal') != -1:
             self.h = data['Value'] / 2.78
         elif data['Path'].find('vertical') != -1:
             self.s = data['Value'] / 1000.0
         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)]})
     return (ret, [])
Esempio n. 13
0
    def doUpdate(self, cid, paramName, newParamValue, currentObject, callback):
        if paramName == 'RenderToScreen':
            if newParamValue == True:
                newParamValue = True
            elif newParamValue == False:
                newParamValue = False
            else:
                newParamValue = None
            if newParamValue is not None:
                currentObject['RenderToScreen'] = newParamValue

        elif currentObject.argDict.has_key(
                'Mutable') and currentObject.argDict['Mutable'].has_key(
                    paramName):
            paramName = paramName.strip('()')
            if paramName in dir(
                    currentObject
            ):  #paramName == 'command_reset' or paramName == 'command_skip':
                member = currentObject.__getattribute__(paramName)
                if hasattr(member, '__call__') and newParamValue:
                    try:
                        member()
                        callback(paramName[8:])
                    except:
                        callback('no ' + paramName[8:])
                elif type(member) is type(newParamValue) and \
                    self.isValidValue(currentObject.argDict['Mutable'][paramName], newParamValue):
                    currentObject.__setattr__(paramName, newParamValue)
                    if currentObject.argDict.has_key(paramName):
                        currentObject[paramName] = newParamValue
                    callback('OK')
                else:
                    callback('FailedWeird')

            elif currentObject.argDict.has_key(paramName):
                if self.isValidValue(
                        currentObject.argDict['Mutable'][paramName],
                        newParamValue):
                    currentObject[paramName] = newParamValue
                    main_log.debug("Modified Correctly")
                    callback('OK')
                else:
                    main_log.error("Invalid modifier, type: " +
                                   str(type(newParamValue)) + " value:" +
                                   str(newParamValue))
                    callback('Failed')
            else:
                main_log.error("Invalid mutable for this object.")
                callback("'" + paramName +
                         "' is invalid method or parameter for this object")
        else:
            raise Exception(
                'Non-mutable parameter specified.'
            )  # don't allow anything else for security purposes
Esempio n. 14
0
def resolveInheritance(el):
    """In place resolution of inheritence.  Doesn't return anything."""
    parentClass = el.find('InheritsFrom')
    if parentClass != None:
        parentTree = loadConfigFile(parentClass.text)
        if parentTree == None:
            main_log.warn('Inheritance Failed.  ' + parentClass.text + 'does not exist')
            main_log.error('Inheritance Failed.  ' + parentClass.text + 'does not exist')
            return el
        el = compositeXMLTrees(parentTree, el) 
        el.remove(parentClass) #get rid of the inheritance flag
Esempio n. 15
0
 def isValidValue(self,obj,val):
     if hasattr(obj, '__call__'):
         valid = obj(val)
     elif type(obj) is type:
         valid = (type(val) is obj)
     elif type(obj) is list:
         valid = (val in obj)
     else:
         main_log.error("invalid validator, need lambda,list,or type: "+str(obj))
         return -1
     return valid
Esempio n. 16
0
 def isValidValue(self, obj, val):
     if hasattr(obj, '__call__'):
         valid = obj(val)
     elif type(obj) is type:
         valid = (type(val) is obj)
     elif type(obj) is list:
         valid = (val in obj)
     else:
         main_log.error("invalid validator, need lambda,list,or type: " +
                        str(obj))
         return -1
     return valid
Esempio n. 17
0
def resolveInheritance(el):
    """In place resolution of inheritence.  Doesn't return anything."""
    parentClass = el.find('InheritsFrom')
    if parentClass != None:
        parentTree = loadConfigFile(parentClass.text)
        if parentTree == None:
            main_log.warn('Inheritance Failed.  ' + parentClass.text +
                          'does not exist')
            main_log.error('Inheritance Failed.  ' + parentClass.text +
                           'does not exist')
            return el
        el = compositeXMLTrees(parentTree, el)
        el.remove(parentClass)  #get rid of the inheritance flag
Esempio n. 18
0
 def processResponse(self, sensorInputs, recursiveInputs):
     ret = []
     for data in sensorInputs:
         if data['Path'].find('horizontal') != -1:
             self.h = data['Value'] / 2.78
         elif data['Path'].find('vertical') != -1:
             self.s = data['Value'] / 1000.0
         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)]
     })
     return (ret, [])
Esempio n. 19
0
def loadConfigFile(fileName): #TODO: error handling etc.
    """Loads a config file.  If its an xml file, inheritances are automatically resolved."""
    try:
        if '.params' in fileName:
            return fileToDict(fileName)
        if '.xml' in fileName:
            config = ElementTree() 
            config.parse(fileName)
            resolveDocumentInheritances(config.getroot())
            return config
    except Exception as inst:
        main_log.error('Error loading config file ' + fileName)#, inst) TODO: log exception too
        main_log.error(str(inst))
        return None
Esempio n. 20
0
def loadConfigFile(fileName):  #TODO: error handling etc.
    """Loads a config file.  If its an xml file, inheritances are automatically resolved."""
    try:
        if '.params' in fileName:
            return fileToDict(fileName)
        if '.xml' in fileName:
            config = ElementTree()
            config.parse(fileName)
            resolveDocumentInheritances(config.getroot())
            return config
    except Exception as inst:
        if '.xml' in fileName:
            main_log.error('Error loading config file ' +
                           fileName)  #, inst) TODO: log exception too
            main_log.error(str(inst))
        return None
Esempio n. 21
0
    def doUpdate(self, cid, paramName, newParamValue, currentObject, callback):
        if paramName == 'RenderToScreen':
            if newParamValue == True:
                newParamValue = True
            elif newParamValue == False:
                newParamValue = False
            else:
                newParamValue = None
            if newParamValue is not None:
                currentObject['RenderToScreen'] = newParamValue
        
        elif currentObject.argDict.has_key('Mutable') and currentObject.argDict['Mutable'].has_key(paramName):
            paramName = paramName.strip('()')
            if paramName in dir(currentObject): #paramName == 'command_reset' or paramName == 'command_skip':
                member = currentObject.__getattribute__(paramName)
                if hasattr(member,'__call__') and newParamValue:
                    try:
                        member()
                        callback(paramName[8:])
                    except:
                        callback('no '+paramName[8:])
                elif type(member) is type(newParamValue) and \
                    self.isValidValue(currentObject.argDict['Mutable'][paramName], newParamValue):
                        currentObject.__setattr__(paramName,newParamValue)
                        if currentObject.argDict.has_key(paramName):
                            currentObject[paramName] = newParamValue
                        callback('OK')
                else:
                    callback('FailedWeird')

            elif currentObject.argDict.has_key(paramName):
                    if self.isValidValue(currentObject.argDict['Mutable'][paramName], newParamValue):
                        currentObject[paramName] = newParamValue
                        main_log.debug("Modified Correctly")
                        callback('OK')
                    else:
                        main_log.error("Invalid modifier, type: "+str(type(newParamValue))+" value:"+str(newParamValue))
                        callback('Failed')
            else:
                main_log.error("Invalid mutable for this object.")
                callback("'"+paramName+"' is invalid method or parameter for this object")
        else:
            raise Exception('Non-mutable parameter specified.') # don't allow anything else for security purposes
Esempio n. 22
0
 def processResponse(self, sensorInputs, recursiveInputs):
     ret = []
     for data in sensorInputs:
         if data['Path'] == '/1/fader1':
             try:
                 self.h = data['Value'][0]*360.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').getSize()[-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, [])
Esempio n. 23
0
 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, [])
Esempio n. 24
0
 def processResponse(self, sensorInputs, recursiveInputs):
     if sensorInputs != []:
         main_log.error('Sensor Inputs: ' + str(sensorInputs))
     return ([], [])