Neetz World
February 19, 2023

MQTT with example

Posted on February 19, 2023  •  3 minutes  • 631 words

What is MQTT ?

MQTT : Message Queue Telemetry Transport


Components of MQTT:

MQTT Architecture

  1. MQTT Broker/Server: It is server which routes published data to the subscriber who subscribed to that topic.

  2. MQTT Clients: The devices which transport data/messages via broker and act as publisher or subscriber.

  3. Topic: This is the special channel/tunnel to pass the messages between a Publisher and its Subscriber.

  4. QoS (Quality of Service): This parameter is to ensure the reliability of the message sent in between Publisher and Subscriber. There are 3 values of this:

    • Qos=0 -> at most once
    • Qos=1 -> at least once
    • Qos=2 -> exactly once

Why MQTT ?


Example in Python:

This is the most basic example to see how the whole publisher-subscriber model works with a broker in between.

Note: There are many tools and libraries available for building Pub/Sub clients. Also, there are a lot of open source Brokers avaiable as listed in this: https://mqtt.org/software .

https://github.com/neetaBirajdar/mqtt_project

Steps:

  1. Create Publisher and Subscriber
  2. Run the Broker
  3. Subscribe to the topic via broker
  4. Publish on the same topic via broker
  5. Check the message recieved by Subscriber which is sent by Publisher

MQTT example

MQTT Client and Broker used here:

Installation of the softwares required:

a. Install paho:

pip install paho-mqtt

b. Install mosquitto:

Install as per OS on the machine you are using with the options given here : https://mosquitto.org/download/

c. Define configuration:

Define the baisc configuration to establish connection and send/recieve the data.

# Add to config.py

HOSTNAME="localhost"
PORT=1883
TOPIC="test/topic"

Note: You can give any Topic name instead of test/topic but make sure you have the same port and hostname if you are running this locally.

d. Create Publisher:

This pubslisher is created using the method publish inside paho.mqtt. It takes the basic configuration which we defined before. Also, here we are publishing the message : “test_message”(you can give any message).

# Add to mqtt_publisher.py

import paho.mqtt.publish as publish
from config import TOPIC, HOSTNAME, PORT

publish.single(
                topic=TOPIC,
                hostname=HOSTNAME,
                port=PORT,
                payload="test_message"
              )

e. Create Subscriber:

Similarly, use subscribe from paho.mqtt to create a basic subcriber who is listening to the defined configuration.client_id can be anything as you are on your local machine. Important: Subscription to a correct topic is necessary to get the expected data.

# Add to mqtt_subscriber.py

import paho.mqtt.subscribe as susbcribe
from config import TOPIC, HOSTNAME, PORT

message  = susbcribe.simple(
                            topics=TOPIC,
                            hostname=HOSTNAME,
                            port=PORT,
                            client_id="test_client",
                            qos=0
                        )

print(f"\nTopic: {message.topic}")
print(f"\nMessage: {message.payload}")

f. Run these in multiple terminals:

  1. First terminal-> Run your Broker using :
mosquitto

It should look like this : MQTT broker Connection

  1. Second terminal -> Run your subscriber using python:
python mqtt_subscriber.py

Once you do this, you will see the test_client connection is established with Broker within first terminal as shown below: MQTT broker with sub connection

  1. Third terminal -> Run the publisher and publish the data:
python mqtt_publisher.py

On first terminal, you will see a new connection:

MQTT broker with pub-sub connection

And on second terminal, you will see the data published by the publisher which we ran using python:

MQTT sub message

Finally, the loop is completed.

Congratulation !!

You have create an end-to-end flow for Publisher-Subscriber model via Broker.

Follow me

To have some coding fun and learning new things!