MQTT TCP Example
Note
This document is automatically translated using AI. Please excuse any detailed errors. The official English version is still in progress.
Example Description
This example demonstrates how to configure an MQTT client on ESP32, establish a connection with the Broker via TCP, and perform basic operations of connection status management and message sending and receiving. Through this example, developers can learn the initialization process of the MQTT client under TCP and the method of event callback handling, providing a reference for subsequent specific message interaction implementation.
Running Method
The complete code of the example can be found at mqtt tcp example. Before running, you need to configure Wi-Fi, Ethernet, or Thread, as detailed in the README.md file in the example directory.
Note
If an esp-tls error occurs after the example is run, you can find the corresponding cause and possible solution by viewing the error troubleshooting document. You can also find the corresponding return value through ESP TLS return value.
Through the above methods, it can be found that if the following error occurs, the cause may be a connection timeout. At this time, you should check whether the network is smooth, for example, you can use MQTT tools, such as MQTTX to access this MQTT Broker, or try to change the MQTT Broker, etc.
E (15139) mqtt_example: Last error reported from esp-tls: 0x8006
Header File Description
The header files used in this example cover FreeRTOS task management, system utility modules, Bluetooth controller and protocol stack interfaces, and BLE GATT service-related APIs, etc., building the core functions of BLE initialization, Profile management, event handling, and data interaction.
The header files are classified by function as follows:
Standard C library functions: Provide data type definitions, memory management, string operations, and input/output support for underlying data processing and general algorithm implementation.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
System and hardware interfaces: Provide ESP32 system control and non-volatile storage operation interfaces for chip management, reset, deep sleep, and storage configuration parameters.
#include "esp_system.h"
#include "nvs_flash.h"
Network and event management: Provide network interface initialization and event loop mechanism for TCP/IP communication and event-driven system response.
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
Log and debugging support: Provide a unified log printing interface, support module tags and log levels, for development and debugging.
#include "esp_log.h"
MQTT Client Functionality: Provides MQTT client configuration, connection establishment, event callback, and message sending/receiving interfaces for IoT device communication with the Broker.
#include "mqtt_client.h"
Task Function Description
This example includes three task functions, which are used for MQTT client initialization, event callback processing, and error message printing, helping to understand the client’s configuration, connection, and event-driven communication logic.
MQTT Client Initialization
mqtt_app_start()
is used to initialize the MQTT client and register event callbacks, preparing the client for connection and message handling.
Its execution logic is as follows:
Configuration Structure: For specific structure members, refer to MQTT API, and for the configuration explanation of each structure member, refer to MQTT Structure Configuration Explanation.
In this example, only the
uri
of the Server Address is configured.Because the complete URI already includes the protocol type, hostname, and port information, the client will prioritize using the URI to establish a connection; at the same time, since the example uses TCP plaintext transmission and does not involve TLS encryption or server verification, there is no need to configure certificates or verification parameters, thereby simplifying the client configuration process.
Manually Input URI: In addition to using the default URI, you can also choose to obtain the URI through standard input. This step is only performed when the macro
CONFIG_BROKER_URL_FROM_STDIN
is enabled.
Create a character array variable
line[]
to store the user-input Broker URI, with an array length of 128.Determine whether the configured Broker address is
"FROM_STDIN"
, this marker indicates that the default URI is not currently in use, and the user needs to provide the actual URI from standard input.
Read the string from standard input and save it to the variable
line
, setting the structure’suri
to this variable.Print confirmation information, displaying the final Broker URI.
If the initially configured Broker address is not
"FROM_STDIN"
, it is considered a configuration error. Print the error log and terminate the program execution to avoid running under invalid configuration.
Initialize/Start MQTT Client
Call
esp_mqtt_client_init()
to initialize the MQTT client according to the configuration, and save the returned handle to the variableclient
for subsequent operations. For API introduction and parameter explanation, refer to MQTT API.Call
esp_mqtt_client_register_event()
to register the event callback function to the client, which is used to handle events such as connection, subscription, message sending and receiving uniformly. For API introduction and parameter description, please refer to MQTT API.Call
esp_mqtt_client_start()
to start the initialized MQTT client, establish a connection with the Broker and enter the event loop. For API introduction and parameter description, please refer to MQTT API.
Event Callback Function
mqtt_event_handler()
is the MQTT client event callback function, which is used to centrally handle various events during the client’s operation, such as connection establishment, disconnection, message publication and subscription results, message reception and error situations, thereby realizing the interaction logic between the client and the Broker. The events that the client may trigger can be referred to Events.
Its execution logic is:
Print debug information, mark the current triggered event source and event ID.
Convert the incoming event data and event client into corresponding types.
Create an integer variable
msg_id
for subsequent reception of the return value of the publish or subscribe operation.Distinguish event types through event ID, and perform corresponding operations for different events:
MQTT_EVENT_CONNECTED
:
Print the event type.
Call
esp_mqtt_client_publish()
to publish a message to a specified topic and print the result, which is used to verify whether the client can send data normally after the connection. For API introduction and parameter description, please refer to MQTT API.Call
esp_mqtt_client_subscribe()
twice to subscribe to messages of different QoS levels of the same topic respectively, and print the results. By comparing the reception of messages with different QoS, the client’s processing mechanism can be verified and whether the Broker’s delivery strategy is normal can be judged. For API introduction and parameter description, please refer to MQTT API.Invoke
esp_mqtt_client_unsubscribe()
to unsubscribe from a specific topic and print the result, demonstrating the unsubscription process and indicating that the client can dynamically adjust subscriptions. For an introduction to the API and an explanation of its parameters, refer to MQTT API.Note
The immediate unsubscription in the example is only for demonstrating the order of API calls. In actual use, the topic just subscribed to is usually not unsubscribed immediately. For business logic, subsequent operations should be continued after receiving the corresponding confirmation event.
MQTT_EVENT_DISCONNECTED
: Print logs to locate the time of disconnection.
MQTT_EVENT_SUBSCRIBED
: After printing the event type, callesp_mqtt_client_publish()
to publish a message to verify the subscription result.
MQTT_EVENT_UNSUBSCRIBED
: Print logs to locate the time of unsubscription.
MQTT_EVENT_PUBLISHED
: Print logs to locate the time of message publishing.
MQTT_EVENT_DATA
: Print the event type and the received topic and message content for message processing and debugging.
MQTT_EVENT_ERROR
: For TCP transmission errors, call the task functionlog_error_if_nonzero()
to check related error fields for problem location.Other events: Print the event ID.
Note
The event handling logic can be adjusted according to actual application requirements. The example here is only for demonstrating how the client responds to common MQTT events and the basic process of publishing, subscribing, and unsubscribing operations.
Error Message Printing
log_error_if_nonzero()
is a helper function used to check the incoming error code error_code
and print the corresponding error message message
when the error code is non-zero, for debugging and troubleshooting.
Main Function Description
This function serves as the program entry point, used for system initialization, network configuration, and the startup and event callback registration of the MQTT client.
Its execution process is as follows:
Print logs, program startup information, remaining heap memory, and the used ESP-IDF version.
Call
esp_get_free_heap_size()
to get the current remaining heap memory. For an introduction to the API and an explanation of its parameters, refer to Miscellaneous System API.Call
esp_get_idf_version()
to get the ESP-IDF version. For an introduction to the API and an explanation of its parameters, refer to Miscellaneous System API.
Call
esp_log_level_set()
to set the log levels of various modules separately, used to control the detail level of logs output by each module, including the MQTT client, example program, transport layer, and TLS modules. For an introduction to the API and an explanation of its parameters, refer to Log Library.Call
nvs_flash_init()
to initialize non-volatile storage, providing storage support for the system and MQTT client. For API introduction and parameter description, refer to NVS API.Call
esp_netif_init()
to initialize the network interface layer ESP-NETIF, preparing for Wi-Fi or Ethernet functionality.Call
esp_event_loop_create_default()
to create the default event loop, providing a foundation for system and MQTT client event handling. For API introduction and parameter description, refer to Event Loop Library.Call
example_connect()
to configure and connect to the network (Wi-Fi or Ethernet), ensuring the device has networking capabilities.Call the task function
mqtt_app_start()
to initialize and start the MQTT client, while registering the event callback function to handle connection, subscription, publication, and message receiving events.