Exemplo n.º 1
0
def myMsgHandler(topic, payload, *args, **kwargs):
    ''' function called whenever our MQTT client receive weather data.
        Beware that it's called by mqtt_loop's thread !
    '''

    # check for special topics we're not interested in
    if (topic.startswith('_') or topic.startswith('TestTopic')
            or "camera" in topic):
        log.debug("special topic not for us: %s" % str(topic))
        return

    # extract timestamp ... or set it
    #_dataTime = int(float( payload.get('dateTime', time.time()) ))
    _dataTime = datetime.utcnow()

    log.debug("MSG topic '%s' received ..." % str(topic))
    print(payload)

    # extract addon parameters ...
    # ... this way to be sure they are defined ;)
    try:
        mydb = kwargs['db']
        valueUnitsIDS = kwargs['valueUnits']
        sensorsIDlist = kwargs['hints']
    except Exception as ex:
        log.error("missing several parameters (!!) : " + str(ex),
                  exc_info=(getLogLevel().lower() == "debug"))
        return
    '''
Exemplo n.º 2
0
 def update(self):
     if logger.getLogLevel() == logger.LOG_DEBUG:
         logger.debug("Updating",len(self.objectTree.getObjects()),"objects")
     self.objectTree.prepObjects()
     self.objectTree.runObjectCollisionDetection()
     self.objectTree.runTerrainCollisionDetection()
     self.objectTree.cleanupObjects()
Exemplo n.º 3
0
    def run( self ):
        # load module
        log.info("module loading")
        self.load()

        # start connection
        log.info("start MQTT connection to '%s:%d' ..." % (self._addons['mqtt_server'],self._addons['mqtt_port']))
        self._connection.connect( host=self._addons['mqtt_server'], port=self._addons['mqtt_port'], keepalive=settings.MQTT_KEEP_ALIVE )

        # launch
        try:
            while not self._shutdownEvent.is_set():

                if self._connection.loop(timeout=2.0) != mqtt_client.MQTT_ERR_SUCCESS:
                    log.debug("loop failed, sleeping a bit before retrying")
                    time.sleep(2)

            log.debug("shutdown activated ...")

        except Exception as ex:
            if getLogLevel().lower() == "debug":
                log.error("module crashed (high details): " + str(ex), exc_info=True)
            else:
                log.error("module crashed: " + str(ex))

        # shutdown module
        log.info("module stopping")
        self.quit()

        # disconnect ...
        self._connection.disconnect()

        # end of thread
        log.info("Thread end ...")
Exemplo n.º 4
0
 def addNewObject(self, objectName, *args):
     if logger.getLogLevel() >= logger.LOG_INFORM:
         numObjects = len(self.objectTree.getObjects()) + 1
         logger.inform("Adding",numObjects,"th object named",objectName,"with args",*args)
     objectPath = os.path.join(constants.objectsPath, objectName)
     objectPath = objectPath.replace(os.sep, '.')
     objectFunc = game.dynamicClassManager.loadDynamicClass(objectPath)
     newObject = objectFunc(*args)
     self.objectTree.addObject(newObject)
     return newObject
Exemplo n.º 5
0
 def draw(self, loc, progress):
     drawLoc = loc
     if self.drawOffset.magnitudeSquared() > constants.EPSILON:
         drawLoc = loc.add(self.drawOffset).round()
     frame = int(self.prevFrame + (self.frame - self.prevFrame) * progress)
     if self.isComplete:
         frame = len(self.frames) - 1
     surface = self.frames[int(frame) % len(self.frames)]
     game.imageManager.drawGameObjectAt(surface, drawLoc)
     if logger.getLogLevel() == logger.LOG_DEBUG:
         # Draw the bounding polygon and location information
         self.polygon.draw(loc)
         gridLoc = loc.toGridspace()
         game.fontManager.drawText('MODENINE', 12,
                 ['%d' % gridLoc.x,
                  '%d' % gridLoc.y,
                  '%d' % loc.x,
                  '%d' % loc.y],
                 loc = drawLoc.addScalar(25),
                 isPositioningAbsolute = False
         )
Exemplo n.º 6
0
def main():

    # Global variables
    global _shutdownEvent, mydb, valueUnits, hints

    # create threading.event
    _shutdownEvent = threading.Event()

    # Trap CTRL+C (kill -2)
    signal.signal(signal.SIGINT, ctrlc_handler)
    '''
    #
    # MongoDB
    log.info("Initiate connection to MongoDB.neocampus database ...")

    _mongo_user = os.getenv("MONGO_USER")
    if( _mongo_user is None or _mongo_user == "" ):
        log.error("unspecified MONGO_USER ... aborting")
        time.sleep(3)
        sys.exit(1)
    
    _mongo_passwd = os.getenv("MONGO_PASSWD")
    if( _mongo_passwd is None or _mongo_passwd == "" ):
        log.error("unspecified MONGO_PASSWD ... aborting")
        time.sleep(3)
        sys.exit(1)

    _mongo_server = os.getenv("MONGO_SERVER", settings.MONGO_SERVER)
    if( _mongo_server is None or _mongo_server == "" ):
        log.error("unspecified MONGO_SERVER ... aborting")
        time.sleep(3)
        sys.exit(1)

    _mongo_port = os.getenv("MONGO_PORT", settings.MONGO_PORT)
    if( _mongo_port is None or _mongo_port == "" ):
        log.error("unspecified MONGO_PORT ... aborting")
        time.sleep(3)
        sys.exit(1)

    _mongo_database = os.getenv("MONGO_DATABASE", settings.MONGO_DATABASE)
    if( _mongo_database is None or _mongo_database == "" ):
        log.error("unspecified MONGO_DATABASE ... aborting")
        time.sleep(3)
        sys.exit(1)

    # connect ...
    mydb = connect_db( _mongo_user,
                        _mongo_passwd,
                        _mongo_server,
                        _mongo_port,
                        _mongo_database )

    if( mydb is None ):
        log.error("unable to connect to MongoDB ?!?! ... aborting :(")
        time.sleep(3)
        sys.exit(1)

    # extract things from mongoDB
    valueUnits  = dict()
    hints = dict()
    # parse 'typecapteur' collection (e.g temperature, co2, humidity etc etc)
    for each in mydb.typecapteur.find():
        # parse units of values (e.g luminosity --> lux (inside), w/m2 (outside)
        for inner in each["Libvals"] :
            valueUnits[inner["unite"]] =  inner["idLibVal"]

        # parse sensors: each sensor has an ID
        # key nomCapteur: <topic/unitID/subID> e.g u4/campusfab/temperature/auto_92F8/79
        #   value = list( id associated with <topic/unitID/subID>, id piece )
        for inside in each["Capteurs"]:
            hints[ inside["nomCapteur"] ] = [ inside["idCapteur"], inside["Piece_courante"]["idPiece"] ]

    print("valueUnits : " + str(valueUnits) )
    print("hints : " + str(hints) )

    log.info("MongoDB connection is UP featuring:\n\t{0:,d} measures :)\n\t{1:,d} unmanaged measures :(".format(mydb.measure.count(),mydb.failedData.count()) )
    time.sleep(2)
    '''

    #
    # MQTT
    log.info("Instantiate MQTT communications module ...")

    params = dict()

    # shutown master event
    params['_shutdownEvent'] = _shutdownEvent

    # credentials
    _mqtt_user = os.getenv("MQTT_USER", settings.MQTT_USER)
    if (_mqtt_user is None or not len(_mqtt_user)):
        log.error("unspecified MQTT_USER ... aborting")
        sys.exit(1)
    params['mqtt_user'] = _mqtt_user

    _mqtt_passwd = os.getenv("MQTT_PASSWD", settings.MQTT_PASSWD)
    if (_mqtt_passwd is None or not len(_mqtt_passwd)):
        log.error("unspecified MQTT_PASSWD ... aborting")
        sys.exit(1)
    params['mqtt_passwd'] = _mqtt_passwd

    # topics to subscribe and addons
    try:
        _mqtt_topics = json.loads(os.getenv("MQTT_TOPICS"))
    except Exception as ex:
        # failed to fing env var MQTT_TOPICS ... load from settings
        _mqtt_topics = settings.MQTT_TOPICS
    if (_mqtt_topics is None or not len(_mqtt_topics)):
        log.error("unspecified or empty MQTT_TOPICS ... aborting")
        sys.exit(1)
    params['mqtt_topics'] = _mqtt_topics

    # host'n port parameters
    params['mqtt_server'] = os.getenv("MQTT_SERVER", settings.MQTT_SERVER)
    params['mqtt_port'] = os.getenv("MQTT_PORT", settings.MQTT_PORT)

    # unitID
    params['unitID'] = os.getenv("MQTT_UNITID", settings.MQTT_UNITID)

    # TODO: replace with log.debug( ... )
    if getLogLevel().lower() == "debug":
        print(params)

    client = None
    try:
        # init client ...
        client = CommModule(**params)
        # register own message handler
        client.handle_message = myMsgHandler

        # ... then start client :)
        client.start()

    except Exception as ex:
        if getLogLevel().lower() == "debug":
            log.error("unable to start MQTT comm module (high details): " +
                      str(ex),
                      exc_info=True)
        else:
            log.error("unable to start MQTT comm module: " + str(ex))
        sys.exit(1)

    #
    # main loop

    # initialise _condition
    _condition = threading.Condition()

    with _condition:

        while (not _shutdownEvent.is_set()):

            #
            #
            # ADD CUSTOM PROCESSING HERE
            #

            # now sleeping till next event
            if (_condition.wait(2.0) is False):
                #log.debug("timeout reached ...")
                pass
            else:
                log.debug("interrupted ... maybe a shutdown ??")
                time.sleep(1)

    # end of main loop
    log.info("app. is shutting down ... have a nice day!")
    _shutdownEvent.set()
    time.sleep(4)