Search code examples
pythonmqttpublish-subscribepahomessagebroker

Mqtt doesn't send data to subscriber after reconnection


I have a mqtt beoker which i am trying to connect and subscribe in python. code

client = mqtt.Client("P1",clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback
client.on_disconnect = on_disconnect
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
print("Subscribing to topic","topic")
client.subscribe("topic")
client.loop_forever() 

call back functions

def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("connected OK Returned code=",rc)
        print(client)
    else:
        print("Bad connection Returned code=",rc)

def on_disconnect(client, userdata, rc):
   print("Client Got Disconnected")
   if rc != 0:
       print('Unexpected MQTT disconnection. Will auto-reconnect')

   else:
       print('rc value:' + str(rc))

   try:
       print("Trying to Reconnect")
       client.connect(broker_address, port)
       client.subscribe("topic")

       print('tried to subscribe')
   except:
       print("Error in Retrying to Connect with Broker")

def on_message(client, userdata, message):
    print("message received ")

So the problem, client gets connected to broker , receives messages for a while and gets disconnected. I have added a re-connection once the client gets disconnected. Now it gets connected but client is not receiving any messages. Output

connecting to broker
Subscribing to topic unilever
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
message received
.
.
.
.

recieves messaged for a while and gets disconnected. Output

Client Got Disconnected
Unexpected MQTT disconnection. Will auto-reconnect
Trying to Reconnect
tried to subscribe
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>

Can someone help me with why this is happening?

Thanks


Solution

  • This is because you get a fresh session by default when you reconnect (because you have clean_session=True), so you have no active subscriptions.

    Move the call to client.subscribe('topic') to inside the on_connect callback then it will resubscribe when it reconnects.