How to publish and subscribe to an EMQX-MQTT Broker?

by Mar 26, 2021Communication Protocols

In this article, we will learn about “How to publish and subscribe to an EMQX-MQTT broker” using python. Before getting into the topic let us freshen up about MQTT protocol. MQTT is a lightweight Internet of Things (IoT) messaging protocol based on publish/subscribe model. In which the broker(EMQX-MQTT) acts as a middleman between the publisher(Who publish the message) and the subscriber(Who subscribe to the message), relaying messages from one to the other.

working of EMQX-MQTT

However, this article primarily explains “How to use the paho-mqtt client in the Python project” and also “How to implement connection, subscribe, messaging, and other functions between the client and EMQX-MQTT broker”.

The use of EMQX Broker and Python Paho MQTT client

Creating cloud EMQX-MQTT broker

The free version of EMQX-broker will be used in this article. This service is built on the MQTT IoT cloud platform. The broker’s access information is as follows:

  1. Firstly, we have to create an account in EMQX-broker
creating account in EMQX broker

2. After creating an account in EMQX-broker. Secondly, we have to create a “New deployment”.

CREATING DEPLYOMENT

4. Click “+ Create deployment” to create a cloud server. After entering required values, finally click “Deploy” to create your deployment.

creating cloud

5. At last, your successfully created deployment will appear as below.

cloud details

6. Don’t forget to note down your address and port details of your deployment.

deployment details

7. Click the “EMQ X Dashboard” to create a “Username and Password” for your connection.

Once the “EMQ X Dashboard” tab opens click “Users & ACL” to add your username and password to your server. Finally, click “Add” to save the entered details.

server topic

Python code for publish and subscribe to EMQX-MQTT broker

Import the Paho MQTT client

The Paho Python Client provides a client class with support for both MQTT v3.1 and v3.1.1 on Python 2.7 or 3.x. It also provides some helper functions to make publishing one off messages to an MQTT server very straightforward.

from paho.mqtt import client as mqtt_client

Set the EMQX-MQTT Broker connection parameter

First, set the MQTT Broker connection’s address, port, and topic. Simultaneously, we use the Python function "random.randint” to generate a random MQTT client id.

#Connect address of your deployment 
BROKER = 'p70e2b8e.en.emqx.cloud 
#Connect ports of your deployment 
PORT = 12482
TOPIC = "SUBCRIBE AND PUBLISH TO AN EMQX-MQTT BROKER"
# generate client ID with pub prefix randomly
CLIENT_ID = "python-mqtt-tcp-sub-{id}".format(id=random.randint(0, 1000))
USERNAME = 'IOTEDU' 
PASSWORD = 'public'

Write the EMQX-MQTT connect function

In the following code, we use “on_connect “as connect call back function. This function will be called after the client has been connected, and we can check if the client has been successfully connected using “rc" in this function. Typically, we’ll build a MQTT client at the same time and connect it to “p70e2b8e.en.emqx.cloud”(broker).

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
        client.subscribe(TOPIC)
    else:
        print("Failed to connect, return code {rc}".format(rc=rc), )”

def connect_mqtt():
    client = mqtt_client.Client(CLIENT_ID)
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.connect(BROKER, PORT)
    return client

Write the EMQX-MQTT Publish message function

Firstly, we start by creating a while loop. We’ll use the MQTT client “publish” function in this loop to send messages to the “SUBSCRIBE AND PUBLISH TO AN EMQX-MQTTBROKER” topic every second.

def publish(client):
    msg_count = 0
    while True:
        msg_dict = {
            'msg': msg_count
        }
        msg = json.dumps(msg_dict)
        result = client.publish(TOPIC, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print("Send `{msg}` to topic `{topic}`".format(msg=msg, topic=TOPIC))
        else:
            print("Failed to send message to topic {topic}".format(topic=TOPIC))
        msg_count += 1
        time.sleep(1)

Write the EMQX-MQTT Subscribe to messages function

Secondly, we created the “on_message” callback function. After the client has received messages from the MQTT Broker, this function will be called. We’ll use this function to print the names of subscribed topics as well as the messages we’ve received.

def on_message(client, userdata, msg):
    print("Received `{payload}` from `{topic}` topic".format(
        payload=msg.payload.decode(), topic=msg.topic))


def connect_mqtt():
    client = mqtt_client.Client(CLIENT_ID)
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(BROKER, PORT)
    return client

The complete code for publishing and subscribing in python

Code for publish messages in python

import json
import random
import time

from paho.mqtt import client as mqtt_client


BROKER = ' p70e2b8e.en.emqx.cloud'
PORT = 12482
TOPIC = " SUBCRIBE AND PUBLISH TO AN EMQX-MQTT BROKER "
# generate client ID with pub prefix randomly
CLIENT_ID = "python-mqtt-tcp-pub-{id}".format(id=random.randint(0, 1000))
USERNAME = 'IOTEDU'
PASSWORD = 'public'
FLAG_CONNECTED = 0


def on_connect(client, userdata, flags, rc):
    global FLAG_CONNECTED
    if rc == 0:
        FLAG_CONNECTED = 1
        print("Connected to MQTT Broker!")
    else:
        print("Failed to connect, return code {rc}".format(rc=rc), )


def connect_mqtt():
    client = mqtt_client.Client(CLIENT_ID)
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.connect(BROKER, PORT)
    return client


def publish(client):
    msg_count = 0
    while True:
        msg_dict = {
            'msg': msg_count
        }
        msg = json.dumps(msg_dict)
        result = client.publish(TOPIC, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print("Send `{msg}` to topic `{topic}`".format(msg=msg, topic=TOPIC))
        else:
            print("Failed to send message to topic {topic}".format(topic=TOPIC))
        msg_count += 1
        time.sleep(1)


def run():
    client = connect_mqtt()
    client.loop_start()
    time.sleep(1)
    if FLAG_CONNECTED:
        publish(client)
    else:
        client.loop_stop()


if __name__ == '__main__':
    run()

Code for subscribe to messages in python

import random

from paho.mqtt import client as mqtt_client


broker = 'p70e2b8e.en.emqx.cloud'
port = 12482
topic = " SUBCRIBE AND PUBLISH TO AN EMQX-MQTT BROKER "
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'
# username = 'IOTEDU'
# password = 'public'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    # client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    run()

Testing code for publishing and subscribing in Pycharm

Output of Published messages in Pycharm

Compile the code of publishing messages in pycharm, we will see that the client connects and publishes messages successfully.

output

Output of Subscribing to messages in Pycharm

Compile the code of subscribing messages in pycharm, we will see that the client connects successfully and receives the published messages successfully

output

However, we can see the connected clients in EMQX Dashboard.

connection to cloud

Summary of our article

Finally, we’ve completed the use of the paho-mqtt client to connect to the free public MQTT broker, as well as implemented the connect, publish messages and subscribe to messages between the test client and the MQTT broker.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to use a GSM/GPRS Module as an IoT device?

How to use a GSM/GPRS Module as an IoT device?

The convergence of physical objects and the digital world is known as IoT. IoT stands for the Internet of Things. It has been a trending field in the world of technology. In addition, the IoT describes the network of physical objects known as “things” that are...

Longwave Wireless Communication

Longwave Wireless Communication

Longwave wireless communication acts as a foundation for a Low power Wide Area Network. Mostly low energy is consumed in these types of networks. The reason is that most sensors are used for extracting data. These data are used for transmitting in long-range...

Architecture of a Bluetooth IoT Application

Architecture of a Bluetooth IoT Application

What is Bluetooth? To understand the architecture of Bluetooth first lets understand what actually Bluetooth is. Bluetooth is a radio-wave technology that is mainly designed to enable wireless communications over short distances. The frequency of these waves ranges...

Most Commonly Used Web Frameworks

Most Commonly Used Web Frameworks

Web Frameworks are software frameworks that are designed to help create Web apps, Web APIs and other resources. Web Frameworks help us solve two of the major hurdles of developing web apps - templates and routing. Now that we know what web frameworks are, lets get...

Communication between XBee modules

Communication between XBee modules

The wireless networking device, XBee is a user friendly, popular and is a technology worth knowing about. It can transmit and receive data wirelessly, and thus can be used for many IoT applications. As the popularity of the XBee module has grown massively, there are...

Role of WiFi in IoT

Role of WiFi in IoT

Internet of Things(IoT) applications has diverse connectivity requirements in terms of range, data throughput, energy efficiency, and device cost. WiFi is often an obvious choice in-building WiFi coverage is almost ubiquitous. It is not always an appropriate...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....