python - 即使我的 MQTT 客户端未连接,我如何继续我的程序运行?

标签 python 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()

最佳答案

编辑:我在我这边运行了你的代码,大约 30 秒后我得到一个 TimeoutError 异常:“A connection attempt failed because the connected party did not properly respond after a period of时间”。您需要在代码中处理该异常,以便程序即使在连接失败时也能继续运行:

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()loop_forever() 不适合您的需求,因为它们是阻塞函数(也就是说,它们会阻塞您的代码的执行并且防止它做任何其他事情)。使用上面的代码,如果客户端成功连接,由于 loop_forever()print("rest of the code here") 将永远不会到达。

相反,尝试结合使用 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)

这将输出此处的其余代码并继续无限期地运行(在无限的while 循环中),无论连接是否成功。

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

on_connect(客户端、用户数据、标志、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/)。

关于python - 即使我的 MQTT 客户端未连接,我如何继续我的程序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390127/

相关文章:

python - 导入的模块不正确

jms - Open MQ 使用哪种传输协议(protocol)?

android - 通过电话本身将 MQTT 数据发送到服务器,即不使用 setOnClickListener() 或任何其他事件

python - python解释器如何处理对象的负引用计数?

python - 有没有办法不缓冲来自 UDP 套接字的数据

python - Python 中的矩阵补全

python - wxpython : button covers all in the frame

sockets - 如何在 Mosquitto 中同时启用 TCP 和 Web 套接字?

javascript - 为什么在将 Paho MQTT 函数从 Angular 1 迁移到 Angular 2 时收到 typescript 错误?

mongodb - MQTT 代理 + mongoDB