【发布时间】:2021-03-14 13:35:52
【问题描述】:
我正在尝试读取 MQTT 服务器上的消息。在某些情况下,连接不稳定,需要重新连接。但重新连接后,我无法收到来自我之前订阅的主题的任何消息。我正在使用 paho 的 python 包来处理 MQTT 连接。这是我正在使用的一些代码
TopicName='some/topic/name'
class Counter:
def __init__(self, mqttClient):
self.messages_recieved = 0
self.mqttClient = mqttClient
self.mqttClient.subscribe(TopicName)
self.mqttClient.on_message = self.on_message
self.mqttClient.on_disconnect = self.on_disconnect
self.mqttClient.loop_start()
def on_message(self, client, userdata, message):
self.messages_received += 1
def on_disconnect(self, client, userdata, rc):
if rc != 0:
print("Trying to reconnect")
while not self.mqttClient.is_connected():
try:
self.mqttClient.reconnect()
except OSError:
pass
如果我的互联网出现故障,我将无法再接收消息。我尝试再次订阅该主题,也尝试在 on_disconnect 方法中调用 loop_start,但这些都不起作用。任何解决方案都会有所帮助。还要指出正在发送消息,我可以在 MQTT 墙上的浏览器中看到它们
【问题讨论】:
-
self.mqttClient.subscribe(TopicName)将默认为 QOS 0,spec 不要求代理在此 QOS 级别保留消息。试试 QOS 1/2(例如subscribe(TopicName, qos=1))。