Introduction To The MQTT Protocol

by Jun 11, 2019MQTT

What is an MQTT?

The MQTT (MQ Telemetry Transport or previously known as the Message Queuing Telemetry Transport) is a light weight publish/subscribe protocol designed for M2M (Machine to Machine) telemetry in low bandwidth environments.

Initially MQTT was designed by IBM and Arcon in 1999 for Oil Pipeline Telemetry Systems over the satellites. Nowadays MQTT is one of the main messaging protocols of the Internet of Things.

MQTT is suitable for the transport of telemetry data ie., data from the sensors and actuators.

MQTT vs HTTP

HTTP is the most popular used messaging protocol but in recent years, HTTP has been slowly replaced by MQTT by the IoT developers. The reason is that MQTT is data-centric whereas HTTP is document centric. HTTP is a request-response protocol for client-server computing and does not go along with mobile devices.

Besides, in comparison to HTTP, MQTT Protocol ensures high delivery guarantees. There are 3 levels of Quality of Services:

– at most once: guarantees a best effort delivery.

– at least once: guaranteed that a message will be delivered at least once. But the message can also be delivered more than once.

– exactly once: guarantees that each message is received only once by the counterpart

MQTT is designed for TCP/IP networks. MQTT-SN which was specified in around 2013, and designed to work over UDP, ZigBee, and other transports.

Example of MQTT publish/subscribe
Source:Wiki

MQTT Client

You need to assign addresses to the client you like to work with the messaging systems. For MQTTv3.1.1 there is client software available in almost all programming languages and for the main operating systems Linux, Windows, Mac from the Eclipse Paho project. Here is a link to the client comparison chart and download page.

MQTT Publish/Subscribe

In a publish/subscribe scheme, the client publisher publishes the data to the client subscriber which has subscribed to the publisher under a topic. For example, a client subscriber receives the data (sensor data) from the client publisher which contains the sensor data.

MQTT Protocol

MQTT Broker

The MQTT broker is the heart of the publish/subscribe protocol. It acts as the hub for the protocol as it handles up to thousands of connected MQTT clients. The responsibility of the broker is to authenticate and authorize the client. It receives all the messages and filters them and sends the message to the corresponding subscriber. The broker also consists of session details and missed messages.

MQTT Connection

The MQTT client always connects and communicates with the broker. It is based on TCP/IP and both the client and the broker need to have this stack.

TCP/IP stack
Source: HiveMQ

Basically, the client connects with the broker and communicates, so the client never connects with another client directly. To start the communication, the client sends a signal to the broker and the broker responds by sending the receiver signal.

Example Code for an IoT project

Let us take an example of NodeMCU and a piezoelectric sensor. The real-time sensor data is viewed using Adafruit.io by MQTT connection establishment.

  
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define WLAN_SSID       "xxxxx"
#define WLAN_PASS       "xxxxxxxxx"
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                  
#define AIO_USERNAME    "xxxxxxxx"
#define AIO_KEY         "5xxxxxxx"

int ledpin=D1;
int sensor =A0;
int analogvalue=0; // Current reading for analog pin
int threshold= 20; 

int led= LOW;

WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// i am going to publish my data alone. no need of subscription, so feed is enough

// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish Piezo_voltage = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Piezo_voltage");
Adafruit_MQTT_Publish  piezo_graph= Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/piezo_graph");


/*************************** Sketch Code ************************************/
void setup() 
{
  Serial.begin(9600);
  
  pinMode (ledpin, OUTPUT);

  // Connect to WiFi access point.
  Serial.print("\n\n\nConnecting to ");
  Serial.println(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
 
  
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(">>");
    delay(5000);
  }
  Serial.println("WiFi connected");
  //Serial.println("IP address: "); Serial.println(WiFi.localIP());

}

void loop()
{
   MQTT_connect();
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
analogvalue = analogRead(sensor);



if (analogvalue>=threshold)
{
  led=!led;
digitalWrite (ledpin, led);
float piezovoltage = analogvalue *(3.3 / 1024.0);
Serial.println(piezovoltage);


 
  // Now we can publish stuff
  Serial.print(F("\nSending piezo val "));
  Serial.print(piezovoltage);
  Serial.print("...");
  if (! Piezo_voltage.publish(piezovoltage++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
  }
  if (! piezo_graph.publish(piezovoltage++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
    delay (3000);
  }
}
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect()

{
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected())
  {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(3000);  // wait 3 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}
Adafruit IO

The above code is compiled in Arduino IDE since NodeMCU is used here. The analog sensor detects the vibration and provides real-time data in Adafruit.io. In this project, the data is published from the client side, there is no necessity for the subscription. The information such as Authentication code, username, password, port number, and server port are needed. The real-time data is displayed in the form of graphs, text, slide and so on.

Useful Links: https://www.hivemq.com/blog/mqtt-essentials-part-3-client-broker-connection-establishment/

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 MQTTBox to debug MQTT messages?

How to use MQTTBox to debug MQTT messages?

MQTTBox is a versatile MQTT (Message Queuing Telemetry Transport) client tool that facilitates testing and debugging of MQTT-based applications. MQTT is a lightweight messaging protocol commonly used in IoT (Internet of Things) and other scenarios where low-bandwidth,...

How to enable Mosquitto MQTT over WebSocket on Windows

How to enable Mosquitto MQTT over WebSocket on Windows

WebSocket is one of the communication protocols which provides full duplex communication over a single TCP/IP connection. It uses HTTP as a intial connection establishment. The WebSocket enables the communication from the web browser (client) to the server, in which...

MQTT Mosquitto Broker on Windows via Windows PowerShell

MQTT Mosquitto Broker on Windows via Windows PowerShell

Eclipse Mosquitto is an open-source message broker (EPL/EDL licensed) that supports MQTT versions 5.0, 3.1.1, and 3.1. The MQTT protocol uses a publish/subscribe method to deliver a lightweight messaging method. This makes it outstanding for Internet of Things (IoT)...

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

With IoT becoming a leading name in the market, businesses are keen to import it in their strategy. Due to the increasing demand, many people seek to learn the use of Mosquitto MQTT broker Linux to pump up their IoT productivity. Eclipse Mosquitto is an open-source...

How to build an MQTT Server using Raspberry Pi

installing-and-testing-MQTT-on-Raspberry_Pi What is MQTT ? MQTT stands for Message Queuing Telemetry Transport and is a network messaging protocol commonly used for messaging between IoT devices. MQTT is a publish/subscribe protocol that allows edge-of-network devices...

CoAP and MQTT: Analyzing the Best IoT Protocol

CoAP and MQTT: Analyzing the Best IoT Protocol

INTRODUCTION TO CoAP and MQTT CoAP and MQTT are two of the most important and most used IoT protocols nowadays. Both are equally important in machine communication. CoAP is a considerable competitor for MQTT because of the similarities in their use. Yet both have...

Mosquitto MQTT Broker introduction

Mosquitto MQTT Broker introduction

In this tutorial, we will discuss about the intro of Mosquittto MQTT broker. MQTT Broker is responsible for receiving network connections from the client and handling the client’s requests of Subscribe/Unsubscribe and Publish, as well as forwarding the messages...

How to Install the Mosquitto MQTT Broker on Windows?

How to Install the Mosquitto MQTT Broker on Windows?

The Mosquitto or MQTT broker is an OASIS standard messaging protocol for IoT. The inculcation of IoT in modern-day lives has pulled MQTT in the picture. Being a lightweight messaging transport that can remotely connect devices, MQTT tutorials were in much demand. So,...

How to choose an MQTT broker for an IoT project?

How to choose an MQTT broker for an IoT project?

What is MQTT Broker? MQTT stands for Message Queuing Telemetry Transport is an open OASIS and ISO standard lightweight, a publish-subscribe network protocol that transports messages between devices. Basically, MQTT Broker is simply software running on the computer. It...

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....