Connecting ESP-IDF MCU to MQTT Broker with ESP-MQTT-C++

Embedded System

In this tutorial, we’ll explore how to connect an ESP-IDF MCU to an MQTT broker using the ESP-MQTT-C++ component. This component is a wrapper over the esp_mqtt client, designed to provide a higher-level API for working with MQTT in C++ applications.

If you’re using C instead of C++, you can find the corresponding article on my blog.

Prerequisites

Before you begin, make sure you have the necessary prerequisites in place:

  1. Clone the ESP Protocols repository from Espressif by running the following command:

    git clone https://github.com/espressif/esp-protocols
  2. In the esp-protocols repository, navigate to the ./components/esp_mqtt_cxx/examples directory. You can either modify the TCP or SSL examples based on your requirements. The rest of this article is based on the TCP example, but the SSL example should behave similarly.

Implementation

Configure MQTT Broker

To connect to your MQTT broker with an URL, port number, and a username, you should configure it as follows:

mqtt::BrokerConfiguration broker{
    .address = {
        mqtt::BrokerAddress{
            .address = {mqtt::URI{std::string{CONFIG_BROKER_URL}}}, // Add your Broker URL
            .port = 1883  // Add the Broker port here
        }
    },
    .security =  mqtt::Insecure{}
};

mqtt::ClientCredentials credentials{
    .username = "JohnDoe", // Fill in your username
};

mqtt::Configuration config{};

MyClient client{broker, credentials, config};

For Thingsboard users, your username could be your $ACCESS_TOKEN. This is a straightforward way (though not as secure) to connect to Thingsboard with the MQTT protocol. The alternative authentication options include X.509 Certificates, Basic MQTT Credentials (Client ID, Username, Password).

Sending MQTT JSON

In ESP-MQTT, the MQTT_EVENT_CONNECTED event is posted by the MQTT client when it successfully establishes a connection to the broker. This event indicates that the client is ready to send and receive data.

For information on other MQTT events and their meanings, please refer to Espressif’s MQTT documentation.

To send MQTT JSON data when the MQTT_EVENT_CONNECTED event occurs, you can override the mqtt::Client::on_connected() method. Here’s how you can create a loop that runs every five seconds, prepares a JSON string containing telemetry data, and uses the publish() method to send the message to the topic "v1/devices/me/telemetry":

private:
    void on_connected(esp_mqtt_event_handle_t const event) override
    {
        using mqtt::QoS;
        subscribe(messages.get());
        subscribe(sent_load.get(), QoS::AtMostOnce);

        while(true)
        {
            // dummy telemetry JSON
            std::string telemetryData = "{\"stringKey\":\"value1\",\"booleanKey\":true,\"doubleKey\":42.0,\"longKey\":73,\"jsonKey\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}";

            // Define a message struct with the telemetry data, QoS, and retain configuration
            mqtt::Message<std::string> message{
                .data = telemetryData,
                .qos = QoS::AtLeastOnce,
                .retain = mqtt::Retain::NotRetained
            };

            publish("v1/devices/me/telemetry", message);
            vTaskDelay(5000 / portTICK_PERIOD_MS);
        }
    }

With this setup, your ESP-IDF MCU will successfully connect to the MQTT broker and periodically send telemetry data as JSON payloads to the specified topic.

Further Resources for Customization

If you’re eager to dive deeper into customizing your ESP-MQTT-C++ implementation and want to explore more details or cross-reference the C version of the documentation, here are some valuable resources:

  • ESP MQTT C++ Documentation: This official documentation for the ESP MQTT C++ component provides insights into the specifics of working with the C++ wrapper. You’ll find detailed information on the C++ API and various configuration options. It’s an essential resource for understanding the ESP-MQTT-C++ component.

  • ESP MQTT C Documentation: The C version of the ESP MQTT documentation offers comprehensive information about the MQTT client in ESP-IDF. While the C++ documentation may not be as detailed, it’s a good practice to cross-reference the C documentation when working with the C++ component. This will help you gain a more comprehensive understanding of MQTT in the ESP-IDF ecosystem and troubleshoot any issues that might arise during customization.

By leveraging these resources, you can explore advanced features, troubleshoot potential problems, and fine-tune your ESP-MQTT-C++ implementation to meet the specific requirements of your IoT project. Don’t hesitate to experiment, innovate, and make the most of the flexibility that the ESP-IDF framework and ESP-MQTT-C++ offer.