Пример #1
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_last_will(topic='hack42/tele/loungeledjes/status',
                         msg='offline',
                         retain=True)
    client.connect()
    client.publish('hack42/tele/loungeledjes/ifconfig',
                   str(sta_if.ifconfig()),
                   retain=True)
    client.publish('hack42/tele/loungeledjes/status', 'online', retain=True)
    return client
Пример #2
0
def mqtt_connect():
    # mqtt初始化
    print("mqtt_broker:%s" % config['mqtt_broker'])
    client = MQTTClient(client_id=config['mqtt_client_id'],
                        server=config['mqtt_broker'],
                        port=config['mqtt_port'],
                        user=config['mqtt_user'],
                        password=config['mqtt_pwd'],
                        keepalive=120)
    # 设置mqtt订阅回调
    client.set_callback(mqtt_callback)
    # 设置遗言
    # 向主题/{dev_id}/devstate ,发送{"dev_id":2,"dev_state":"offline"}
    last_will = json.dumps({"dev_id": DEVICE_ID, "dev_state": 'off'})
    client.set_last_will(DEVICE_ID + '/devstate', last_will)
    return client