Based on your requirements, you might want to consider the esp-mqtt library developed by Espressif, the company behind the ESP32. This library supports MQTT over TCP with SSL using mbedtls, which means it can handle TLS 1.2 and 1.3. It's also designed to work with the ESP-IDF, which is the official development framework for the ESP32.
Here are some key features of the esp-mqtt library:
- Supports MQTT over TCP, SSL with mbedtls, MQTT over Websocket, and MQTT over Websocket Secure.
- Allows for easy setup with URI.
- Supports multiple instances (multiple clients in one application).
- Handles subscribing, publishing, authentication, will messages, keep alive pings, and all 3 QoS levels.
To use esp-mqtt, you would need to integrate it into your ESP-IDF project. The library is a standard ESP-IDF component, and you can refer to the ESP-IDF documentation for instructions on how to use it.
Alternatively, you could look into the espMqttClient library, which is a MQTT 3.1.1 compliant library that supports TCP and TCP/TLS using standard WiFiClient and WiFiClientSecure connections. It's designed to work with the Arduino framework on ESP8266 and ESP32, and it provides fully async clients via AsyncTCP or ESPAsnycTCP.
The espMqttClient library allows you to set up TLS secured connections using methods from WiFiClientSecure, which include setting the CA certificate, client certificate, private key, and pre-shared key.
Here's an example of how you might set up a secure connection with espMqttClient:
#include <WiFi.h>
#include <esp_mqtt_client.h>
// WiFi credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT server
const char* mqtt_server = "your_MQTT_SERVER";
// CA certificate for TLS
const char* ca_cert = "-----BEGIN CERTIFICATE-----\n"
"...your CA certificate here...\n"
"-----END CERTIFICATE-----";
void setup() {
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
}
// Set up MQTT client
esp_mqtt_client_config_t mqtt_cfg = {
.uri = mqtt_server,
.cert_pem = ca_cert,
// ... other configurations ...
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_start(client);
}
void loop() {
// Handle MQTT client loop
esp_mqtt_client_loop(client, 10);
}
This example sets up a secure MQTT connection using the CA certificate for TLS. You would replace "your_SSID", "your_PASSWORD", and "your_MQTT_SERVER" with your actual WiFi and MQTT server credentials, and you would provide the actual CA certificate in the ca_cert variable.
Remember to check the documentation for the esp-mqtt library and the espMqttClient library for more detailed information on how to use these libraries and configure them to meet your specific needs.