ESP32 - ESP32 MQTT client: Publish and Subscribe.

We are going to learn how to:

  • Develop an ESP32 MQTT client to publish MQTT messages and to subscribe to MQTT topics.
  • Use pubsubclient library to connect the ESP32 to MQTT broker.

Hardware Required

1×ESP-WROOM-32 Dev Module
1×Micro USB Cable
1×Breadboard
1×Push button
2×Jumper Wires

Video Tutorial

you can watch this video tutorial

What is MQTT

MQTT protocol is a Machine to Machine (M2M) protocol widely used in IoT (Internet of things).

The MQTT protocol is a message based protocol, extremely light-weight and for this reason, it is adopted in IoT. Almost all IoT platforms support MQTT to send and receive data from smart objects.

MQTT Protocol Technical description

The MQTT IoT protocol was developed around 1999. The main goal of this protocol was to create a protocol very efficient from the bandwidth point of view. Moreover, it is a very power-saving protocol. For all these reasons, it is suitable for IoT.

This uses the publish-subscribe paradigm in contrast to HTTP based on the request/response paradigm. It uses binary messages to exchange information with low overhead. It is very simple to implement and it is open. All these aspects contribute to its large adoption in IoT. Another interesting aspect is the fact that the MQTT protocol uses TCP stack as a transmission substrate.

The role of the MQTT Broker and MQTT Client

As said before, the MQTT protocol implements a publish-subscribe paradigm. This paradigm decouples a client that publishes a message (“publisher”) to other clients that receive the message (“subscribers”). Moreover, MQTT is an asynchronous protocol, which means that it does not block the client while it waits for the message.

In contrast to the HTTP protocol, that is a mainly asynchronous protocol. Another interesting property of MQTT protocol is that it does not require that the client (“subscriber”) and the publisher are connected at the same time.

The key component in MQTT is the MQTT broker. The main task of MQTT broker is dispatching messages to the MQTT clients (“subscribers”). In other words, the MQTT broker receives messages from the publisher and dispatches these messages to the subscribers.

The MQTT topic

While it dispatches messages, the MQTT broker uses the topic to filter the MQTT clients that will receive the message. The topic is a string and it is possible to combine the topics creating topic levels.

A topic is a virtual channel that connects a publisher to its subscribers. MQTT broker manages this topic. Through this virtual channel, the publisher is decoupled from the subscribers and the MQTT clients (publishers or subscribers) do not have to know each other to exchange data. This makes this protocol highly scalable without a direct dependency from the message producer (“publisher”) and the message consumer (“subscriber”).

The schema below describes the MQTT architecture:

ESP32 Button LED Wiring Diagram

ESP32 Code

Copy

#include <WiFi.h>
#include <PubSubClient.h>

const char *SSI_D = "WE_87B9D0";
const char *PWD = "jae05161";

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient); 
const char *mqttServer = "broker.hivemq.com";
int mqttPort = 1883;

void reconnect() {
  Serial.println("Connecting to MQTT Broker...");
  while (!mqttClient.connected()) {
      Serial.println("Reconnecting to MQTT Broker..");
      String clientId = "ESP32Client-";
      clientId += String(random(0xffff), HEX);
      
      if (mqttClient.connect(clientId.c_str())) {
        Serial.println("Connected.");
        // subscribe to topic
        mqttClient.subscribe("someTopic");
      }
      
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Callback - ");
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println("");
}


void setup() {
  Serial.begin(115200);
  Serial.print("Connectiog to ");
 
  WiFi.begin(SSI_D, PWD);
  Serial.println(SSI_D);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
     }
  Serial.print("Connected.");

  mqttClient.setServer(mqttServer, mqttPort);
  // set the callback function
  mqttClient.setCallback(callback);
  

}

void loop() {
   if (!mqttClient.connected())
    reconnect();
  mqttClient.loop();

  if(digitalRead(15)){
    mqttClient.publish("buttonTopic", "on");
  }
  delay(500);
  
}              

Code Explanation

  • Step 1: Connect the ESP32 to Wifi
  • Step 2: Set up and configure the ESP32 Client using PubSubClient

    After the Wifi connection is implemented, we can focus on how to configure the MQTT client for ESP32. To simplify client development, we will use the PubSubClient Library that is suggested by HiveMQ.

    You have to import the PubSubClient library using your IDE. It depends on the IDE you are using but the process is almost the same: you have to look for the library and import it.

    • 1: Import the PubSubClient header PubSubClient.h
    • 2: define the mqttClient passing the WiFiClient
    • 3: define the cloud MQTT broker address and the port. In this example, we are using HiveMQ but you can use another MQTT broker
    • 4: configure the mqttClient setting the MQTT broker

  • Step 3: Connect the ESP32 to the MQTT broker

    During this step, we wil connect the ESP32 MQTT client to the broker so that the client can send data.

    • 1: we try to connect the ESP32 MQTT client to the broker selecting a random id client (clientId). The clientId changes every time we connect
    • 2: In the loop method, the code checks if the ESP32 client is connected. If not, reconnect the client to the broker
    • 3: the client subscribes to a topic named /swa/commands to receive data (we will see it later)

  • Step 4: Publishing the button readings to MQTT topics using PubsubClient for ESP32

    /swa/temperature topic used to publish the temperature readings

    • 1: the code reads the Button values
    • 2: the code publishes the button reading to the topic
    • 3: the client subscribes to a topic named /swa/commands to receive data (we will see it later)

  • Step 5: Subscribe to MQTT topic to listen to incoming message

    In this step, we subscribe to MQTT topics to listen to the incoming MQTT messages published by another MQTT client subscribing to the same topic. Therefore, in the Pubsubclient library, It is necessary to implement a callback function.

It will be easier to understand exactly how this sketch works in the demonstration.

Using HiveMQ browser client Test

Run the code on your ESP32. If you have done everything correctly, the code should compile and run. Now you can configure the HiveMQ browser client to visualize the MQTT messages published by the MQTT client.

1: Go to this link and click on connect button

2: Add the subscription topics one for each topic the ESP32 uses

You should have something like this:

ESP32 Button LED Wiring Diagram

As soon as the ESP32 client publishes data to this topics you should get see the data as shown in the picture below:

ESP32 Button LED Wiring Diagram

Testing the ESP32 MQTT topic subscription

In this last test we will publish using the HiveMQ client browser a message to the topic where the ESP32 client is subscribed:

ESP32 Button LED Wiring Diagram

Notice that the topic is the same used in the ESP32 MQTT client code. Write Hello ESP32 in the message box and click on publish. We will get:

ESP32 Button LED Wiring Diagram

Book Tutorial

We are considering to make the book tutorials. If you think the book tutorials are essential, you can download it. download book

※ NOTE THAT:

Some components works on 3.3v and others works on 5v!

test bootstrap style