Lecture 6 - MQTT Clients
Lecture Note 6: ESP32 – MQTT Clients
- CSS452 Internet of Things
- Dr. Seksan Laitrakun
- School of ICT, SIIT, Thammasat University
Outlines
- Introduction to MQTT
- Installing a Necessary Library in Arduino IDE
- Publishing/Subscribing via a Public MQTT Broker using Two ESP32
- Publishing/Subscribing via a Public MQTT Broker using One ESP32
References
- Random Nerd Tutorials: https://randomnerdtutorials.com/projects-esp32/
- HiveMQ: https://www.hivemq.com/developers/
1. Introduction to MQTT
MQTT and Publish/Subscribe Method
- MQTT (Message Queuing Telemetry Transport) is a communication protocol for the Internet of Things (IoT) that uses the publish/subscribe method for communication.
- MQTT is lightweight and is used in low bandwidth environments.
- It is popular for IoT systems (a network of constrained devices).
- Three main components in MQTT:
- Publisher/Producer (sender)
- Broker (middleman)
- Subscriber/Consumer (receiver)
Think of it like a magazine subscription service: writers (publishers) send articles to a publishing house (broker), and readers (subscribers) who signed up for a particular magazine title (topic) automatically get every new issue — the writer never needs to know who's reading.
Publish/subscribe method (steps)
- The producer publishes a message (data) and the topic to the Broker.
- The Broker receives the message (data) and the topic.
- The Broker sends the message (data) to the appropriate consumer(s) that are subscribed to this topic.
[Image: MQTT pub/sub diagram — temperature sensor publishes to MQTT Broker, laptop and mobile device subscribe/publish back]
Advantages of MQTT
- The publish/subscribe method (pub/sub) is an alternative to traditional client-server architecture.
- HTTP protocol: in the client-server model, a client communicates directly with an endpoint.
- Advantages: pub/sub decouples the client that sends a message (publisher) from the client(s) that receive the messages (subscribers).
- The publishers and subscribers never contact each other directly — they aren't even aware the other exists. Unlike HTTP, publisher and subscriber don't need to know each other's IP addresses.
- The connection between them is handled by a third component (the broker), which filters all incoming messages and distributes them correctly to subscribers.
- The topic is the key that lets the message be delivered to the corresponding subscribers.
- As a result, the publisher and subscriber do not know each other.
Like a radio station: the station (publisher) broadcasts on a frequency (topic) without knowing who's listening; listeners (subscribers) tune in to that frequency without ever contacting the station directly.
How does MQTT work?
- The pub/sub method solves the problem of detail by introducing a new concept: a topic.
- Each publisher must declare itself to the MQTT broker and its published topics.
- Each subscriber must declare itself as a subscriber and its subscribed topics.
- The MQTT broker will distribute messages from publishers to subscribers according to the topic.
- In MQTT, an IoT device can be:
- a publisher,
- a subscriber,
- both publisher and subscriber.
[Image: Example diagram — humidity sensor publishes "55%" to topic "humidity"; two subscribers (phone, monitor) receive it]
Topic Setup: A Systematic Way
- A topic can be defined as a hierarchy (or level), using a slash (
/) as a separator. - Example: smart home "Home1" has 3 rooms (Room1, Room2, Room3), each with 2 sensor nodes: "temp" and "humid". 6 sensor nodes total, set up as publishers with topics:
Home1/Room1/tempHome1/Room1/humidHome1/Room2/tempHome1/Room2/humidHome1/Room3/tempHome1/Room3/humid
- This gives 3 topic levels (you can create as many levels as you want).
- A device wanting humidity data from room 2 subscribes to the topic
Home1/Room2/humid.
This is basically a folder-path system for data:
Home1/Room2/humidis like a file pathHome1/Room2/humid.txt— each slash narrows down exactly where the data "lives".
Wildcards
By setting topics as a hierarchy, we can use two wildcards when a device wants to subscribe to many topics at once.
-
Single-level wildcard (
+): subscribes to various topics at once, but only one level deep.Example — given published topics:
Home1/Room1/temp,Home1/Room1/humid,Home1/Room2/temp,Home1/Room2/humid,Home1/Room3/temp,Home1/Room3/humid:- a) Which topics will a subscriber receive if it subscribes to
Home1/Room1/+?- →
Home1/Room1/tempandHome1/Room1/humid
- →
- b) Which topics will a subscriber receive if it subscribes to
Home1/+/temp?- →
Home1/Room1/temp,Home1/Room2/temp,Home1/Room3/temp
- →
- a) Which topics will a subscriber receive if it subscribes to
-
Multi-level wildcard (
#): subscribes to various topics at once, multiple levels deep.Example (same published topics as above):
- a) Which topics will a subscriber receive if it subscribes to
Home1/Room1/#?- →
Home1/Room1/tempandHome1/Room1/humid
- →
- b) Which topics will a subscriber receive if it subscribes to
Home1/#?- → all six topics (every temp and humid topic under Home1)
- a) Which topics will a subscriber receive if it subscribes to
+is like a wildcard for exactly one folder level (e.g., "any room, but only its direct temp reading"), while#is like "everything inside this folder and all its subfolders" — a catch-all.
Quality of Service (QoS)
- What is QoS? A setting that defines the guarantee of message delivery between the client and the broker.
- Who decides? The publisher sets the level for the message, and the subscriber sets the maximum level it is willing to receive.
- The Rule: The message is always delivered at the lower of the two QoS levels.
| Level | Name | Guarantee | Description |
|---|---|---|---|
| QoS 0 | Fire and Forget | At most once | The message is sent once with no confirmation. Fast but unreliable. |
| QoS 1 | Acknowledged Delivery | At least once | The message is guaranteed to arrive, but duplicates may occur if acknowledgments are lost. |
| QoS 2 | Assured Delivery | Exactly once | The message is guaranteed to arrive exactly one time through a multi-step handshake. Slowest but most reliable. |
Think of QoS like shipping options: QoS 0 is dropping a letter in a mailbox with no tracking (might get lost); QoS 1 is registered mail (guaranteed, but you might get a duplicate confirmation); QoS 2 is a signed, tracked courier delivery (guaranteed exactly once, but slowest).
2. Installing a Necessary Library in Arduino IDE
- To let an ESP32 send a message using the MQTT protocol, we must install a library "PubSubClient.h" in the Arduino IDE.
- On the Arduino IDE, choose: Sketch → Include Library → Manage Libraries…
- Search for PubSubClient and install it. (This library is provided by Nick O'Leary.)
- After finishing, close the Arduino IDE and open it again.
[Image: Arduino IDE Library Manager screenshot showing PubSubClient by Nick O'Leary]
3. Publishing/Subscribing via a Public MQTT Broker using Two ESP32
3.1 Project Outline
- In this project, we use two ESP32:
- a) An ESP32 called "PubNode" connected to a potentiometer, set as a publisher to send the potentiometer value to the other ESP32 (subscriber) via a public MQTT broker.
- b) An ESP32 called "SubNode" connected to an LED and a resistor, set as a subscriber to receive the potentiometer value via a public MQTT broker.
- Rotating the potentiometer on the PubNode will turn on/off the LED on the SubNode:
- If the potentiometer value is more than 500, the LED will be on; otherwise, the LED will be off.
These two ESP32 do not need to connect to the same access point and can be at different locations.
[Image: Demonstration photo — PubNode with potentiometer on one breadboard, SubNode with LED on another breadboard]
Public MQTT Brokers (free list)
Source: https://mntolia.com/10-free-public-private-mqtt-brokers-for-testing-prototyping/
| Name | Broker Address | TCP Port |
|---|---|---|
| Eclipse | mqtt.eclipse.org | 1883 |
| Mosquitto | test.mosquitto.org | 1883 |
| HiveMQ | broker.hivemq.com | 1883 |
| Flespi | mqtt.flespi.io | 1883 |
| Dioty | mqtt.dioty.co | 1883 |
| Fluux | mqtt.fluux.io | 1883 |
| EMQX | broker.emqx.io | 1883 |
- In this project, we will use HiveMQ as the public MQTT broker (port 1883).
- Note: if there is a problem with HiveMQ, you might choose Mosquitto instead.
3.2 Schematic
- Connect a potentiometer to the PubNode:
- Potentiometer wiper → pin A0
- One end → Pin 3v3 of ESP32
- Other end → Pin GND of ESP32
- Connect an LED and resistor to the SubNode:
- Pin 26 → LED → 330Ω resistor → Pin GND of ESP32
[Image: Schematic diagrams for PubNode (potentiometer wiring) and SubNode (LED + 330Ω resistor wiring)]
3.3 Arduino Code
Two Arduino codes are used:
Public_HiveMQ_PubNode.ino— sets the ESP32 as a publisher, reads the potentiometer value, and sends it to the public HiveMQ broker.Public_HiveMQ_SubNode.ino— sets the ESP32 as a subscriber, receives the subscribed message from the public HiveMQ broker, and turns the LED on/off.
[Image: Photo of the two breadboards (PubNode + SubNode) used for demonstration]
This code demonstrates how to:
- Configure the ESP32 as an MQTT Client — set up the connection and define its role as either a Publisher or a Subscriber.
- Publish Sensor Data — read a value from a potentiometer and send it to a specific MQTT topic.
- Subscribe and Act on Data — listen for messages on a topic and use the received data to control a physical output (an LED).
Revising the given code
-
Write this code in your Arduino IDE.
-
Fill in your SSID and Password of your access point:
const char* ssid = "Your SSID";const char* password = "Your Password"; -
Add your student ID at the end of Client and Topic so we have unique names:
const char* ClientID = "Client_YourStudentID";const char* Topic = "IoT/PotenValue_YourStudentID";- ClientID: PubNode and SubNode have different ClientIDs, and different from other students'.
- Topic: must be the same topic name in both PubNode and SubNode. However, it must be a different namefrom other students.
3.3.1 Arduino Code: "Public_HiveMQ_PubNode.ino"
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Your SSID";
const char* password = "Your Password";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* ClientID = "Client_YourStudentID";
const char* Topic = "IoT/PotenValue_YourStudentID";
long lastMsg = 0;
WiFiClient ClientNode;
PubSubClient ClientESP(ClientNode);- Lines 1–2: necessary libraries.
- Lines 4–5: WiFi access point parameters.
- Lines 6–9: the MQTT parameters.
- Lines 12–13: set up an MQTT node.
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
ClientESP.setServer(mqtt_server, mqtt_port); //Specify the MQTT server
ConnectMQTT(); //Connect to the MQTT server.
}- The first block connects to your WiFi access point.
- The last two lines specify the MQTT broker and connect to it.
void loop() {
if (!ClientESP.connected()) {
ConnectMQTT();
}
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
char Val[8];
dtostrf(analogRead(A0), 1, 0, Val);
ClientESP.publish(Topic, Val);
Serial.print("Pub: ");
Serial.println(Val);
}
}if (!ClientESP.connected())checks the connection to the MQTT broker.- The rest is the publisher part:
- Checks every 2 seconds.
- Publishes the value from pin A0 to the MQTT broker under the topic "Topic".
dtostrf()is a function to convert an integer to a string..publish()is used to publish.
void ConnectMQTT() {
while (!ClientESP.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to the broker
if (ClientESP.connect(ClientID, NULL, NULL)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(ClientESP.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}- A custom function to connect to the MQTT broker and listen to an incoming message from the broker.
- Compared to the SubNode code, there is no
.setCallback()method and no.subscribe()method because this ESP32 is working as a publisher only.
3.3.2 Arduino Code: "Public_HiveMQ_SubNode.ino"
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Your SSID";
const char* password = "Your Password";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* ClientID = "Client_YourStudentID";
const char* Topic = "IoT/PotenValue_YourStudentID";
long lastMsg = 0;
WiFiClient ClientNode;
PubSubClient ClientESP(ClientNode);- Lines 1–2: necessary libraries.
- Lines 4–5: WiFi access point parameters.
- Lines 6–9: the MQTT parameters.
- Lines 12–13: set up an MQTT node.
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
ClientESP.setServer(mqtt_server, mqtt_port); //Specify the MQTT server
ClientESP.setCallback(callback);
ConnectMQTT(); //Connect to the MQTT server.
pinMode(26, OUTPUT); //Set the pin mode to the pin GPIO26
digitalWrite(26, LOW);
}- The first block connects to your WiFi access point.
- The MQTT block specifies the broker, sets up the callback (for a subscriber), and connects to it.
void loop() {
if (!ClientESP.connected()) {
ConnectMQTT();
}
ClientESP.loop();
}if (!ClientESP.connected())checks the connection to the MQTT broker.ClientESP.loop();— this is for a subscriber. This command should be called regularly to allow the client to process incoming messages and maintain its connection to the server.
void ConnectMQTT() {
while (!ClientESP.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to the broker
if (ClientESP.connect(ClientID, NULL, NULL)) {
Serial.println("connected");
ClientESP.setCallback(callback);
ClientESP.subscribe(Topic);
} else {
Serial.print("failed, rc=");
Serial.print(ClientESP.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}- A custom function that:
- connects to the MQTT broker,
- (as a subscriber) listens for an incoming message from the broker.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String ValString;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
ValString += (char)payload[i];
}
Serial.println();
int ValInt = ValString.toInt();
Serial.print("Sub : ");
Serial.println(ValInt);
Serial.println("================ Wait 2 seconds ====================");
if (ValInt > 500) {
digitalWrite(26, HIGH); // Turn the LED on
} else {
digitalWrite(26, LOW); // Turn the LED off
}
}- This function is called when the ESP32 receives an incoming message from the broker.
- The incoming message is stored in the variable "ValString".
- Convert the ValString to an integer.
- Store it in the variable "ValInt".
- Use ValInt to turn the LED on/off.
3.4 Code Explanation (Summary)
- Declare MQTT parameters: MQTT broker address, MQTT port number (in general 1883), name of the MQTT publisher or subscriber, and the topic. The publisher name, subscriber name, or topic can be any name.
- Set the ESP32 as a web client and pub/sub client.
- Set up the MQTT protocol:
- Specify the MQTT server.
- Specify that if a subscribed message arrives, call the function "callback".
- Connect to the MQTT broker using a custom function
ConnectMQTT();.
- Check whether the ESP32 connects to the MQTT broker.
- In the Sub Node, call
ClientESP.loop();regularly to allow the client to process incoming messages and maintain its connection to the server. - In the Pub Node, convert an integer to a string and publish (send) it under the topic "Topic" to the MQTT broker.
- In the Sub Node, declare the topic to be subscribed from the MQTT broker via
ClientESP.subscribe(Topic);. - In the Sub Node, the function "callback" is called when a subscribed message is received. The subscribed message is stored in the pointer variable "payload" whose length is equal to the variable "length".
- In the Sub Node, retrieve the subscribed message from the pointer variable "payload" to the variable "ValString".
4. Publishing/Subscribing via a Public MQTT Broker using One ESP32
4.1 Project Outline
- In this project, we implement a global MQTT-based system, where:
- a public MQTT broker is set up as our MQTT broker,
- our ESP32 works as both publisher and subscriber (sending the data to itself).
This is like talking to yourself through a walkie-talkie relay station: you transmit a message out (publish), and the same relay sends it right back to your own receiver (subscribe) — useful for testing the whole pipeline with just one device.
[Image: Photo of single ESP32 breadboard with potentiometer and LED wired together]
[Image: Photo of Arduino IDE code "Public_HiveMQ_PubSub" showing WiFi/MQTT parameter declarations]
Public MQTT Brokers (same list as before)
| Name | Broker Address | TCP Port |
|---|---|---|
| Eclipse | mqtt.eclipse.org | 1883 |
| Mosquitto | test.mosquitto.org | 1883 |
| HiveMQ | broker.hivemq.com | 1883 |
| Flespi | mqtt.flespi.io | 1883 |
| Dioty | mqtt.dioty.co | 1883 |
| Fluux | mqtt.fluux.io | 1883 |
| EMQX | broker.emqx.io | 1883 |
- Again, we use HiveMQ (port 1883); switch to Mosquitto if there's a problem.
Tasks
- Connect a potentiometer and an LED (and a resistor) on the ESP32.
- Rotating the potentiometer will turn the LED on and off:
- Potentiometer value > 500 → LED is on
- Otherwise → LED is off
- Roles of the single ESP32:
- As a publisher, the ESP32 sends the potentiometer value to the MQTT broker every 2 seconds.
- As a subscriber, the ESP32 receives a message (potentiometer value) from the MQTT broker (when the broker receives a new value). The ESP32 compares the received value (> 500 or not) and turns the LED on or off accordingly.
[Image: Photo of single ESP32 breadboard setup with potentiometer and LED]
4.2 Schematic
- Connect a potentiometer and an LED to the ESP32:
- Potentiometer wiper → pin A0
- One end → Pin 3v3 of ESP32
- Other end → Pin GND of ESP32
- Pin 26 → LED → 330Ω resistor → Pin GND of ESP32
[Image: Schematic diagram + photo of single ESP32 wired with potentiometer and LED]
4.3 Arduino Code
- The Arduino code "Public_HiveMQ_PubSub.ino" sets the ESP32 to be both publisher (sends the potentiometer value to the broker) and subscriber (receives the potentiometer value from the broker), connecting to the HiveMQ broker.
Revising the given code
-
Write this code in your Arduino IDE.
-
Fill in your SSID and Password of your access point:
const char* ssid = "Your SSID";const char* password = "Your Password"; -
Add your student ID at the end of Client and Topic so we have unique names:
const char* ClientID = "Client_YourStudentID";const char* Topic = "IoT/PotenValue_YourStudentID";
Full Code: "Public_HiveMQ_PubSub.ino"
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Your SSID";
const char* password = "Your Password";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* ClientID = "Client_YourStudentID";
const char* Topic = "IoT/PotenValue_YourStudentID";
long lastMsg = 0;
WiFiClient ClientNode;
PubSubClient ClientESP(ClientNode);- Lines 1–2: necessary libraries.
- Lines 4–5: WiFi access point name and password.
- Lines 6–9: MQTT details.
- Lines 12–13: set up an MQTT node.
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
ClientESP.setServer(mqtt_server, mqtt_port); //Specify the MQTT server
ClientESP.setCallback(callback);
ConnectMQTT(); //Connect to the MQTT server.
pinMode(26, OUTPUT); //Set the pin mode to the pin GPIO26
digitalWrite(26, LOW);
}- The first block connects to your WiFi access point.
- Then:
- Specify the MQTT broker.
- Set up the callback from the MQTT broker — the callback function is called when new messages arrive at the client.
- Connect to the MQTT broker.
void loop() {
if (!ClientESP.connected()) {
ConnectMQTT();
}
ClientESP.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
char Val[8];
dtostrf(analogRead(A0), 1, 0, Val);
ClientESP.publish(Topic, Val);
Serial.print("Pub: ");
Serial.println(Val);
}
}if (!ClientESP.connected())checks the connection to the MQTT broker.ClientESP.loop();— this is for a subscriber; should be called regularly to process incoming messages and maintain its connection to the server.- The rest is the publisher part:
- Checks every 2 seconds.
- Publishes the value from pin A0 to the MQTT broker under the topic "Topic".
dtostrf()converts an integer to a string..publish()publishes the message.
void ConnectMQTT() {
while (!ClientESP.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to the broker
if (ClientESP.connect(ClientID, NULL, NULL)) {
Serial.println("connected");
ClientESP.setCallback(callback);
ClientESP.subscribe(Topic);
} else {
Serial.print("failed, rc=");
Serial.print(ClientESP.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}- A custom function to:
- connect to the MQTT broker,
- listen to an incoming message from the broker.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String ValString;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
ValString += (char)payload[i];
}
Serial.println();
int ValInt = ValString.toInt();
Serial.print("Sub : ");
Serial.println(ValInt);
Serial.println("================ Wait 2 seconds ====================");
if (ValInt > 500) {
digitalWrite(26, HIGH); // Turn the LED on
} else {
digitalWrite(26, LOW); // Turn the LED off
}
}- This function is called if the ESP32 receives an incoming message from the broker.
- The incoming message is stored in the variable "ValString".
- Convert the ValString to an integer.
- Store it in the variable "ValInt".
- Use ValInt to turn the LED on/off.
4.4 Code Explanation (Summary)
- Declare MQTT parameters: MQTT broker address, MQTT port number (in general 1883), name of the MQTT publisher or subscriber, and the topic. The publisher name, subscriber name, or topic can be any name.
- Set the ESP32 as a web client and pub/sub client.
- Set up the MQTT protocol:
- Specify the MQTT server.
- Specify that if a subscribed message arrives, call the function "callback".
- Connect to the MQTT broker using a custom function
ConnectMQTT();.
- Check whether the ESP32 connects to the MQTT broker.
- Call
ClientESP.loop();regularly to allow the client to process incoming messages and maintain its connection to the server. - Convert an integer to a string and publish (send) it under the topic "Topic" to the MQTT broker.
- Declare the topic to be subscribed from the MQTT broker via
ClientESP.subscribe(Topic);. - The function "callback" is called when a subscribed message is received. The subscribed message is stored in the pointer variable "payload" whose length is equal to the variable "length".
- Retrieve the subscribed message from the pointer variable "payload" to the variable "ValString".