MQTT is the most used protocol for IoT to exchange data between devices over the internet. The protocol follows a set of rules on how devices can publish and subscribe to data. Both the publisher and the subscriber communicate using topics which are handled by the MQTT broker.
The broker will filter all messages which are published to a topic and will distribute them to the subscribers who have subscribed to the topic.
We will use the HiveMQ broker for our below example to see how MQTT works (https://www.hivemq.com/public-mqtt-broker/).
Code to publish to a topic [publisher.py]
import paho.mqtt.client as paho
broker = "broker.hivemq.com"
port = 1883
def on_publish(client, userdata, result):
print("Publisher: Data published.")
client = paho.Client()
client.on_publish = on_publish
for x in range(100):
d = random.randint(1, 500)
message = str(d)
ret = client.publish("<your_topic_here>", message) #Update your topic here
Code to subscribe to a topic [subscriber.py]
import paho.mqtt.client as mqtt
port = 1883
timelive = 60
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("<your_topic_here>") #Update your topic here
def on_message(client, userdata, msg):
client = mqtt.Client()
client.connect(broker, port, timelive)
client.on_connect = on_connect
client.on_message = on_message