python - 重新连接后读取订阅的MQTT消息

标签 python mqtt paho

我正在尝试读取 MQTT 服务器上的消息。某些情况下,连接不稳定,需要重新连接。但重新连接后,我无法收到来 self 之前订阅的主题的任何消息。我正在使用 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 墙上的浏览器中看到它们

最佳答案

您尚未显示调用 connect 的位置,但通常的安全模式是将对 subscribe() 的调用放在附加到的 on_connect() 回调中。客户端。

这意味着订阅调用将

  1. 始终等待连接完成
  2. 重新连接时自动再次调用

关于python - 重新连接后读取订阅的MQTT消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65110695/

相关文章:

java - 使用单一连接实例实现 Eclipse MQTT Android 客户端

python - 谷歌云物联网 Python MQTT "out of memory"错误

python - 错误 :root:code for hash md5 was not found

python - 将字符串一中的字符替换为字符串二

unit-testing - 如何为 MQTT 客户端编写测试?

java - 编写无代理 AMQP 到 MQTT 适配器

mqtt - Mosquitto MQTT Broker 中的访问控制

python - tensorflow word2vec 教程如何更新嵌入?

python - 这个测试有意义吗?

mqtt - 如何设置 Mosquitto 桥接配置?