So, If the broker goes down for lets say 20 seconds and comes back up and I have published something, there will be data loss. I have tried adding Qos as 2 and retain = true but only the last message is displayed i.e. If I enter 1,2,3 when broker is down then only 3 will be shown! Tried similar queries on StackOverflow but only worked while printing the last previous data!
This is what I have tried and understood till now using MQTT. But I still don't know how to prevent data loss!
Publisher ==>
import paho.mqtt.client as mqtt
# MQTT broker details
broker_address = "localhost"
port = 1883
client = mqtt.Client()
client.connect(broker_address, port, 60)
client.loop_start()
while True:
message = input("Enter message to publish (or 'q' to quit): ")
if message == 'q':
break
client.publish("mytestingtopic", message, retain=True, qos=2)
Subscriber =>
import paho.mqtt.client as mqtt
import time
broker_address = "localhost"
port = 1883
def on_connect(client, userdata, flags, rc):
# print("Connected with result code " + str(rc))
client.subscribe("mytestingtopic", qos=2)
def on_message(client, userdata, msg):
print("Received message: " + msg.topic + " " + str(msg.payload))
# Create MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
while True:
try:
client.connect(broker_address, port, 60)
client.loop_start()
while True:
pass
except KeyboardInterrupt:
client.loop_stop()
break
except Exception as e:
print("Error: " + str(e))
time.sleep(5)