首页 > 解决方案 > 即使我的 MQTT 客户端未连接,我如何继续运行我的程序?

问题描述

我正在编写一个在树莓派上运行并连接到 pic-camera 的 python 程序。当我使用 MQTT 时,当客户端没有通过程序连接时冻结。即使客户端没有连接,是否有任何方法可以继续运行程序,即我没有收到任何数据但相机仍然运行。

例如,即使客户端没有连接,我如何打印 x ?

import time
import paho.mqtt.client as mqtt
import json


def on_connect(client, userdata, rc):
    print ("Connected with rc: " + str(rc))
    client.subscribe("demo/test1")

def on_message(client, userdata, msg):
    data_json = msg.payload
    data = json.loads(data_json)

print(data['ant_plus_power'])

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

x = client.connect("118.138.47.99", 1883, 60)
print(x)

client.loop_forever()

标签: pythonmqtt

解决方案


编辑:我最后运行了您的代码,TimeoutError大约 30 秒后出现异常:"A connection attempt failed because the connected party did not properly respond after a period of time". 您需要在代码中处理该异常,以便程序即使在连接失败时也能继续运行:

try:
    client.connect("118.138.47.99", 1883, 60)
    client.loop_forever()
except:
    print("failed to connect, moving on")

print("rest of the code here")

这输出:

failed to connect, moving on
rest of the code here

但是,使用connect()andloop_forever()并不适合您的需求,因为它们是阻塞函数(意思是,它们会阻塞代码的执行并阻止它执行任何其他操作)。使用上面的代码,如果客户端成功连接,print("rest of the code here")由于loop_forever().

相反,请尝试以非阻塞方式connect_async()与连接一起使用(这意味着您的程序可以在尝试在后台连接时继续做其他事情):loop_start()

client.connect_async("118.138.47.99", 1883, 60)
client.loop_start()

print("rest of the code here")

while True:
    time.sleep(1)

无论连接是否成功,这都会输出rest of the code here并无限期地继续运行(在无限循环中)。while

请注意,您的on_connect()定义缺少一个参数。它应该是:

on_connect(client, userdata, flags, rc)

此外,检查 的返回码可能是个好主意on_connect,并且仅在连接成功时才订阅:

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        client.connected_flag = True # set flag
        print("Connected OK")
        client.subscribe("demo/test1")
    else:
        print("Bad connection, RC = ", rc)
        mqtt.Client.bad_connection_flag = True

# create flags so you can check the connection status throughout the script
mqtt.Client.connected_flag = False 
mqtt.Client.bad_connection_flag = False

请参阅https://www.eclipse.org/paho/clients/python/docs/http://www.steves-internet-guide.com/client-connections-python-mqtt/

为了快速测试成功的连接,您可以连接到test.mosquitto.org(请参阅https://test.mosquitto.org/)。


推荐阅读