gpt4 book ai didi

python - paho-MQTT python : How to let the loop_forever support subscribe message?

转载 作者:行者123 更新时间:2023-12-01 03:57:21 28 4
gpt4 key购买 nike

我已经在 paho-mqtt 上测试了示例程序,并且我知道函数 Loop_forever() 可以处理重新连接。但我的问题是,虽然loop_forever()可以重新连接,但它不能重新订阅。应该是服务器突然崩溃的时候出现问题,此时客户端还在监听,但是当服务器重新启动后,客户端可以重新连接,但不能再订阅消息了。我想也许我应该重写loop_forever()函数,但我不确定我是否正确,以及如何做到这一点。

import sys
try:
import paho.mqtt.client as mqtt
except ImportError:
# This part is only required to run the example from within the examples
# directory when the module itself is not installed.
#
# If you have the module installed, just use "import paho.mqtt.client"
import os
import inspect
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import paho.mqtt.client as mqtt

def on_connect(mqttc, obj, flags, rc):
print("rc: "+str(rc))

def on_message(mqttc, obj, msg):
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_publish(mqttc, obj, mid):
print("mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
print(string)

# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
mqttc.connect("m2m.eclipse.org", 1883, 60)
mqttc.subscribe("$SYS/#", 0)


mqttc.loop_forever()

最佳答案

处理此问题的简单方法是在 on_connect 回调中进行订阅,然后当您重新连接时,所有订阅也将恢复。

关于python - paho-MQTT python : How to let the loop_forever support subscribe message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225839/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com