Understanding MQTT Protocol Packet Format

Understanding MQTT Protocol Packet Format

MQTT protocol communicates by exchanging a series of predefined MQTT control packets. The MQTT packets consist of up to three parts in the following order as a 2-byte fixed header that appears in all MQTT packets, Variable Headers, and Payload that appear in some MQTT packets. This document describes how to format an MQTT Message or Packet.

MQTT client to MQTT protocol

MQTT Protocol Packet Types

Types of MQTT Protocol Control Packets are:

  • CONNECT – Fixed Header / Variable Header / Payload – MQTT Client requests a connection to a Broker.
  • CONNACK – Fixed Header – Acknowledge connection request.
  • PUBLISH – Fixed Header / Variable Header – Publish message.
  • SUBACK – Fixed Header / Variable Header / Payload – Subscribe acknowledgement.
  • UNSUBSCRIBE – Fixed Header / Variable Header / Payload – Unsubscribe from a topic.
  • UNSUBACK – Fixed Header / Variable Header / Payload – Unsubscribe acknowledgement.
  • DISCONNECT – Fixed Header – Disconnect notification.
  • PUBREL – Fixed Header / Variable Header – Publish release(QoS 2 publish received).
  • PUBACK – Fixed Header / Variable Header – Publish acknowledgement.
  • PUBREC – Fixed Header / Variable Header – Publish received(QoS 2 publish received).
  • PUBCOMP – Fixed Header / Variable Header – Publish complete.
  • SUBSCRIBE – Fixed Header / Variable Header / Payload – Subscribes to a topic.
  • PINGREQ – Fixed Header – PING request.

MQTT Packet Sizes

The fixed header field consists of the control field, and the variable header contains the packet length field. The minimum size of a packet length field is 1 byte, which is for messages less than 127 bytes.

The maximum packet size is 256 MB. The minimum packet size is only 2 bytes with a single control field and a single packet length field. Smaller packets less than 127 bytes have a 1-byte packet length field. The Packets greater than 127 and less than 16383 use 2 bytes, and so on. 7-bits are used with the 8th bit is the continuation bit.

MQTT Packet size

Control Field

The 8-bit control field is the principal byte of the 2-byte fixed header. It is divided into two 4 bit fields and contains all protocol commands and responses. The first four most important bits are the command or message type field, while the remaining 4 bits are used as control flags.

control field structure

Control Flags

While there are 16 possible flags, a limited is used. The Publish message makes the most use of these flags. The duplicate flag is used when a message is republished with QoS or 1 or 2. QoS flags are used when publishing to indicate a QoS level of -0,1,2. The Retain Message flag is also used when publishing a message.

Remaining Length

The Remaining Length is the number of bytes left in the current packet, including variable header and payload data. The Remaining length does exclude the bytes used to encode the Remaining Length.

The Remaining Length is encoded using a variable-length encoding scheme that uses one byte for values up to 127. The least seven important bits of each byte encodes the data, and the most important bit is used to indicate there are following bytes in the representation. Thus, each byte encodes 128 values and one “continuation bit”. The greatest number of bytes in the remaining length field is four.

Size of the remaining length field

Variable Header

Some types of MQTT control packets have a variable header component. Variable-length header fields are not always present in MQTT messages. Some MQTT message types or commands require this field to carry additional control information. It remains between the Fixed Header and the Payload. The Variable Header will vary depending on the packet type.

Example: MQTT Connect Message Structure

As an example, let’s take a look at the details of the CONNECT message packet in the Bevywise MQTTRoute / MQTTBroker.

After establishing a connection between the MQTT client and the broker, the first packet must be a CONNECT packet. The CONNECT packet only needs to be sent once over the network connection. The second CONNECT packet sent by the MQTT client is ignored and disconnected.

Fixed Header

Fixed header

Variable Header

The variable header must have four parts. They are the protocol name bytes, protocol level, connect flags, and keepalive.

Protocol name bytes

MQTTRoute will disable false protocol name.

Protocol name bytes

Protocol level

The protocol level for MQTTRoute is 4, other values lead to disconnection.

Protocol level

Connect flags

This field indicates the presence or absence of data in the payload.

Connect flags

Keep Alive

The MQTT client should send control packets that do not exceed the value of the defined Keep Alive. The Keep Alive value depends on the duration of the control packet of one transmission by the client.

Keep alive

MQTT Protocol Payload

The payload contains the MQTT client credentials (username, password, etc.). The client ID must be unique for each client. The broker responds with a unique client ID for each client. If you send a client ID in an empty field, the client will be rejected. The following fields must be filled in the following order: Client ID, Will Topic, Will message, username, password.

The above fields must be in string format. Any packet that does not send a CONNECT packet after a reasonable amount of time will be rejected by the broker. After successful above validation, the broker will respond in 2 format

  • Check if the client already exists. If so, the broker will respond with the disconnection.
  • The MQTT Broker will send a CONNACK packet with zero value.

After successful CONNACK, the broker will do a keepalive monitoring regularly.

To know more about the MQTT messages or packets structure, do visit the MQTT Developers page.

To know about the format of the MQTT-SN packets, visit the MQTT-SN Developers page.

Download the free version of the MQTTRoute now to validate all the features.

You can upgrade to the premium version of MQTTRoute for the full-fledged functionalities after your free trial period.

Fight Industrial Data Security Breaks with Secure Enterprise MQTT Broker

Fight Industrial Data Security Breaks with Secure Enterprise MQTT Broker

We all know that our world is more connected. Billions of intelligent tools and machines are generating enormous amounts of data, which creates enormous potential for businesses and other organizations to optimize their operations and achieve efficiency. As IoT devices continue to evolve, every newly connected product is vulnerable to hackers, and security turns into a significant concern. Fighting the industrial data security breaks is a 100% mandate to protect critical data in any place it dwells. Bevywise MQTTRoute provides an option to enable encrypted data transmission for better MQTT data security. It works with all standard SSL / TLS certificates and runs with a self-signed certificate. This article provides complete guidance on securing the delicate data that you transfer over the Enterprise MQTT Broker.

MQTT Broker Security Fundamentals

With regards to security in Enterprise MQTT Broker, there are some fundamental concepts to take into account they are identity, authentication, authorization, and encryption. In this tutorial, we take a gander at how you can confine access to a broker, and protect your data using different security systems.

Identity

Every client has a unique Client ID. The Enterprise MQTT broker indicates that the client must report the client ID when requesting a connection. When the broker receives a connect command from the client, it determines whether to allow the client to connect only if the received message contains a legitimate client ID, user name, and password. The client can use UUID, mac address of the network device, or other unique client information as the client ID.

Authentication With X.509

This is the safest method for client authentication. In addition to authentication with username and password, the MQTT broker allows a device to authenticate with an X.509 certificate. This certificate provides authentication at the transport level. X.509 uses a public key infrastructure to verify that a public key belongs to a client. In the X.509, a certificate authority is introduced to verify the identity of a client. During the handshake process, the client presents the broker with its certificate, which contains information such as identity and public key. Then the broker relays this certificate to the certificate authority for verification. After verifying the client certificate, the broker ensures it is genuine or not and gain trust in the binding with the client name and public key.

Client Authentication

There are three ways to verify the identity of the MQTT client on Bevywise MQTT broker : the Client IDs, Usernames and Passwords, and the Client Certificates.

Client ids

All MQTT clients must provide a client id. When a client subscribes to a topic the client id links the topic to the client and the TCP connection. With constant connections, the broker remembers client IDs and subscribed topics. When configuring the MQTT client you need to relegate the Name / ID to the client. However the Bevywise MQTT Broker allows you to impose client id prefix restrictions on the client name, and this provides some basic client security. You will find this setting in the security settings section of the broker.conf file.

########### prefix for Random Clientid Generation ###########
[MQTT]
CLIENTID_PREFIX = Bevywise-

Username and Password

An Enterprise MQTT broker can request a valid username and password from a client before allowing a connection. The username and password combination is transmitted in plain text and is not secure without some form of transport encryption. However, it does provide an easy way of restricting access to a broker and is probably the most common form of identification used. The username used for authentication can also be used in restricting access to topics. On the Bevywise MQTT broker, you need to configure settings for this to work. Again you will find these settings in the security section of the broker.conf file. The devices can connect using MQTT Username / Password or you can connect it without the username and password. You have to change NO to YES if you are planning to use Authentication.

################ Device Authentication #################
[AUTHENTICATION]
AUTHENTICATION_ENABLED = YES
# YES || NO

To create the passwords you will need to use the utility that comes with the broker. You can add the Username and passwords on the UI under the Security tab for secure client connections.

Authorization

Authorization is managing the clients’ rights. The most common types of authorization used are Role-Based Access Controls (RBAC) and Access Control List (ACL). RBAC provides a level of abstraction between the client and the main resources. It facilitates the administration of security in a large organization. This allows the broker to authorize the clients published or subscribed topic. ACL associates certain clients with a list of permissions that includes who can access the resources and which operations are allowed. ACL provides policies on what topics a client can subscribe / publish. Using ACL or RBAC, the broker implements topic permissions to restrict a client from publish / subscribe to unauthorized topics. Each topic permission allows the broker to specify authorization for clients and limit them to subscribe and publish messages. If a client attempts to perform an unauthorized operation, the broker can perform actions such as disconnect the client by preventing it from publishing data to other clients.

Authorization with Access Tokens

Another approach to providing authorization is a token authorization. Token authorization permits a client to request the scope or privileges that the client has. To connect to the broker with an access token, the client must use the password field to send the access token with the connect message. The client must be given an access token before requesting a connection. There are a variety of token services available. The most commonly used are OAuth and OAuth 2.0.

OAuth

It is a token-based authentication that is used to provide SSO and permits information to be utilized by third party services. It likewise requires an identity provider for authenticating clients’ access.

OAuth 2.0

It authorizes third-party applications to access the client account and authenticates the client by following the authorization code flow.

Securing Data

There are numerous possibilities to hack the data transfer between Clients and Broker. To protect the contents of your MQTT messages, you can use TLS or SSL Security and Payload encryption. Enterprise MQTT Broker eliminates “Man in Middle attack” by enabling data transfer through TLS port.

TLS / SSL Security

TLS / SSL security is a more commonly known security used on the web. This security is part of the TCP / IP protocol. TLS provides a secure communication channel between the client and the server. TLS certificate is provided for both server and client, and those certificates will be verified and authenticated by Certificate Authority before connection. The broker will connect only if the Certificate and host IP match.

Communication between clients and the server must be ensured by enabling TLS mode and setting passwords for the connection. You can use a single password for all clients or individual passwords for each client. Open conf/ folder on broker.conf and update TLS_ENABLED to TRUE . All other values can be changed if necessary. Using a non-regular port number for Broker and a secure web socket will further enhance security against DDOS.

#########MQTT BROKER CONFIG#######
[CONFIG]
PORT_NO = 8883
WS_PORT_NO = 10443
TLS_ENABLED = TRUE
# TLS_PORT must be 88xx.
TLS_PORT_NO = 8883
WSS_PORT_NO = 11443

Payload Encryption

This is done at the application level and not by the broker. You can encrypt data without configuring the broker. It likewise implies that data is eventually encrypted and not just between the broker and the client. However, this type of encryption doesn’t protect passwords on the connection itself. Because it doesn’t involve any broker configuration or support this is likely to be a very popular method of protecting data.

WILL and Retained message

Last WILL, will help the subscribers to know when the publishing device has gone down or got disconnected from the broker. Retain tag tells the broker to keep the last published message for the new subscribers to know the last published messages while connecting for the first time. Besides, the Enterprise MQTT Broker provides both these messages as needed for the realtime.

DataBase Storage

The broker will store the data into the database for further analysis and decision making. The default DB supported is SQLite. But the DB Configuration can be modified to make it work with MySQL or any other Big Data engine. Please refer to the help document to set up MySQL, its dependency packages, and other big data engines.

Intuitive User Interface

Through a web-based primitive User Interface broker, you can view the active devices and recent activities of different devices. It also helps to view the activities and messages sent from and to specific devices.

mqtt-dashboard

Get your free version of MQTT Broker now for secure data transfer.

download now

The product page and the help documentation will provide more information on configuring and running the Broker securely. For more queries, feel free to contact us at [email protected].

Build a Fleet Management System with Ease

Build a Fleet Management System with Ease

IoT technology is used to make the transportation and logistics industry increasingly effective and solid. Fleet management systems play an important role in the transportation system. Here we have depicted the Bevywise MQTTRoute which gives the technology required to track associated fleets. Bevywise MQTTRoute is a profoundly extendable, adaptable, and versatile MQTT Broker utilized for gathering information from IoT edge devices in which it is easy to transfer data to and from associated vehicles in a dependable and quick way. This documentation provides developers with a comprehensive guide to using this IoT application framework to track associated fleets.

MQTT Implementation

Fleet management is now made simple with IoT. It offers a high return on investment, improved fleet optimization, operator safety, and reduced fuel costs. Nevertheless, it faces some challenges in managing fleets. One of the biggest challenges is bidirectional messaging and real-time connectivity resulting in loss of connection and significant network latency. Bevywise MQTTRoute facilitates the reliable and fast transfer of data to and from connected vehicles.

The MQTT Route Fleet Management System enables you to maintain a continuous connection between the vehicle and the cloud, ensures reliable data transfer between vehicles and the cloud, setting up a secure TLS / SSL connection, deploy MQTTBroker and run it in a private or public cloud and integrate messaging data with other existing business systems.

The factors that affect fleet optimization are:

  • Live Tracking and Notifications
  • Outing History
  • Fleet Safety and Security
  • Charts and Reports
  • Fuel Management
  • Admin Console

Live Tracking and Notifications

The intuitive dashboard exhibits real-time information from vehicle sensors and gathers it using MQTT to create notifications. The collected data is stored on the MySql. For powerful visualization and analysis of data, you can use Advanced data storage for custom usage to store your data in Elastic Search or other data engines. Coordinate your ML Algorithm into the Python assembled MQTT Broker and get your data ready for decisions. Direct the incoming real-time events and guide it to your ML engine utilizing the scheduler module to make custom alerts and notifications.

Map
Fuel Consumption

Outing History

You can create historical graphs and charts, to preview and download any vehicle’s historical data for a specific date range. You can also check the details of any previous trip, including distance, fuel mileage, and driving conduct during the excursion. The history graph provides a comparative report of payloads issued on two different days, months, or years. You can also download the graph as a PDF.

Outing History
Driving Behaviour

Fleet Safety and Security

Control hasty driving behavior, such as excessive speed, sudden acceleration, and braking. The IoT platform and Mobile SDK are tightly integrated with the firebase cloud messaging system, which sets burglar alarms on the phone to let you know if the vehicle is driven without permission. The web platform is also integrated with the WebSocket-based notification engine for notifications in the web user interface. Real-time driving behavior dashboards and charts let you understand the intensity of hasty driving and take the appropriate action.

Safer Drive
Safety score history
 

Charts and Reports

Consequently get reports of distance, driving time, fuel expended, and other indispensable data to lessen manual slip-ups and improve consistency. Get definite vehicle use, fuel, driver execution, and other downloadable reports of your fleet to improve assets and increase productivity. The report tab in MQTTRoute has build-in visualization, in which the users can visualize the data in a chart or graph. The reports can also get downloaded in which it is stored in the big data engine in the back-end and automatically converted to PDF.

Distance
Alerts

Fuel Management

The fleet costs can be reduced by observing fuel utilization and inefficient driving conduct. The intuitive dashboard gives you the permeability of all viewpoints including fleet usage, driving conduct, fuel utilization patterns.

The developers can create widgets for measuring fleet usage, driving conduct, fuel utilization patterns. All widgets created by the developer are placed on the interactive dashboard which gives you the permeability of all viewpoints. The following code snippet is used to build a custom URL inside custom_ui_server.py.

def custom_urls():
urllist={
“AUTHENTICATION”:’DISABLE’,
“urls”:[{“/extend/Dashboard”:dashboard}]
}
return urllist

Fuel Consumption
Fuel Mileage
 

Admin Console

Manage multiple users on the platform with appropriate privileged access through the Admin console. Admin console has an elegant Dashboard that gives brief details about the organizations to manage drivers and assign them to specific vehicles. Bevywise MQTTRoute provides an API for integrating relevant data into internal enterprise applications. This allows the server infrastructure to provide the opportunity to consolidate, collect, store, and test various vehicle information and the impact of test results with clients and end users.

Fleet Management Dashboard

Download MQTT Broker now and start building your application today.

Configuring end-to-end IoT environment on Raspberry Pi

Configuring end-to-end IoT environment on Raspberry Pi

Over the past few years, MQTT has begun to establish itself as the most commonly used messaging protocol for IoT projects. This document provides developers with a complete guide on how to set up and run an MQTT Broker on Raspberry Pi in just a few minutes. You will also see how easily you can add intelligence to your Edge device using ESP8266. Once you have gained the knowledge of the MQTT Broker and how to use it, you will be able to make your own IoT projects.

Overview:

The steps involved in setting up a MQTT Broker on Raspberry Pi are

  1. Installing MQTT Broker on Raspberry Pi
  2. Configuration of MQTTBroker
  3. Setting up the ESP8266
  4. Flashing ESP8266
  5. Connecting ESP8266 with MQTT Server
  6. MQTTRoute User Interface

MQTT

MQTT is a lightweight messaging protocol that allows you to send arbitrary messages across a network to any interested device. It uses the publish/subscribe method to exchange data among clients and the server.

 

Installing MQTT Broker on Raspberry Pi

We are going to use Bevywise MQTT Broker and the Raspberry Pi 3 running the latest version of Raspbian Jessie in this tutorial.

To install the Bevywise MQTT Broker and its client packages follow the below steps

    • You can download the broker from

download now

    • In the download form, provide all your required details, choose the Raspberry OS, and download the MQTT Broker.
    • The downloaded file will be in a zip format.
    • Unzip the downloaded zip folder using the command
    • unzip Bevywise_MQTT_Route_Raspbian.zip
    • Once you unzip the file, the Bevywise folder will be created.

Configuration of MQTTBroker on Raspberry Pi

  • To configure the broker go the Downloads -> Bevywise -> MQTTRoute -> Conf folder.
  • In the conf folder, there will be two conf files.

1. broker.conf

2. data_store.conf

broker.conf

    • To configure the MQTTRoute, use the broker.conf file inside the conf folder of the Bevywise package.
    • By default, the broker will run in non-TLS mode with the port number 1883, and the authentication is disabled.
    • MQTTRoute provides an option to enable encrypted data transfer and authentication.
    • To run your product with SSL/TLS support, change TLS_ENABLED = TRUE and change the port number to 8883 .
    • You can also connect your edge devices more securely with MQTT authentication .
    • To enable the authentication change AUTHENTICATION_ENABLED = YES.
    • By enabling this, you need to provide an MQTT username and password when the edge device is connected.
    • The username and the password are available in the Broker User interface.
    • Once you run the broker, the user interface will appear.
    • In the User Interface below the “Authentication” tab, there will be a username and password.
    • You can use that username and password for a secure device connection.

 

 

broker-conf

 

 

data_store.conf

    • SQLite is the default data storage in MQTTRoute.
    • For storing a large amount of data, you can change the storage configuration to MySQL or MSSQL.
    • For powerful visualization and analysis of data, you can store the data in Elastic Search or any other Big Data engine using a custom implementation.
    • These options configured using the data_store.conf file inside the conf folder.
    • To use MySQL as your data storage change, DB_SERVER= MySQL.
    • And provide the required username and password for MySQL.
    • Now the data will be stored inside the data folder in the name of the file specified for MYSQL_DB.

 

 

data-store-conf

 

 

    • After the broker configuration, now you can start the MQTT Broker.
    • To run the MQTTBroker as service, use the Monit version 5.25.

The procedure to set up the monit:

    • Download the Monit for Raspberry Pi 3, based on your servers.
    • Extract the archive using tar -xzf < downloaded file > .
    • Go to monit-5.25.2/bin.
    • Copy monit to /usr/bin folder by using the command
    • sudo cp monit /usr/bin
    • Go to monit-5.25.2/conf.
    • Using the below command copy the monitrc file to “/etc/”
    • sudo cp monitrc /etc/.

Monit configuration:

    • Modify the monit conf file.
    • Monit comes with its web server running on port 2812.
    • To configure the web interface, uncomment the section that begins with set httpd port 2812 in /etc/monitrc file.
    • Then use
    • sudo vi /etc/monitrc.
    • And, change the username and password as per your need.

Add Monitoring services:

    • At the end of the /etc/monitrc file , add the following.

Check process MQTTRoute, with pidfile Bevywise/MQTTRoute/Broker.pid.
start program = “Bevywise/MQTTRoute/bin/runbroker.sh” with timeout 2 seconds.
stop program = “Bevywise/MQTTRoute/bin/stopbroker.sh” with timeout 2 seconds.

 

    • To reload the configuration changes, run

        sudo monit reload

 

    • To add the MQTTRoute process to monitoring, use

         sudo monit start MQTTRoute

 

    • Restart the Raspberry Pi.
    • Now, the broker will start running in the background.

Setting up the ESP8266

 

The below steps explains how to flash a client library in ESP8266 by using the Arduino IDE.

 

Step 1: Connect your PC with internet

    • Connect your PC to the internet in which you are going to flash the ESP8266.
    • You can connect it using an Ethernet cable or WiFi.

Step 2: Install the Latest Arduino IDE

Step 3: Installing the ESP8266 Board

    • Once you install the Arduino software, open it.
    • Navigate to File -> Preferences -> Additional Boards Manager URLs.
    • In this text box, copy and paste the following link http://arduino.esp8266.com/stable/package_esp8266com_index.json

 

setting-up-esp8266

 

 

    • Click “ok” to save your changes.
    • Now open the Board Manager.
    • Go to Tools -> Board -> Board Manager.

 

esp8266-settings

 

    • Select the esp8266 by ESP8266 Community package and install it.

 

ESP-settings

 

 

    • Then choose your ESP8266 board from Tools -> Board -> Generic ESP8266 Module (ESP8266-01).

or

    • Tools -> Board -> NodeMCU 1.0 ESP-12 E Module (ESP8266-12 E & Development Board)
    • Finally, re-open your Arduino IDE.

Step 4: Install the Device Driver Software – CDM21226

Step 5: Download and Install the needed Libraries

    • Before programming the ESP8266, you need to install the libraries in the Arduino library manager.
    • There are quite a several Arduino-compatible MQTT clients available now.
    • One of the best-known clients is PubSubClient.
    • It works very well and is simple to use.
    • Now, download the Library from GitHub.
    • To install the PubSubClient Library, copy and paste it in Documents -> Arduino -> Library.
    • And restart Arduino IDE.

Step 6: Compile the main program

    • Once you have installed those libraries, you will be able to run the code.
    • Presently, before beginning the programming, we have to choose a couple of various alternatives.
    • In the Tools menu choice, select ESP8266 for Board, 80 MHz for the CPU Frequency, 4M for the Flash Size, and 115200 for the Upload Speed.
    • Additionally, try to choose the COM port that you are using (this will rely upon your setup).
    • Now, open the MQTT Broker user interface to download the default library of Bevywise MQTT Broker.
    • Below the MQTT Clients tab, download the client code that is compatible with your OS.
    • Once you start the Arduino, Open file -> new in Arduino IDE.
    • Copy the program in ESPMQTT_Client.
    • Paste it on a new file.
    • To compile the main program, go to ArduinoIDE Sketch -> verify/compile.

ESPMQTT_Client


ESPMQTT_Client
#include <ESP8266WiFi.h>
#include  <PubSubClient.h>
const char* ssid = “wifi name”;
const char* password = “wifi password”;
const char* mqtt_server = “localhost”;
WiFiClient espClient;
PubSubClient client(espClient);
int RECV_PIN = 5;
void reconnect()
{
while (!client.connected())
{
Serial.print(“Attempting MQTT connection…”);
if(client.connect(“ESP8266Client”))
{
Serial.println(“connected”);
client.subscribe(“ESP8266/LED”);
client.publish(“ESP8266/LED”,”on”);
}
else
{
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
delay(5000);
}
}
}
void setup()
{
pinMode(RECV_PIN,OUTPUT);
Serial.begin(115200);
digitalWrite(RECV_PIN,HIGH);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
reconnect();
}
void setup_wifi()
{
delay(10);
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
if((char)payload[0] == ‘o’ && (char)payload[1] == ‘n’)
{
digitalWrite(RECV_PIN,LOW);
}
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}

Below we have explained the code to help you understand what is going on.

Here, we have configured WIFI:

const char* ssid = “wifi name”;
const char* password = “wifi password”;

Then the MQTT Configuration:

const char* mqtt_server = “localhost”;
client.setServer(mqtt_server, 1883);

    • In the client.setServer, provide the broker port number to configure the MQTT.

Now, we have created the MQTT and WiFi stacks:

WiFiClient espClient;
PubSubClient client(espClient);

    • We have created the PubSubClient library, which we have downloaded before.

Arduino Setup Function:

void setup()
{
pinMode(RECV_PIN,OUTPUT);
Serial.begin(115200);
digitalWrite(RECV_PIN,HIGH);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
reconnect();
}

    • This is the Arduino setup function.
    • First, the LED configured, then the serial port is set up, and the WiFi configured.
    • Finally, the client sets the MQTT server address as 1883, and the callback function.

Setting up an MQTT Publish/Subscribe:

void reconnect()
{
while (!client.connected())
{
Serial.print(“Attempting MQTT connection…”);
if(client.connect(“ESP8266Client”))
{
Serial.println(“connected”);
client.subscribe(“ESP8266/LED”);
client.publish(“ESP8266/LED”,”on”);
}
else
{
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
delay(5000);
}
}
}

    • In this phase, the publish and subscribe process will occur.
    • The client.connect will attempt to establish the connection.
    • The client.publish will publish the topic “ESP8266/LED” with the value “on”.
    • If successful, the client publishes the “on” message.
    • In client.subscribe, the client will subscribe to the topic “ESP8266/LED”.
    • If a failure occurs, it will attempt to reconnect.

Flashing ESP8266

    • To flash the ESP8266, go to ArduinoIDE -> Sketch -> upload.

 

flashing-esp8266
Circuit Diagram for Flashing the program in ESP-12E

 

Connecting ESP8266 with MQTT broker on Raspberry Pi

    • Once the program uploaded, the ESP8266 will be started and connected to the MQTT Server.
    • To make sure it is connected, go to the MQTT user interface.
    • Check whether the client is connected or not.

MQTTRoute User Interface

    • Once you get connected to the MQTT Route, you can view it through the user interface.
    • Use your browser and open the User interface with the URL “http://localhost:8080”.
    • On the login page, you will see the default “Username” and “Password” as “admin”, use it to log in to the MQTT broker user interface.
    • Users can also change the username and password via the user interface.

 

MQTT Broker UI

 

    • The Dashboard of MQTTRoute will give a quick view of the connected device.
    • The individual device details can be seen by visiting the Devices tab.
    • The connection status and the messages published will be dynamically updated.

For more reference about our MQTT Broker User Interface, use the link below https://www.bevywise.com/mqtt-broker/help.html.

MQTTRoute 3.3 is now available. To know more about the features, visit the MQTT Broker page. Also, try controlling your MQTT devices with MQTT Broker app. Get it on play store.

Note : Are you the technology person looking to automate your house on a Raspbery pi box?. Here is your FREE MQTT Broker with all the widgets and dashboard needed to monitor and control your MQTT devices.