I have below code for mqtt client for receiving message from broker.
If client is disconnected from broker then client tries to connect with broker using connect()
call again. I have read paho documentation saying that loop_start()
will handle reconnection with broker. Please let me know if is it right to use connect()
call for reconnection with broker or let it handle by loop_start()
itself.
import paho.mqtt.client as mqtt
import json
import time
is_connect = False
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print("Message received on "+msg.topic)
parsed_message = json.loads(msg.payload)
print(json.dumps(parsed_message, indent=4, sort_keys=True))
def on_disconnect(client, userdata, rc):
if rc != 0:
print "Unexpected disconnection." , (rc)
global is_connect
is_connect = False
while True:
global is_connect
#If client is not connected, initiate connection again
if not is_connect:
try:
client = mqtt.Client(client_id='testing_purpose', clean_session=False)
client.loop_stop()
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect("localhost", 1883, 5)
is_connect = True
client.loop_start()
time.sleep(15)
except Exception as err:
is_connect = False
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
#client.loop_forever()