How to build an MQTT Server using Raspberry Pi

by Apr 19, 2021MQTT

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 to publish to a broker. Clients connect to this broker, which then mediates communication between the two devices. Each device can subscribe, or register, to particular topics. When another client publishes a message on a subscribed topic, the broker forwards the message to any client that has subscribed. MQTT server using Raspberry pi

MQTT(definition &etails)

MQTT is based around the idea that devices can publish or subscribe to topics. So, for example. If Device #1 has recorded the temperature from one of its sensors, it can publish a message which contains the temperature value it recorded, to a topic (e.g. “Temperature”). This message is sent to an MQTT Broker, which you can think of as a switch/router on a local area network. Once the MQTT Broker has received the message, it will send it to any devices (in this case, Device #2) which are subscribed to the same topic.

  • The MQTT Broker is the Server.
  • The MQTT Subscribers and Publishers are the Clients.

To get our Raspberry Pi to support the MQTT protocol, we will be using a server software called Mosquitto.

Mosquitto is a message broker that implements several versions of the MQTT protocol, including the latest 5.0 revision.

Installing the Mosquitto Broker on a Raspberry Pi

In this section, we will show you how to install the MQTT Server on Raspberry Pi.

Step-1:

The first step I would recommend is updating the software on your Raspberry Pi. Open up a terminal and enter the following commands:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade

Step-2:

Once you’ve done this install mosquitto and then the mosquitto-clients packages.

sudo apt-get install mosquitto -y 
sudo apt-get install mosquitto-clients -y

Step-3:

when you’ve finished installing these two packages, we need to configure the broker. The Mosquitto broker’s configuration file is located at /etc/mosquitto/mosquitto.conf, so open it with your favorite text editor. If you don’t have favourite text editor or don’t know how to use any of the command line editor, I’ll be use nano so you can follow along.

sudo nano /etc/mosquitto/mosquitto.conf

At the bottom of the file, you should see the line:

include_dir /etc/mosquitto/conf.d

Delete this Line. Add the following lines at the bottom of the file.

allow_anonymous false
password_file /etc/mosquitto/pwfile
listener 1883

By typing these lines, we’ve told mosquitto that we don’t want anyone connecting to our broker who don’t have valid username and password and we want mosquitto to listen for messages on port number 1883.

Now close (and save) that file. If you are following along with the nano example, press CTRL+X, and type Y when prompted.

Because we’ve just told mosquitto that users trying to use the MQTT broker need to be authenticated, we now need to tell mosquitto what the username and password are! So, type the following command – replacing username with the username that you would like – then enter the password you would like when prompted (Note: if, when editing the configuration file, you specified a different password_file path, replace the path below with the one you used).

Step-4:

sudo mosquitto_passwd -c /etc/mosquitto/pwfile username

As we’ve just changed the mosquitto configuration file, we should reboot the Raspberry Pi.

sudo reboot

Once the Raspberry Pi has finished rebooting, you should have a fully functioning MQTT broker! Next, we are going to try to interact with it, using a number of different devices/methods!

Step-5: Testing the broker

Once you’ve installed mosquitto on the Raspberry Pi, you can give it a quick test – Just to make sure everything is working correctly. For this purpose, there are two commands that we can use on the command line. mosquitto_pub and mosquitto_sub. In this step, I will guide you through using each of these to test our broker. In order to test the broker, you will need to open two command line windows.

Now that you have opened two windows, we can get started on the testing. In one of the two terminals, type the following command, replacing username and password with the ones you setup in the previous step.

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

The mosquitto_sub command will subscribe to a topic, and display any messages that are sent to the specified topic in the terminal window. Here, -d means debug mode, so all messages and activity will be output on the screen. -u and -P should be self-explanatory. Finally, -t is the name of the topic we want to subscribe to – in this case, “test”.

Next, in the other terminal window, we are going to try and publish a message to the “test” topic. Type the following, remembering again to change username and password:

Produce the MQTT Topic Locally

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

When you press enter, you should see your message “Hello, World!” appear in the first terminal window we used (to subscribe).

Try Out from a Different Machine

That’s all fine , but it’s not that efficient. True power of MQTT becomes apparent once you see how easy it’s to interface between different machines.

Select a Test Machine.

There are many different MQTT clients out there except for simplicity’s sake I’m getting to suggest you persist with mosquitto for testing. it’s the advantage of having the ability to run on just about everything (see The Official linked page).

Firstly we’ll learn, how to send and receive messages via your Raspberry Pi broker from another computer on the network. This is the ideal test environment because it’s real enough in that the client is a separate machine from the Raspberry Pi, and because it’s a computer rather than an embedded system it’s convenient for testing and debugging.

In my opinion, a Linux virtual machine makes an excellent test platform. you’ll spin up lots of terminals and even different VMs to really exercise your MQTT network. I used Ubuntu 20.04 running in VirtualBox very successfully.

But for now, just stir up whatever system you’ve got to perform your first test…

As we have already downloaded the mosquitto-clients which is mentioned above ,so now go further on, but if you haven’t done it before just write down the following commands in the Terminal

apt update
sudo apt install mosquitto-clients

Step-6:  Identify the Raspberry Pi on the Network

The MQTT client doesn’t need to know considerably about the broker, but it does need to know where it’s on the network. The MQTT client code needs a hostname or an IP address whenever you subscribe or publish a message.

If your Raspberry Pi features a unique name on your network, It is sensible to use that. Find the host name on the Pi by typing: the given command-

hostname 

If yours is left at the default it will return

raspberrypi

Alternatively, you can also use the Raspberry Pi’s IP address in place of the hostname. An easy way to get this is by running.

ifconfig | grep inet | grep cast

Step-7: Subscribe to the Topic Remotely MQTT server Raspberry Pi

On the test machine, there’s no need to run a server since it’s already running on the Raspberry Pi.

You can just subscribe to the test message like this.

mosquitto_sub -h raspberrypi -t "test/message"

If your Raspberry Pi’s hostname is different, substitute it in place of raspberrypi in the above command. You can also use the IP address directly if you prefer.

mosquitto_sub -h 10.0.2.15 -t "test/message"

This will now cause the terminal to wait for messages from the broker on the topic test/message.

Publish a Test Message Remotely:

As before, you can now open another terminal window and type.

mosquitto_pub -h raspberrypi -t "test/message" -m "Hello from remote"

Again, substitute your hostname or IP address as appropriate.

Now you should a message see in the first terminal window.

Hello from remote

If you still have the subscription terminal, open it up from above and you will see the message is also appear there.

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

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

Setting up a private Mosca MQTT broker using Node.js

Setting up a private Mosca MQTT broker using Node.js

In this tutorial, we are going to learn all about setting up a private Mosca MQTT broker using Node.js. But before we get into it let us brush up what we know about MQTT protocol. MQTT stands for Message Queuing Telemetry Transport. It works on the pub sub-model. The...

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