MQTT mosquito | IoT Platform Series - 7 (2023)

Things used in this project

hardware components

MQTT mosquito | IoT Platform Series - 7 (1)
Espressif ESP32 Development Board - Developer Edition

Software applications and online services

MQTT mosquito | IoT Platform Series - 7 (2)


What is MQTT?

MQTT stands for Message-Queue-Telemetry-Transport, is apublish/subscribeprotocol formachine to machineContact. This simple protocol is easy for any client to implement. is called asThe barifault,both are used for the same purpose but with different methods.

Get PCBs for your manufacturing projects

You must log outPCBWAYorder cheap pcb online!

You get 10 good quality PCBs cheaply manufactured and shipped to your door. You'll also get a discount on shipping on your first order. Upload your Gerber filesPCBWAY τor produce them with high quality and in a short delivery time. PCBWay can now offer a complete product solution, from design to case manufacturing. Take a look at Gerber's online browser feature. With reward points you can get free stuff from their gift shop.

Start of work

There are 2 sections here -Publish and register. And then there is the intermediary -Hall. let's look deeper

  • IoT devices have the function of collecting sensor data and sending it to the cloud (broker). Whilepersonal computer/server/Mobile devicesPlay the role of monitoring and receiving sensor data to display - Here,IoT devicethat's oneEditor, icomputing devicesesSubscriber.
[EXAMPLE] When auser 1post a photo on social media and then justuser 2registereduser 1can see/receive the image. Here,user 1EsEDITOR,user 2EsSUBSCRIBER, iuser accountEsMEDIATOR.
  • According to the previous analogy, the image that is published is data, that is,transfer from user 1 to user 2📤. And this is the exact scenario in the MQTT Pub/Sub model.
(Video) Getting Started with MQTT using Mosquitto | Cloud MQTT
  • We have a more secure layer 🔒 that ensures the exchange of datain a certain way, we call it that 'element', when the user1publish topic data, the subscriber receives automatically if he is already connected to the broker. Therefore, inmetroLow latency.

MQTT intermediary

Whenever the pub-sub model is used as the messaging protocol, we need a broker that can transfer the information to the requested device. This can be done by sending a message to the correct subject.

To clear things up -

  • Broker is a runtime server (continuously running service), which can have 2 types of clients:Publisher (seller)iSubscriber (client)
  • For example, when the sellersell the productthrough the broker to the buyer, then uses the broker's service to reach out and find a safe buyer.
  • Likewise, when the publisher publishes information, the data reaches the subscriber through the Broker.
  • The broker is responsible for having a specific storage space where it can wait for the data from the publisher to be cached and then sent to the subscriber.
  • In pub-sub MQTT, clients communicate with each other through an MQTT broker.
  • There are many MQTT brokers on the market. It is even possible to create your own broker or use an open source broker.relay'.
  • For the current project, we will first understand the mechanism and then monitor the test data traffic.Broker Mosquitto MQTT.

mosquito platform

Now that we understand how MQTT works, let's use the MQTT cloud service and send data over the Internet. In this article we will use Mosquitto MQTT

In the Server section we can see different ports that provide servers separated by attributes. These servers act as channels for sharing data through the cloud. Let's clear this up first -

  • MQTT broker port (zadano: 1883):This is the standard port used for MQTT communication. MQTT clients use I to connect to the Mosquitto broker and publish/subscribe to topics. It works over TCP.
  • Puerto MQTT Broker SSL/TLS (zadano: 8883):This is a secure version of the MQTT port broker. It uses SSL/TLS encryption for secure communication between MQTT clients and the Mosquitto broker. Clients connect to this port to establish a secure connection.
  • WebSocket Port (default: 9001):Mosquitto also supports MQTT over WebSockets, allowing MQTT clients to connect to the broker using the WebSocket protocol. The WebSocket port is used for WebSocket-based MQTT communication.
  • Puerto WebSocket SSL/TLS (zadano: 9443):This is a secure WebSocket port used for encrypted WebSocket-based MQTT communication. It provides a secure connection using SSL/TLS encryption.

we will use each otherin 1883Port for sending data and monitoring. As we know, MQTT has 3 services: Publisher, Broker and Subscriber. In this case, MQTT Cloud mosquito already plays the role of intermediary.

Now we would useESP32 development board, which has a wifi chip and can connect to the Internet by playingthe role of the publisherto share temperature and humidity data from sensors.

On the other hand, we will use a computer to view this data asSubscriber.This will allow us to fully understand the working principle of the MQTT protocol used in IoT communication between devices.

Editor (ESP32)

To configure ESP32 for MQTT, we need to install a library:PubSubClient. This library has functions that use the variables listed below to send data to the broker.

  • servidor_mqtt: This variable represents the address or IP of the MQTT broker. We will use ""
  • puerto_mqtt: This variable represents the port number of the MQTT broker. In our case, 1883.
  • mqtt_topic: This variable represents the topic to which the editor will send messages. For example"schoolofiot/dispositivo1".wherea collegiate' is the most general level of questioning. and 'device 1'is a sublevel.

The code provided is an Arduino sketch that uses an ESP32 WiFi module and the PubSubClient library to connect to an MQTT broker and publish temperature and humidity data. Let's break down the code step by step:

(Video) Home Assistant MQTT Install and Setup - A Beginner's Guide

1. Include the required libraries:


This code includes the libraries needed for the ESP32 WiFi module and MQTT client functionality.

2. Set the WiFi and MQTT server variables:

const char* ssid = "XXXXXXXXX";
const char* lozinka = "XXXXXXXXX";
const char* mqtt_server = "";

These variables store the SSID (network name) and password of the WiFi network you want to connect to. Heservidor_mqttThe variable contains the IP address or hostname of the MQTT broker.

3. Declare global variables and objects:

WiFiClient espClient;
PubSubClient client (special client);
last long message = 0;
message char[50];
valor int = 0;
tempura plovka = 0;
moisture plovka = 0;

Here the WiFi client object (espCliente) and the MQTT client object (the client) are declared. HeLast messageThe variable stores the timestamp of the last message imessageis a character string to store messages. Hevalor,temperature, ihumidityVariables are used to store the corresponding sensor values.

4. Installation method:

void setup() {
client.setServer(mqtt_server, 1883);

Heinstallation()the function is called once at the beginning of the program. Initializes serial communication, establishes a WiFi connection, configures the MQTT server and port, and sets up a callback function to process incoming messages.

5. WiFi configuration method:

override wifi_configuration() {

Hewifi_configuration()The feature manages the connection to a WiFi network using the provided SSID and password. Wait for the connection to be established and print the local IP address on the serial screen.

6. MQTT callback function:

void callback (char* subject, byte* message, length unsigned int) {

This function is called when a message is received from the MQTT broker. Prints the received message along with the corresponding subject.

7. MQTT reconnection method:

abort reconnect() {

Hereconnect()The function is responsible for reconnecting to the MQTT broker if the connection is lost. It tries to connect to the broker using a randomly generated client ID. If the connection is successful, a success message is printed. Otherwise, wait 5 seconds before trying again.

8. Main loop:

void loop() {
if (!client.connected()) {
time now = milliseconds();
if (now - ultimoMessages > 2000) {
lastMessage = now;
send data();

Heloops()The function is the main loop of the program that is executed continuously afterinstallation()operation mode. Checks if the MQTT client is connected, and if not, tries to connect again. also calls itclient.loop()Function to maintain the internal state of the MQTT client. Every 2 seconds, she calls him.send data()Function to publish temperature and humidity data.

9. Method of posting sensor data:

void sendData() {

Hesend data()The function is responsible for publishing temperature and humidity data for specific MQTT topics. It generates random temperature and humidity values, converts them to strings, and publishes them along with the corresponding topic.

- Send an empty message:

client.publish("schoolofiot/gap", "---------------");

This line generates a message consisting of a series of dashes (---------------) and MQTT topicsschool/vacancy". It is used to indicate a separation or gap between different data sets.

- Read and publish temperature data:

temperature = random(30, 40);
char CadenaTemporal[8];
dtostrf(temp, 1, 2, cadena temporal);
Serial.print("Temperatura: ");
String tempdata = "Temp: " + String(tempString);
client.publish("schoolofiot/temperature", tempdata.c_str());

These lines generate random temperature values ​​between 30 and 40 degrees, save them intemperaturevariable and usedtostrf()function to convert decimal data to a string.

dtostrf(floatValue, minStringWidth, numAfterDecimal, charBuf_to_store_string);
This function takes four parameters to convert a double to an ASCII value stored in an array:1. floatValue: The first parameter that takes a float value that we want to convert to a string.2. minStringWidth – This is the second parameter that sets the minimum width of the output string field.3. numAfterDecimal: The third parameter is the precision that describes the number of digits after the decimal point.4. charBuffer - The last argument is where the string will be stored. This is a type of fixed-size character array.

Then the temperature value is printed to the serial display and connected to the string "Temperature:". The resulting array is stored in theprovisional datavariable. Finally,provisional datathe string is posted to an MQTT threadschool/temporaryusing itclient.publish()operation mode.

- Read and publish humidity data:

(Video) How to configure an MQTT Mosquitto v2 broker and enable user authentication on Windows in 2022

humidity = random(60, 70);
char humString[8];
dtostrf(humidity, 1, 2, humString);
Serial.print("Humidity: ");
String humdata = "Vlažnost: " + String(humString);
client.publish("schoolofiot/humedad", humdata.c_str());

These lines generate a random humidity value between 60 and 70 percent, save it tohumidityvariable.

All in all,send data()The function generates random temperature and humidity values, converts them to strings, and posts them to specific MQTT topics for further processing or monitoring.

You can find the final code in the Code section

But to confirm this, we also need to read the data from the other side:Subscriber.

Subscriber (Windows PC)

To install Subscriber on a computer, we need to install the Mosquitto MQTT application. This app can create brokers, publishers and subscribers - all modules.

To install Mosquitto MQTT on your computer from the official website and make changes to the configuration file for the 1883 listener and enable anonymous connections, you can follow these steps:

1. Download iInstall Mosquito:

  • Go to the official Mosquitto website (
  • A "downloads"Unit.
  • Select the appropriate installer for your operating system (in this case Windows x64) and download it
  • Install the app in the desired location.

2. Edit the configuration file:

  • Open the installation directory where Mosquitto is installed.
  • Locate itmosquito.conffile (usually located in the parent directory).
  • Openmosquito.confin the text editor of your choice.Add the following 2 lines:
listener in 1883
allow_anonymous verdadero
  • It should look something like this:
  • We can uncomment the ad to make changes to the file, but adding just 2 lines at the top is simpler and more noticeable.

3. Corremosquito subscriber

  • Miwe can start the Mosquitto broker and then subscribe to the topic we want. But launching directly to the subscriber is best in our case.
  • Open the folder/directory where mosquitto.exe is locatedmosquito_sub.exehe is present
  • Run itPowerShell/CMDterminal through the directory. for windows,open directory > press shift + right mouse button (right click), and we would see options to launch a terminal as powershell.
  • In the terminal, type the following command:
> .\mosquitto_sub -h -t "schoolfiot/#"

In the above command, if you noticed, I didn't write any specific topic. According to topics that we have published (from ESP32) such as "school/vacancy","school/temporary" "school/humidity".

  • The reason is that the vacuum, temperature and humidity are lower.general themeofa collegiatelevel. So, to access/view published data like your sublevelsa collegiate, we can use '#'.
  • Also, in case we need to log a specific issue (like temperature), we can use a command like this:
> .\mosquitto_sub -h -t "schoolfiot/temperature"

Therefore, regardless of the name given undergeneral theme,we can subscribe and watch everything together.

(Video) How to configure an MQTT Mosquitto broker and enable user authentication on Windows

¡Reps! 🎉

We learned another IoT platform - MosquittoMQTT(From eclipse)

Read more


  • Mosquitto MQTT pomoću PubSub Client Library

Mosquitto MQTT pomoću PubSub Client Library


#include #include // Replace the following variables with the SSID/password combinationcomputer char* ssid = "XXXXXXXXX";computer char* Password = "XXXXXXXXX";// Add the IP address of the MQTT broker, for example:computer char* servidor_mqtt = "";WiFiClient espCliente;PubSubClient the client(espCliente)sangre Last message = 0;char message[50];And t valor = 0;float temperature = 0;float humidity = 0;empty assembly() { Serial.they start(115200) // default elements wifi_adjustment() the client.establecerServidor(servidor_mqtt, in 1883) the client.setCallback(call back)}empty wifi_adjustment() { postpone(10) // We start by connecting to the WiFi network Serial.print() Serial.Impression("Connected to") Serial.print(ssid) Wifi.they start(ssid, Password) while (Wifi.state() != WL_CONNECTED) { postpone(500) Serial.Impression(".") } Serial.print("") Serial.print("Wi-Fi connected") Serial.print("IP adress: ") Serial.print(Wifi.ip local());}empty call back(char* him, problem* message, not signed And t largo) { Serial.Impression("The message reached the headline: ") Serial.Impression(him) Serial.Impression(". Message: ") Serie groupTemp;  For (And t y = 0; y < largo; y++) { Serial.Impression((char)message[y]); groupTemp += (char)message[y]; } Serial.print()}empty reconnecting() { // Loop until we reconnect while (!the client.connected()) { Serial.Impression("Trying to connect MQTT...") // Connection attempt Serie Customer identification = "the client-" + coincident(100, 999) I (the client.connect-connect(Customer identification.c_str())) { Serial.print("connected")  } elsewhere { Serial.Impression("failure, rc=") Serial.Impression(the client.state()); Serial.print("try again in 5 seconds") // Wait 5 seconds before trying again postpone(5000) } }}empty LOOP() {   I (!the client.connected()) { reconnecting() } the client.LOOP() sangre now = mili()  I (now - Last message > in the year 2000) { Last message = now; Serial.print(the client.connected()); sending data() }}empty sending data(){ Serial.print() the"school/empty", "--------------")  //Accept the temperature temperature = coincident(30,40)  char temporary string[8]; dtostrf(temperature, 1, 2, temporary string) Serial.Impression("Temperature:") Serial.print(temporary string) Serie provisional data = "Temperature:" + Serie(temporary string) the"school/temperature", provisional data.c_str()); //Accept moisture humidity = coincident(60,70)  char HumString[8]; dtostrf(humidity, 1, 2, HumString) Serial.Impression("Humidity: ") Serial.print(HumString) Serie humdata = "Humidity: " + Serie(HumString) the"school/humidity", humdata.c_str()); }


Akshay Sinha

22 projects • 16 followers

The creator who creates.


10 projects • 1 follower

(Video) IoT Training #7 Making cellular communications work with MQTT



What version of MQTT does Mosquitto use? ›

Eclipse Mosquitto is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 5.0, 3.1. 1 and 3.1. Mosquitto is lightweight and is suitable for use on all devices from low power single board computers to full servers.

What is the difference between MQTT and MQTTs? ›

MQTT is a widely used network protocol in IoT for sending messages between devices and a server. To keep the connection secure, MQTTS is normally used. Unfortunately, the added security from MQTT to MQTTS requires more traffic and drains device batteries quicker.

What is the difference between MQTT and Mosquitto? ›

Sensors and actuators are the sources and destinations of MQTT messages. Message Queuing Telemetry Transport (MQTT) is a standard protocol. Mosquitto is a bridge which connects to other MQTT based messaging servers. Bridge has features of passing MQTT messages from source to destination.

What is the default port for Mosquitto broker? ›

The default configuration uses a default listener which listens on port 1883. To configure the broker to listen on additional ports you need to create extra listeners.


1. 008 | How to Create Your Own Public MQTT Broker using Mosquitto and Ngrok | MQTT | IoT | IIoT |
(Fusion Automate)
2. Raspberry Pi IoT Server Tutorial: InfluxDB, MQTT, Grafana, Node-RED & Docker
(Learn Embedded Systems)
3. Learn MQTT Protocol using Mosquitto & MQTT fx
4. MQTT Broker Comparison for Your IoT Applications
5. Mosquitto MQTT Broker on Raspberry Pi Zero 2 W Using Cedalo Platform
6. Easy MQTT Server Setup


Top Articles
Latest Posts
Article information

Author: Kieth Sipes

Last Updated: 11/05/2023

Views: 6447

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.