示例#1
0
def keepalive():
    """Make sure to let Redis know we're still alive"""
    while True:
        # will expire one second after the keep alive...
        keeptime = config.getint('redis', 'keepalive') + 1

        # set expirations on my data
        r.setex(myid(), int(time.time()), keeptime)
        r.expire('%s:clients' % myid(), keeptime)

        # clear any clients that are too old
        r.zremrangebyscore('%s:clients' % myid(), 0, int(time.time()))

        yield from asyncio.sleep(config.getint('redis', 'keepalive'))
示例#2
0
def handle_connect(message, addr):
    logger.debug("Handling CONNECT")

    keeptime = config.getint('redis', 'keepalive') + 1
    addr_s = pickle.dumps(addr)

    # tracking entry in redis (will be expired manually)
    r.zadd('%s:clients' % broker.myid(), addr_s,
           int(time.time()) + message.duration)

    # socket for this client
    r.hmset(
        '%s:client_info' % addr_s, {
            'broker_id': broker.myid(),
            'client_id': message.client_id,
            'last_message': int(time.time())
        })

    # be sure to clean up
    r.expire('%s:client_info' % addr_s, keeptime)

    # broker lookup entry
    r.set('%s:broker' % message.client_id, broker.myid())

    # socket lookup entry
    r.set('%s:socket' % message.client_id, addr_s)

    # TODO: if clean session is set, expire stuff related
    # to this this client right now

    # queue the CONNACK
    queue_msg(addr_s, create_connack(message))
示例#3
0
def queue_msg(destination, payload):
    if payload is None:
        logger.info('Cowardly refusing to queue empty payload')
        return

    # add to the outgoing queue for that broker
    logger.debug('Queued message for %s' % destination)
    keeptime = config.getint('redis', 'keepalive') + 1
    r.rpush('%s:queue' % (destination, ), payload)
    r.expire('%s:queue' % (destination, ), int(time.time() + keeptime))
示例#4
0
def main():
    """Set up logging, start the event loop"""
    # File and console
    fh = logging.FileHandler(config.get('logging', 'path'))
    ch = logging.StreamHandler()

    # Set log levels
    log_level = config.get('logging', 'level')
    logger.setLevel(log_level)
    fh.setLevel(log_level)
    ch.setLevel(log_level)

    # Set format
    formatter = logging.Formatter(config.get('logging', 'format'))
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # Add handlers
    logger.addHandler(fh)
    logger.addHandler(ch)

    # ready to go
    logger.info("pymqttsn broker started")

    # start the asyncio loop
    loop = asyncio.get_event_loop()
    if signal is not None:
        loop.add_signal_handler(signal.SIGINT, loop.stop)

    host = config.get('mqtt_sn', 'listen_host')
    port = config.getint('mqtt_sn', 'listen_port')

    server = start_server(loop, (host, port))

    try:
        loop.run_forever()  # and ever and ever
    finally:
        server.close()
        loop.close()
        logger.info('Goodnight, sweet prince')