mqtt data not visible in topic

Viewed 13

I am running into a very strange scenario. I am pushing JSON data to the MQTT broker every other 2 minutes from k8s cron job.

Code I use to publish to mqtt.

import paho.mqtt.client as mqtt
from bs4 import BeautifulSoup
import json
import os

MQTT_HOST = os.environ["MQTT_HOST"]
MQTT_PORT = int(os.environ["MQTT_PORT"])
MQTT_KEEPALIVE_INTERVAL = int(os.environ["MQTT_KEEPALIVE_INTERVAL"])
MQTT_TOPIC = os.environ["MQTT_TOPIC"]

# Define on_publish event function
def on_publish(client, userdata, mid):
    print("Message Published...")


# Initiate MQTT Client
mqttc = mqtt.Client()

# Register publish callback function
mqttc.on_publish = on_publish

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

mqttc.loop_start() #start loop to process received messages
print("subscribing ")
mqttc.subscribe(MQTT_TOPIC)#subscribe

print("publishing ")
# Publish message to MQTT Broker
mqttc.publish(MQTT_TOPIC, json.dumps(reading_table_data))

# Disconnect from MQTT_Broker
mqttc.disconnect()
mqttc.loop_stop() #stop loop

JSON data it is sending to mqtt broker. {"Energy Source": "EB", "Grid Reading ": "2683.4", "DG Reading ": "15.5", "Power Factor": "0.897", "Total Kw": "0.463", "Total KVA": "0.521", "Average Voltage": "244.3", "Total Current": "2.63", "Frequency Hz": "49.9", "accountBalance": "3796.20"}

Now when I opened mqtt explorer (client) to see data, it's not visible initially.

enter image description here

it becomes available after 2 minutes (when cron again pushes the data) and shows only until mqtt explorer (client) windows are opened.

enter image description here

my query is why the data is not persisted. or something wrong with the code? I would like to subscribe to the topic JSON key in another program.

Any guidance is appreciated.

1 Answers

Normally MQTT messages are not persisted. They are delivered to any clients connected at the time the message is published.

If a client connects, subscribes at a high QOS (1 or 2) then disconnects, the messages will be queued for that specific client and if they reconnect with the same client id and with the clean session flag set to false the queued messages will be delivered.

You can have the broker persist the last message published on a topic and deliver it to any client that subscribes to that topic before any other messages by setting the retained flag on the message when it's published.

https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php#publishing

mqttc.publish(MQTT_TOPIC, json.dumps(reading_table_data), retain=True)

https://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages/

Related