0
votes

I am trying to read messages on a MQTT server. In some cases, the connection is unstable and requires to reconnect. But after reconnect, I am not able to receive any message from the topic that I previously subscribed to. I am using paho's python package to handle MQTT connection. Here is some code I am using

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

If my internet goes down, I am no longer able to receive messages. I have tried to subscribe again to the topic, also I have tried to call loop_start in the on_disconnect method, neither of those worked. Any solution would be helpful. Also to point out messages are being sent, I can see them in the browser on MQTT wall

2
self.mqttClient.subscribe(TopicName) will default to QOS 0 and the spec does not require that brokers retain messages at this QOS level. Try QOS 1/2 (e.g. subscribe(TopicName, qos=1)) . - Brits

2 Answers

0
votes

You have not shown where you are calling connect, but the usual safe pattern is to put the calls to subscribe() in the on_connect() callback attached to the client.

This means that calls to subscribe will

  1. Always wait until the connection has completed
  2. Get called again automatically when a reconnect had happend
0
votes

Not sure what module you are using, but most will require you to re-subscribe if you disconnect. Add your subscribe() call after your .reconnect() call and you should be good to go. Also, keep in mind that at QOS level 0, any messages that the broker received while you were disconnect, your client will NOT receive...only messages while the client is subscribed will be received by your client. If messages are published with the Retain flag, you client will receive the LAST one received by the broker...even if the client previously received it.