paho-MQTT python:如何让loop_forever支持订阅消息?
问题描述:
我已经在paho-mqtt上测试了示例程序,并且我知道函数loop_forever()可以处理重新连接。但我的问题是,虽然loop_forever()可以重新连接,但它不能重新订阅。当服务器突然崩溃时应该是一个问题,在这种情况下,客户端仍在监听,但是当服务器重新启动时,客户端可以重新连接,但不能再订阅消息。我想也许我应该重写loop_forever()函数,但我不确定我是否正确,以及如何去做。paho-MQTT python:如何让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
回调,然后。
答
在实例化您的mqtt客户端时,您可以将“清理会话”标志设置为false。
mqttc = mqtt.Client(clean_session=False)
引文从mosquitto手册:
清洁会话/耐用连接
在连接中,客户机设置了“干净的会话”标志,其有时也被称为“干净启动”标志。如果干净会话设置为false,则该连接被视为持久。这意味着,当客户端断开连接时,它的任何订阅都将保留,任何后续的QoS 1或2消息将被存储,直到将来再次连接。如果清理会话为真,那么客户端在断开连接时将删除所有订阅。
它确实有用,非常感谢! –