Mosquitto MQTT Broker on Raspberry Pi

by Jun 13, 2020MQTT, Raspberry Pi

This tutorial will show you what is Mosquitto MQTT Broker and how to install it on Raspberry Pi.

Contents

What is MQTT?

MQTT stands for Message Queuing Telemetry Transport. It is a simple and lightweight protocol that works on the publish-subscribe principle. and transports messages between devices. It is based on TCP/IP, however, any network protocol that provides bi-directional, lossless, and ordered connections can support MQTT. This protocol is highly useful when the network bandwidth is limited or when low-power sensors are used.

To understand the publish/subscribe or the “pub/sub” principle better, let us take an example of a news website or app. The website acts as the “broker”, meaning that it it contains information about various “topics”, in this case, news articles. A client can subscribe to specific topics and will get information when anything related to the subscribed topics is “published”. The news agencies,in this case, will be the publishers. MQTT does not provide any hierarchy between publishers and subscribers. A client can both be a publisher and a subscriber. The publishers and subscribers use messages to communicate with one another. Every message is routed through the broker.

For this tutorial, we shall use the Mosquitto MQTT broker.

Using local MQTT broker for cloud and interprocess communication ...

Installing Mosquitto MQTT on Raspberry Pi

First update the operating system on your Raspberry Pi:

sudo apt-get update
sudo apt-get upgrade
sudo reboot

Now, open a terminal and type the following command:

sudo apt install -y mosquitto mosquitto-clients

You can test your installation using the following command:

mosquitto -v

This will return the version of Mosquitto MQTT installed on your Raspberry Pi.

For the rest of this tutorial, you shall need the IP address of your Raspberry Pi. Type the following command and note down the IP address:

hostname -I

Creating an MQTT Broker on Raspberry Pi

The easiest way to understand this protocol is to create a broker on Raspberry Pi and use it to publish and subscribe to topics. Mosquitto MQTT provides a layer of security that authorizes only specific clients to publish or subscribe to topics. For this, we need to set up a username and password. This step is optional, however, it is recommended to use it in all your projects.

Type the following command:

sudo nano /etc/mosquitto/mosquitto.conf

The last line in the file will be:

include_dir /etc/mosquitto/conf.d

Remove this line and add the following lines at the end of the file:

allow_anonymous false
password_file /etc/mosquitto/pwfile
listener 1883

The above three lines will tell the broker, listening on port 1883, to prevent any communications from devices that do not have a valid username and password.

The above step is optional. Hence, to proceed without adding a username and password, remove the first two lines and directly go to the rebooting part. 
sudo mosquitto_passwd -c /etc/mosquitto/pwfile username

Type the above command in a terminal window. Replace “username” with your username. You will be prompted to enter a password. Type a password and press Enter.

Finally, reboot the Pi for the changes to take effect.

sudo reboot

Subscribe to a Topic

Open a terminal and type the following command:

mosquitto_sub -d -u username -P password -t Test

In the command, replace username and password with the username and password you created before. In case that step was skipped, just type the following command:

mosquitto_sub -d -t Test

We have successfully subscribed to our Test topic. Now we have to publish a message to this topic.

Publish a message to a Topic

To publish a message to a topic, type the following command:

mosquitto_pub -d -u username -P password -t Test -m "Hello, World!"

Replace username and password with you username and password. In case that step was skipped, simply type the following command:

mosquitto_pub -d -t Test -m "Hello, World!"
Publish Window
Subscribe Window

Once the above message was published, the message is received by the subscriber as can be seen in the above image.

Congratulations, we have created a MQTT broker on Raspberry Pi and published/subscribed a topic.

Sample Project

Taking our knowledge further, let us use a NodeMCU device that publishes the reading from a LDR to Raspberry Pi.

Components Required

  • Raspberry Pi (I have used a Model 4 B)
  • NodeMCU 1.0 (ESP-12E Module)
  • 1x LDR (Light Dependent Resistor)
  • 1x 10K resistor
  • Jumper Wires

Background

Check out our earlier post on NodeMCU here. We need to install the PubSubClient library. Download the zip file of the library from here. To set up NodeMCU with the Arduino IDE and install the downloaded library, check out my earlier post.

We are going to connect an LDR to the NodeMCU. The NodeMCU will publish the sensor reading to our Raspberry Pi broker. The Username and Password created above will be used in this project as well. We shall then subscribe to the topic using Raspberry Pi and hence, will be able to see the sensor reading.

Circuit Diagram

how_to_install_Mosquitto_MQTT_Broker_PL_MP_image5.png
Circuit Diagram

Once the circuit is rigged up, we can proceed to the code.

NodeMCU Code

Open an Arduino IDE and create a new file. Paste the following code:

#include <ESP8266WiFi.h> 
#include <PubSubClient.h> 


// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "YOUR_SSID"; // enter your WiFi SSID
const char* wifi_password = "YOUR_PASSWORD"; // enter your WiFi password

// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "Raspberry Pi IP Adress";
const char* mqtt_topic = "MQTT_Tutorial"; //any topic name of your choice
const char* mqtt_username = ""; //type your mosquitto mqtt username
const char* mqtt_password = ""; //type your mosquitto mqtt password
// The client id identifies the NodeMCU
const char* clientID = "ID"; // any name that identifies the client


// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

int photo=A0; //analog pin of the NodeMCU
void setup() {
 
  pinMode(photo, INPUT);
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);
  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Debugging - Output the IP Address of the NodeMCU
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

   client.setServer("Raspberry Pi IP Address", 1883); // type your Raspberyry Pi IP address
  // Connect to MQTT Broker
  // client.connect returns a boolean value to let us know if the connection was successful.
  // If the connection is failing, make sure you are using the correct MQTT Username and Password
  if (client.connect(clientID, mqtt_username, mqtt_password)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }
}

void loop() {
      
    int  val=analogRead(photo)/4;
    char buf [4];
    sprintf (buf, "%03i", val);
    unsigned int p=4;
    client.connect(clientID, mqtt_username, mqtt_password); //connects to the broker
    //delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
    client.publish(mqtt_topic,(const uint8_t*)buf,4);
    delay(500); //delay between each message
}

Appropriate comments have been included in the code itself. After entering all the required credentials in the spaces shown in the code, compile, and run the code. You should see the following output in the Serial Monitor:

Raspberry Pi Broker/Subscriber

Now it is time to subscribe to the topic using Raspberry Pi. Keep the publish code on the NodeMCU running. Open a terminal on the Raspberry Pi and type the following comand:

 mosquitto_sub -d -u username -P password -t MQTT_Tutorial

Replace username and password with the ones created earlier in the tutorial.

You should see the sensor value in the terminal.

Terminal Output

The above tutorial shows how we can use NodeMCU to publish sensor values to a particular topic. We use Raspberry Pi as both broker and subscriber to the topic in which the sensor values are published.

Further Scope

MQTT is a simple protocol and can be used for a variety of low power sensors. We can build a simple home automation system using Mosquitto MQTT, NodeMCU, a few sensors, and Raspberry Pi as the broker. Using this system, we can monitor sensor values around the house such as temperature, humidity, ambient light (LDR), and many others. If you don’t have a NodeMCU, check out my previous post on building a home automation system using Raspberry Pi and Flask.

Thank you for checking out this tutorial and stay tuned for many more such tutorials.

Happy learning!

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