### PubSubClient to ESP32MQTTClient Migration Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/README.md Illustrates the setup differences between PubSubClient and ESP32MQTTClient for MQTT connections. ESP32MQTTClient's loopStart is non-blocking. ```cpp PubSubClient client; void setup() { client.setServer("broker", 1883); client.setCallback(messageCallback); } void loop() { if (!client.connected()) { client.connect("client"); // Blocks for 8+ seconds! } client.loop(); // Required in every loop } ``` ```cpp ESP32MQTTClient mqttClient; void setup() { mqttClient.setURI("mqtt://broker:1883"); mqttClient.loopStart(); // Returns immediately! } void loop() { // No mqttClient.loop() needed! } ``` -------------------------------- ### Build and Run ESP-IDF Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Builds, flashes, and monitors a specific example project within the CppEspIdf directory. ```bash cd examples/CppEspIdf idf.py build flash monitor ``` -------------------------------- ### Install ESP32MQTTClient via Arduino IDE Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/README.md Install the library through the Arduino IDE Library Manager. Search for 'ESP32MQTTClient' and click install. ```text Sketch → Include Library → Manage Libraries → Search "ESP32MQTTClient" → Install ``` -------------------------------- ### Compile Arduino Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Compiles an Arduino example project using the Arduino CLI. Ensure the correct board package (`esp32:esp32:esp32`) is installed. ```bash arduino-cli compile --fqbn esp32:esp32:esp32 examples/HelloToMyself ``` -------------------------------- ### Build ESP-IDF Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Builds an example project within the CppEspIdf directory using the ESP-IDF build system. ```bash cd examples/CppEspIdf idf.py build ``` -------------------------------- ### Arduino IDE Setup and Loop Sketch for MQTT Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/usage-patterns.md This sketch demonstrates the basic setup and loop structure for an ESP32 project using the ESP32 MQTT Client library. It includes WiFi connection, MQTT client initialization, event handling, and periodic sensor data publishing. Ensure you replace placeholder credentials with your actual WiFi and MQTT broker details. ```cpp #include #include "ESP32MQTTClient.h" #define SSID "MyWiFi" #define PASSWORD "MyPassword" #define MQTT_URI "mqtt://broker.example.com:1883" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { Serial.println("MQTT Connected!"); mqttClient.subscribe("esp32/led", [](const std::string &payload) { if (payload == "on") { digitalWrite(LED_BUILTIN, HIGH); } else { digitalWrite(LED_BUILTIN, LOW); } }); } } #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) esp_err_t handleMQTT(esp_mqtt_event_handle_t event) { mqttClient.onEventCallback(event); return ESP_OK; } #else void handleMQTT(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { auto *event = static_cast(event_data); mqttClient.onEventCallback(event); } #endif void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); WiFi.begin(SSID, PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected!"); mqttClient.setURI(MQTT_URI); mqttClient.setMqttClientName("ESP32_Arduino"); mqttClient.enableDebuggingMessages(true); if (mqttClient.loopStart()) { Serial.println("MQTT client started"); } } void loop() { // Publish sensor data periodically static unsigned long lastPublish = 0; if (mqttClient.isConnected() && (millis() - lastPublish > 5000)) { lastPublish = millis(); int sensorValue = analogRead(A0); std::string payload = std::to_string(sensorValue); mqttClient.publish("esp32/analog", payload); } delay(100); } ``` -------------------------------- ### Basic Publishing Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/MANIFEST.txt Demonstrates how to publish sensor data to an MQTT topic. Ensure you have WiFi connectivity and an MQTT broker configured. ```cpp #include #include "ESP32MQTTClient.h" // WiFi credentials const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; // MQTT broker details const char* mqtt_server = "YOUR_MQTT_BROKER_ADDRESS"; const int mqtt_port = 1883; const char* mqtt_user = "YOUR_MQTT_USERNAME"; const char* mqtt_password = "YOUR_MQTT_PASSWORD"; // MQTT topic for sensor data const char* sensor_topic = "esp32/sensor/temperature"; void setup() { Serial.begin(115200); Serial.println("Connecting to WiFi..."); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); // Initialize MQTT client ESP32MQTTClient client; client.setBroker(mqtt_server, mqtt_port, mqtt_user, mqtt_password); // Connect to MQTT broker if (client.connect()) { Serial.println("Connected to MQTT broker"); } else { Serial.println("Failed to connect to MQTT broker"); return; } // Simulate sensor reading float temperature = 25.5; // Publish sensor data char temp_str[8]; dtostrf(temperature, 1, 2, temp_str); if (client.publish(sensor_topic, temp_str)) { Serial.println("Temperature published successfully"); } else { Serial.println("Failed to publish temperature"); } client.disconnect(); } void loop() { // Nothing to do in loop for this basic example } ``` -------------------------------- ### Start ESP32 MQTT Client Loop Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Starts the MQTT client's background FreeRTOS task and initiates the connection to the broker. This method is non-blocking and should be called once to begin client operation. It returns true if the task was successfully started, false otherwise. ```cpp if (mqttClient.loopStart()) { Serial.println("MQTT client started"); } else { Serial.println("Failed to start MQTT client"); } ``` -------------------------------- ### Arduino MQTT Client Setup Source: https://github.com/cyijun/esp32mqttclient/blob/main/README.md Basic setup for the ESP32 MQTT Client in an Arduino environment. Ensure WiFi credentials and MQTT broker details are correctly configured. ```cpp #include #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); mqttClient.setURI("mqtt://broker.hivemq.com:1883"); mqttClient.setMqttClientName("ESP32_Client"); mqttClient.loopStart(); // Non-blocking! } void loop() { // Your code here - no need for mqttClient.loop() delay(1000); } ``` -------------------------------- ### MQTT Wildcard Topic Examples Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Illustrates examples of MQTT topic patterns that include wildcards for multi-level ('#') and single-level ('+') matching. ```cpp // Examples: "foo/#", "bar/+/baz" ``` -------------------------------- ### Include Order Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Demonstrates the recommended order for including header files: standard library, ESP-IDF headers, and then local project headers. ```cpp #include #include #include #include "esp_log.h" #include "ESP32MQTTClient.h" ``` -------------------------------- ### ESP-IDF Component Setup Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Instructions for adding ESP32MQTTClient as a component in an ESP-IDF project. ```bash cd your_project/components git clone https://github.com/cyijun/ESP32MQTTClient.git ``` -------------------------------- ### Start Plain MQTT Connection Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Configures and starts the MQTT client for a plain (unencrypted) connection on the default MQTT port. Ensure the broker address and port are correct. ```cpp mqttClient.setURL("broker.example.com", 1883); mqttClient.loopStart(); ``` -------------------------------- ### Configuration Methods (before loopStart) Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md These methods are used to configure the MQTT client before starting the main loop. They set up connection details, security, and client behavior. ```APIDOC ## setURL(h,p,u,pw) ### Description Set broker host and port with optional username and password. ### Method `setURL` ### Parameters - **h** (string) - Required - Broker host address. - **p** (int) - Required - Broker port. - **u** (string) - Optional - Username for authentication. - **pw** (string) - Optional - Password for authentication. ### Example `setURL("mqtt.example.com", 1883, "user", "pass")` ``` ```APIDOC ## setURI(uri,u,pw) ### Description Set broker connection URI with optional username and password. ### Method `setURI` ### Parameters - **uri** (string) - Required - Full MQTT connection URI (e.g., "mqtt://broker:1883"). - **u** (string) - Optional - Username for authentication. - **pw** (string) - Optional - Password for authentication. ### Example `setURI("mqtt://broker:1883", "user", "pass")` ``` ```APIDOC ## setMqttClientName(id) ### Description Set the unique client identifier for the MQTT connection. ### Method `setMqttClientName` ### Parameters - **id** (string) - Required - The client ID string. ### Example `setMqttClientName("ESP32_1")` ``` ```APIDOC ## setCaCert(cert) ### Description Set the Certificate Authority (CA) certificate for TLS/SSL connections. ### Method `setCaCert` ### Parameters - **cert** (string) - Required - The CA certificate in PEM format. ### Example `setCaCert(caCertPEM)` ``` ```APIDOC ## setClientCert(cert) ### Description Set the client certificate for mutual TLS authentication. ### Method `setClientCert` ### Parameters - **cert** (string) - Required - The client certificate in PEM format. ### Example `setClientCert(clientCertPEM)` ``` ```APIDOC ## setKey(key) ### Description Set the private key for the client certificate. ### Method `setKey` ### Parameters - **key** (string) - Required - The private key in PEM format. ### Example `setKey(privKeyPEM)` ``` ```APIDOC ## setMaxPacketSize(sz) ### Description Set the maximum allowed MQTT packet size. ### Method `setMaxPacketSize` ### Parameters - **sz** (int) - Required - The maximum packet size in bytes. ### Example `setMaxPacketSize(4096)` ``` ```APIDOC ## setKeepAlive(sec) ### Description Set the keep-alive interval for the MQTT connection. ### Method `setKeepAlive` ### Parameters - **sec** (int) - Required - The keep-alive interval in seconds. ### Example `setKeepAlive(30)` ``` ```APIDOC ## setAutoReconnect(b) ### Description Enable or disable automatic reconnection to the MQTT broker. ### Method `setAutoReconnect` ### Parameters - **b** (bool) - Required - `true` to enable, `false` to disable. ### Example `setAutoReconnect(true)` ``` ```APIDOC ## enableLastWillMessage(t,m,r) ### Description Configure and enable the Last Will and Testament (LWT) message. ### Method `enableLastWillMessage` ### Parameters - **t** (string) - Required - The topic for the LWT message. - **m** (string) - Required - The payload of the LWT message. - **r** (bool) - Required - Whether the LWT message should be retained. ### Example `enableLastWillMessage("topic", "offline", true)` ``` ```APIDOC ## disablePersistence() ### Description Disable session persistence for the MQTT client. ### Method `disablePersistence` ### Example `disablePersistence()` ``` ```APIDOC ## enableDebuggingMessages(b) ### Description Enable or disable debugging messages for the MQTT client. ### Method `enableDebuggingMessages` ### Parameters - **b** (bool) - Required - `true` to enable, `false` to disable. ### Example `enableDebuggingMessages(true)` ``` -------------------------------- ### Basic ESP32 MQTT Client Sketch Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/README.md A fundamental example demonstrating how to connect to WiFi, set up the MQTT client, subscribe to a topic, and publish messages. Ensure you replace 'SSID', 'PASSWORD', and 'broker.example.com' with your actual network credentials and MQTT broker details. ```cpp #include #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { mqttClient.subscribe("test/topic", [](const std::string &payload) { Serial.println(payload.c_str()); }); } } #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) esp_err_t handleMQTT(esp_mqtt_event_handle_t event) { mqttClient.onEventCallback(event); return ESP_OK; } #else void handleMQTT(void *h, esp_event_base_t b, int32_t id, void *d) { mqttClient.onEventCallback((esp_mqtt_event_handle_t)d); } #endif void setup() { WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) delay(100); mqttClient.setURL("broker.example.com", 1883); mqttClient.setMqttClientName("ESP32_Client"); mqttClient.loopStart(); } void loop() { if (mqttClient.isConnected()) { mqttClient.publish("test/status", "online"); } delay(5000); } ``` -------------------------------- ### loopStart() Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Starts the MQTT client's background FreeRTOS task and initiates the connection to the broker. This method is non-blocking and serves as the primary entry point for establishing a connection. ```APIDOC ## loopStart() ### Description Starts the MQTT client's background FreeRTOS task and initiates the connection to the broker. Non-blocking—returns immediately. This is the main entry point to connect to the MQTT broker. ### Method bool ### Parameters None ### Return: `bool` - `true` if the background task was successfully started - `false` if initialization failed (no URI set, memory allocation failed, or ESP-IDF error) ### Behavior: - Creates and starts a FreeRTOS task running the MQTT client loop in the background - Connection attempts and message handling happen asynchronously - Multiple calls are safe (though typically only called once) ### Example: ```cpp if (mqttClient.loopStart()) { Serial.println("MQTT client started"); } else { Serial.println("Failed to start MQTT client"); } ``` ``` -------------------------------- ### Arduino IDE Environment Setup Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/MANIFEST.txt Provides instructions and code structure for setting up the ESP32 MQTT Client library within the Arduino IDE. This includes necessary includes and basic configuration. ```cpp // Include necessary libraries #include // For WiFi connection #include "ESP32MQTTClient.h" // The main MQTT client library // --- WiFi Credentials --- const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; // --- MQTT Broker Details --- const char* mqtt_server = "YOUR_MQTT_BROKER_ADDRESS"; const int mqtt_port = 1883; // Optional: Add username and password if your broker requires authentication // const char* mqtt_user = "YOUR_MQTT_USERNAME"; // const char* mqtt_password = "YOUR_MQTT_PASSWORD"; // --- Callback Functions --- // Define a function to handle incoming messages void messageReceived(const char* topic, const char* payload) { Serial.print("Received message on topic: "); Serial.print(topic); Serial.print(" | Payload: "); Serial.println(payload); } // Define a function to be called when connected to MQTT void onMqttConnect(ESP32MQTTClient client) { Serial.println("MQTT Connected!"); // Subscribe to a topic upon connection if (client.subscribe("esp32/command")) { Serial.println("Subscribed to esp32/command"); } else { Serial.println("Failed to subscribe to esp32/command"); } } // Define a function to be called when disconnected from MQTT void onMqttDisconnect(ESP32MQTTClient client) { Serial.println("MQTT Disconnected!"); // Handle disconnection, e.g., attempt to reconnect } // --- Setup Function --- void setup() { Serial.begin(115200); Serial.println("\nStarting ESP32 MQTT Client Example..."); // --- Connect to WiFi --- Serial.print("Connecting to WiFi..."); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // --- Initialize MQTT Client --- ESP32MQTTClient client; // Set MQTT broker details client.setBroker(mqtt_server, mqtt_port); // If using authentication: // client.setBroker(mqtt_server, mqtt_port, mqtt_user, mqtt_password); // Set callback functions client.onMessage(messageReceived); client.onConnect(onMqttConnect); client.onDisconnect(onMqttDisconnect); // --- Connect to MQTT Broker --- Serial.println("Connecting to MQTT broker..."); if (!client.connect()) { Serial.println("Failed to connect to MQTT broker. Check credentials and server address."); // Handle connection failure (e.g., retry, deep sleep) } } // --- Loop Function --- void loop() { // The ESP32MQTTClient library handles background tasks like // maintaining the connection, processing incoming messages, // and automatic reconnection attempts. // You can add your application logic here. delay(1000); } ``` -------------------------------- ### Basic MQTT Configuration Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/configuration.md Configure the client for a standard MQTT connection. Ensure WiFi is connected before starting the MQTT client. ```cpp #include #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); // Wait for WiFi to connect while (WiFi.status() != WL_CONNECTED) { delay(100); } // Configure MQTT mqttClient.setURL("test.mosquitto.org", 1883); mqttClient.setMqttClientName("ESP32_Client"); mqttClient.enableDebuggingMessages(true); // Start MQTT connection if (mqttClient.loopStart()) { Serial.println("MQTT started"); } } ``` -------------------------------- ### Publish Commands and Monitor Responses with ESP32 MQTT Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/usage-patterns.md This example demonstrates how to set up an ESP32 as an MQTT controller. It subscribes to device status topics and publishes commands to control devices. Ensure the MQTT broker is accessible and devices are configured to listen on the specified topics. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; struct Device { const char *id; const char *commandTopic; const char *statusTopic; }; Device devices[] = { {"light1", "device/light1/cmd", "device/light1/status"}, {"light2", "device/light2/cmd", "device/light2/status"} }; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { // Subscribe to status updates from all devices for (auto &dev : devices) { mqttClient.subscribe(dev.statusTopic, [devId = dev.id](const std::string &status) { Serial.printf("Device %s status: %s\n", devId, status.c_str()); }); } } } void sendCommand(const char *deviceId, const char *command) { char topic[64]; snprintf(topic, sizeof(topic), "device/%s/cmd", deviceId); if (!mqttClient.publish(topic, command)) { Serial.printf("Failed to send command to %s\n", deviceId); } } extern "C" void app_main(void) { mqttClient.setURI("mqtt://broker:1883"); mqttClient.setMqttClientName("ESP32_Controller"); mqttClient.loopStart(); // Wait for connection while (!mqttClient.isConnected()) { vTaskDelay(pdMS_TO_TICKS(100)); } // Send commands sendCommand("light1", "on"); vTaskDelay(pdMS_TO_TICKS(1000)); sendCommand("light2", "on"); vTaskDelay(pdMS_TO_TICKS(1000)); sendCommand("light1", "off"); while (true) { vTaskDelay(pdMS_TO_TICKS(1000)); } } ``` -------------------------------- ### Topic Subscription Callback Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/architecture.md An example of a topic subscription callback using a lambda function. It executes in the MQTT background task context. Avoid long blocking operations and memory allocation. ```cpp mqttClient.subscribe("topic", [](const std::string &payload) { // Executed in MQTT background task context // Safe to call: isConnected(), other publish() to different topics // Avoid: Long blocking operations, memory allocation }); ``` -------------------------------- ### Example Usage of MessageReceivedCallback Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/types.md Demonstrates how to define and use a MessageReceivedCallback for handling incoming MQTT messages when only the payload is required. ```cpp MessageReceivedCallback handler = [](const std::string &message) { Serial.println("Received: " + String(message.c_str())); }; mqttClient.subscribe("sensor/temperature", handler); ``` -------------------------------- ### Inline Getter Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Shows an example of an inline getter method within a class definition, typically placed in a header file for performance. ```cpp inline bool isConnected() const ``` -------------------------------- ### Start Secure MQTT Connection with CA Certificate Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Configures and starts the MQTT client for a secure (TLS) connection using a provided CA certificate for server verification. Includes optional username and password. ```cpp mqttClient.setURL("broker.example.com", 8883, "user", "pass"); mqttClient.setCaCert(caCert); mqttClient.loopStart(); ``` -------------------------------- ### Install ESP32MQTTClient via PlatformIO Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/README.md Add the ESP32MQTTClient library to your PlatformIO project dependencies. This command adds the library from its GitHub repository. ```ini lib_deps = https://github.com/cyijun/ESP32MQTTClient.git ``` -------------------------------- ### Start Secure MQTT Connection with Mutual TLS Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Configures and starts the MQTT client for a secure (TLS) connection using mutual TLS. Requires CA certificate, client certificate, and client key for authentication. ```cpp mqttClient.setURL("broker.example.com", 8883, "user", "pass"); mqttClient.setCaCert(caCert); mqttClient.setClientCert(clientCert); mqttClient.setKey(clientKey); mqttClient.loopStart(); ``` -------------------------------- ### Handle loopStart() With No URI Set Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/errors.md Ensure the broker URI is set using setURI() or setURL() before calling loopStart(). This prevents configuration errors where the client attempts to start without a destination. ```cpp // Always set the URI before calling loopStart() mqttClient.setURI("mqtt://broker:1883", "user", "password"); if (!mqttClient.loopStart()) { ESP_LOGE(TAG, "Failed to start MQTT client"); } ``` -------------------------------- ### TLS/SSL MQTT Client Setup Source: https://github.com/cyijun/esp32mqttclient/blob/main/README.md Configuration for connecting to a TLS/SSL-enabled MQTT broker. Requires setting the broker URL, port, credentials, and CA certificate for verification. ```cpp // For TLS brokers like HiveMQ Cloud const char* caCert = "-----BEGIN CERTIFICATE-----\n..."; void setup() { // ... WiFi setup ... mqttClient.setURL("broker.hivemq.cloud", 8883, "username", "password"); mqttClient.setCaCert(caCert); // Enable TLS verification mqttClient.loopStart(); } ``` -------------------------------- ### MQTT Topic Wildcard Matching Examples Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/architecture.md Demonstrates the usage of `mqttTopicMatch` with various wildcard patterns and topics. Ensure the topic pattern is provided as the first argument and the actual topic as the second. ```cpp mqttTopicMatch("sensors/#", "sensors/temp") // true ``` ```cpp mqttTopicMatch("sensors/+", "sensors/temp") // true ``` ```cpp mqttTopicMatch("sensors/+", "sensors/indoor/temp") // false (+ doesn't cross /) ``` ```cpp mqttTopicMatch("#", "anything/here") // true ``` ```cpp mqttTopicMatch("exact/topic", "exact/topic") // true ``` ```cpp mqttTopicMatch("exact/topic", "exact/other") // false ``` -------------------------------- ### Start MQTT Background Task Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Starts the background task responsible for handling MQTT communication, including connection management, message publishing, and receiving. This must be called after configuration and before other MQTT operations. ```cpp loopStart() ``` -------------------------------- ### Subscribe to Multiple Related Topics with Wildcard Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/usage-patterns.md Use wildcard subscriptions to efficiently subscribe to multiple related topics. This example subscribes to all topics under 'sensors/' and processes temperature and humidity data. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { // Subscribe to all sensor data mqttClient.subscribe("sensors/+", [](const std::string & topic, const std::string & payload) { if (topic == "sensors/temperature") { float temp = std::stof(payload); Serial.printf("Temp: %.1f°C\n", temp); } else if (topic == "sensors/humidity") { float humidity = std::stof(payload); Serial.printf("Humidity: %.1f%%\n", humidity); } }); } } // ... handleMQTT and app_main ... ``` -------------------------------- ### Example Usage of MessageReceivedCallbackWithTopic Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/types.md Shows how to implement and assign a MessageReceivedCallbackWithTopic to handle messages, providing both the topic and payload to the callback. This is suitable for topic-specific subscriptions or the global message callback. ```cpp MessageReceivedCallbackWithTopic handler = [](const std::string &topic, const std::string &message) { ESP_LOGI(TAG, "Topic: %s, Payload: %s", topic.c_str(), message.c_str()); }; mqttClient.subscribe("sensor/#", handler); mqttClient.setOnMessageCallback(handler); ``` -------------------------------- ### Minimal ESP32 MQTT Client Sketch Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md A basic template for an ESP32 project using the MQTT client. It covers WiFi connection, MQTT client setup, event handling, and basic message publishing. Ensure you replace 'SSID' and 'PASS' with your actual WiFi credentials. ```cpp #include #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { mqttClient.subscribe("topic", [](const std::string &payload) { // Handle message }); } } #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) esp_err_t handleMQTT(esp_mqtt_event_handle_t event) { mqttClient.onEventCallback(event); return ESP_OK; } #else void handleMQTT(void *h, esp_event_base_t b, int32_t id, void *d) { mqttClient.onEventCallback((esp_mqtt_event_handle_t)d); } #endif void setup() { WiFi.begin("SSID", "PASS"); while (WiFi.status() != WL_CONNECTED) delay(100); mqttClient.setURL("broker", 1883); mqttClient.setMqttClientName("ESP32"); mqttClient.loopStart(); } void loop() { if (mqttClient.isConnected()) { mqttClient.publish("topic", "payload"); } delay(5000); } ``` -------------------------------- ### Enable Debugging Messages in ESP32MQTTClient Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/errors.md Enable detailed logging to aid in troubleshooting and understanding client behavior. Call this function early in the setup process. ```cpp void setup() { // Enable detailed logging for troubleshooting mqttClient.enableDebuggingMessages(true); mqttClient.setURI("mqtt://broker:1883"); if (!mqttClient.loopStart()) { Serial.println("Failed to start MQTT"); } } ``` -------------------------------- ### Set MQTT Broker URI and Credentials Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Configures the MQTT broker connection using a complete URI string, including optional username and password. Must be called before starting the client loop. ```cpp mqttClient.setURI("mqtt://test.mosquitto.org:1883"); mqttClient.setURI("mqtts://broker.hivemq.cloud:8883", "user", "password"); ``` -------------------------------- ### Validate MQTT Client Configuration Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/configuration.md Checks if essential MQTT client settings like URI and client name are set, and if WiFi is connected before starting the client loop. Call this function before mqttClient.loopStart(). ```cpp bool validateConfiguration() { // Check required settings if (mqttClient.getURI() == nullptr) { Serial.println("ERROR: URI not set"); return false; } if (mqttClient.getClientName() == nullptr) { Serial.println("ERROR: Client name not set"); return false; } // Check WiFi if (WiFi.status() != WL_CONNECTED) { Serial.println("ERROR: WiFi not connected"); return false; } return true; } void setup() { WiFi.begin("SSID", "PASSWORD"); // Configure MQTT mqttClient.setURL("broker.example.com", 1883, "user", "pass"); mqttClient.setMqttClientName("ESP32_Client"); // Validate before starting if (validateConfiguration()) { mqttClient.loopStart(); } else { Serial.println("Configuration invalid"); } } ``` -------------------------------- ### Global MQTT Connect Callback Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/architecture.md Example of a global callback function executed in the MQTT background task context upon connection. Safe operations include subscribe, publish, and isConnected. Avoid WiFi, Serial, and delay. ```cpp void onMqttConnect(esp_mqtt_client_handle_t client) { // Executed in MQTT background task context // Safe to call: subscribe(), publish(), isConnected() // NOT safe to call: WiFi, Serial, delay() } ``` -------------------------------- ### Set MQTT Broker URL and Credentials Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Configures the MQTT broker connection using hostname, port, and optional username/password. Automatically determines the URI scheme based on the port. Must be called before starting the client loop. ```cpp // Connect to plain MQTT broker mqttClient.setURL("broker.example.com", 1883, "user", "pass"); // Connect to secure MQTT broker (TLS) mqttClient.setURL("broker.hivemq.cloud", 8883, "user", "pass"); ``` -------------------------------- ### Initialize ESP32MQTTClient with Default Values Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/configuration.md Instantiate the `ESP32MQTTClient` class to apply all default configuration values. Ensure most settings are configured before calling `loopStart()`. ```cpp ESP32MQTTClient mqttClient; ``` -------------------------------- ### Pointer Validation Example Source: https://github.com/cyijun/esp32mqttclient/blob/main/AGENTS.md Demonstrates a common pattern for validating if a pointer is not null before dereferencing it, preventing potential crashes. ```cpp if (_mqttUri != nullptr) ``` -------------------------------- ### Configuration Methods Source: https://github.com/cyijun/esp32mqttclient/blob/main/README.md Methods for setting up the MQTT client's connection details, security, and operational parameters. ```APIDOC ## Configuration Methods ### `setURL(url, port, username, password)` **Description**: Set broker connection details. ### `setURI(uri, username, password)` **Description**: Set complete MQTT URI. ### `setMqttClientName(name)` **Description**: Set client ID. ### `setCaCert(caCert)` **Description**: Enable TLS with CA certificate. ### `setClientCert(clientCert)` **Description**: Set client certificate. ### `setKey(clientKey)` **Description**: Set client private key. ### `setMaxPacketSize(size)` **Description**: Set maximum packet size (default: 1024). ### `setKeepAlive(seconds)` **Description**: Change keepalive interval (default: 15s). ### `enableLastWillMessage(topic, message, retain)` **Description**: Set last will message. ### `setAutoReconnect(choice)` **Description**: Enable/disable auto-reconnect. ### `disableAutoReconnect()` **Description**: Disable auto-reconnect. ### `enableDebuggingMessages(enabled)` **Description**: Enable debug logging. ``` -------------------------------- ### Set MQTT Client Name Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Sets the client ID string used for the MQTT CONNECT message. This should be called before starting the client loop. ```cpp mqttClient.setMqttClientName("ESP32_Kitchen"); ``` -------------------------------- ### Get MQTT Client Name Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Retrieves the MQTT client ID that was previously set using `setMqttClientName()`. Returns a C-style string or nullptr if not set. ```cpp const char* name = mqttClient.getClientName(); ``` -------------------------------- ### Create ESP32MQTTClient Instance Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Instantiates the ESP32MQTTClient. This must be called before any other methods to initialize the client's internal state. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void setup() { // Configure and use mqttClient } ``` -------------------------------- ### PlatformIO Build Configuration Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Use this configuration in your platformio.ini file to include the ESP32MQTTClient library. ```ini [env:esp32] platform = espressif32 framework = arduino lib_deps = https://github.com/cyijun/ESP32MQTTClient.git ``` -------------------------------- ### ESP32MQTTClient Constructor Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Creates a new MQTT client instance. Initializes all internal state and configuration to default values. Must be called before using any other methods. ```APIDOC ## ESP32MQTTClient() ### Description Creates a new MQTT client instance. Initializes all internal state and configuration to default values. Must be called before using any other methods. ### Parameters None ### Return None ### Example ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void setup() { // Configure and use mqttClient } ``` ``` -------------------------------- ### Handle setURL() URI Buffer Allocation Failure Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/errors.md Check the return value of loopStart() to implicitly verify successful URI allocation and connection. This snippet demonstrates how to handle potential memory allocation failures when setting the broker URL. ```cpp // Check the return value implicitly by verifying connection mqttClient.setURL("broker.example.com", 1883, "user", "pass"); // The URI is only actually used when loopStart() is called if (mqttClient.loopStart()) { ESP_LOGI(TAG, "MQTT started successfully"); } else { ESP_LOGE(TAG, "Failed to start MQTT - check memory"); // Restart or retry later } ``` -------------------------------- ### ESP-IDF CMake Project Configuration Source: https://github.com/cyijun/esp32mqttclient/blob/main/examples/CppEspIdf/CMakeLists.txt Sets the minimum required CMake version and includes the ESP-IDF project setup script. This is essential for any ESP-IDF project using CMake. ```cmake cmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(CppEspIdf) ``` -------------------------------- ### Handle MQTT Connection with onMqttConnect Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/global-callbacks.md Implement this global function to execute code when the MQTT client successfully connects. Use it to subscribe to topics and publish initial status. Always check `isMyTurn(client)` if managing multiple client instances. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; // Global callback - must be outside any class void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { Serial.println("Connected to MQTT broker!"); // Subscribe to topics mqttClient.subscribe("sensor/temperature", [](const std::string &payload) { Serial.printf("Temp: %s\n", payload.c_str()); }); mqttClient.subscribe("commands/#", [](const std::string &topic, const std::string &payload) { Serial.printf("Command from %s: %s\n", topic.c_str(), payload.c_str()); }); // Publish online status mqttClient.publish("device/status", "online", 0, true); } } void setup() { // ... WiFi setup ... mqttClient.setURI("mqtt://broker:1883"); mqttClient.loopStart(); } ``` -------------------------------- ### Set Correct Authentication Credentials Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/errors.md Verify and set the correct username and password before connecting. Consult the broker's documentation for the expected credential format, as some brokers may require specific formats like email addresses. ```cpp // Verify credentials before connecting mqttClient.setURL("broker.example.com", 1883, "correct_user", "correct_pass"); // Check the broker documentation for credential format // Some brokers expect username in email format (user@domain) mqttClient.setURL("broker.example.com", 1883, "user@example.com", "password"); ``` -------------------------------- ### Dynamic Subscription and Unsubscription Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/MANIFEST.txt Shows how to subscribe to and unsubscribe from MQTT topics dynamically during runtime. This is useful for changing data streams or controlling resource usage. ```cpp #include #include "ESP32MQTTClient.h" // WiFi and MQTT credentials (replace with your own) const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; const char* mqtt_server = "YOUR_MQTT_BROKER_ADDRESS"; const int mqtt_port = 1883; const char* topic1 = "data/stream1"; const char* topic2 = "data/stream2"; void messageReceived(const char* topic, const char* payload) { Serial.print("Received on "); Serial.print(topic); Serial.print(": "); Serial.println(payload); } void setup() { Serial.begin(115200); Serial.println("Connecting to WiFi..."); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); ESP32MQTTClient client; client.setBroker(mqtt_server, mqtt_port); client.onMessage(messageReceived); if (client.connect()) { Serial.println("Connected to MQTT broker"); // Subscribe to topic1 if (client.subscribe(topic1)) { Serial.println("Subscribed to " + String(topic1)); } else { Serial.println("Failed to subscribe to " + String(topic1)); } // Simulate a condition to unsubscribe from topic1 and subscribe to topic2 delay(5000); // Unsubscribe from topic1 if (client.unsubscribe(topic1)) { Serial.println("Unsubscribed from " + String(topic1)); } else { Serial.println("Failed to unsubscribe from " + String(topic1)); } // Subscribe to topic2 if (client.subscribe(topic2)) { Serial.println("Subscribed to " + String(topic2)); } else { Serial.println("Failed to subscribe to " + String(topic2)); } } else { Serial.println("Failed to connect to MQTT broker"); } } void loop() { delay(1000); } ``` -------------------------------- ### Set CA Certificate for TLS Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Provides the PEM-formatted CA certificate for verifying the TLS server's identity. Essential for secure connections and must be set before starting the client loop if using TLS. ```cpp const char* caCert = R"(-----BEGIN CERTIFICATE----- MIIDtzCCAp+gAwIBAgIQDOfg5.... -----END CERTIFICATE-----)"; mqttClient.setCaCert(caCert); ``` -------------------------------- ### Get MQTT Broker URI Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/api-reference-classes.md Retrieves the full MQTT broker URI that was configured using `setURI()` or `setURL()`. Returns a C-style string or nullptr if not set. This is useful for logging or debugging connection details. ```cpp const char* uri = mqttClient.getURI(); ESP_LOGI(TAG, "Connected to: %s", uri); ``` -------------------------------- ### Set MQTT Broker URL and Port Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Configures the MQTT broker's host and port. This method should be called before `loopStart()`. ```cpp setURL("mqtt.example.com", 1883) ``` -------------------------------- ### Set Correct MQTT URI Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/errors.md Ensure the MQTT URI format is correct, using 'mqtt://' for standard connections and 'mqtts://' for secure connections. Use setURI() or setURL() with the appropriate broker address and port. ```cpp // Verify URI format: mqtt:// for standard, mqtts:// for secure mqttClient.setURI("mqtt://broker.example.com:1883"); // Correct for port 1883 // mqttClient.setURL("broker.example.com", 1883); // Or use setURL() ``` -------------------------------- ### Set MQTT Broker URI Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/quick-reference.md Configures the MQTT broker using a URI string, which can include authentication. This method should be called before `loopStart()`. ```cpp setURI("mqtt://broker:1883", "user", "pass") ``` -------------------------------- ### Development Configuration (Max Debugging) Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/configuration.md Enable maximum debugging output and set a global message callback for monitoring all MQTT traffic during development. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void setup() { Serial.begin(115200); // Enable all debugging mqttClient.enableDebuggingMessages(true); // Configure connection mqttClient.setURL("test.mosquitto.org", 1883); mqttClient.setMqttClientName("ESP32_Dev"); // Global message callback for monitoring all messages mqttClient.setOnMessageCallback([](const std::string &topic, const std::string &payload) { Serial.printf("[%s] %s\n", topic.c_str(), payload.c_str()); }); if (mqttClient.loopStart()) { Serial.println("✓ MQTT started"); } else { Serial.println("✗ MQTT failed"); } } void setup() { // Monitor connection status if (millis() % 10000 == 0) { Serial.printf("Connected: %s\n", mqttClient.isConnected() ? "yes" : "no"); } } ``` -------------------------------- ### Dynamic MQTT Topic Subscription and Unsubscription Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/usage-patterns.md Demonstrates how to add and remove MQTT subscriptions dynamically after the client has connected. This pattern is useful for managing device-specific topics or commands. ```cpp #include "ESP32MQTTClient.h" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { Serial.println("Connected - ready for subscriptions"); } } // Subscription management functions void subscribeToDevice(const char *deviceId) { char topic[64]; snprintf(topic, sizeof(topic), "devices/%s/command", deviceId); if (mqttClient.subscribe(topic, [deviceId](const std::string &payload) { Serial.printf("Device %s command: %s\n", deviceId, payload.c_str()); })) { Serial.printf("Subscribed to %s\n", topic); } else { Serial.printf("Failed to subscribe to %s\n", topic); } } void unsubscribeFromDevice(const char *deviceId) { char topic[64]; snprintf(topic, sizeof(topic), "devices/%s/command", deviceId); if (mqttClient.unsubscribe(topic)) { Serial.printf("Unsubscribed from %s\n", topic); } } extern "C" void app_main(void) { mqttClient.setURI("mqtt://broker:1883"); mqttClient.setMqttClientName("ESP32_Hub"); mqttClient.loopStart(); // Subscribe to devices as needed vTaskDelay(pdMS_TO_TICKS(2000)); if (mqttClient.isConnected()) { subscribeToDevice("kitchen"); subscribeToDevice("bedroom"); } // Later: unsubscribe vTaskDelay(pdMS_TO_TICKS(10000)); unsubscribeFromDevice("kitchen"); while (true) { vTaskDelay(pdMS_TO_TICKS(1000)); } } ``` -------------------------------- ### Configure ESP32 MQTT Client Component Source: https://github.com/cyijun/esp32mqttclient/blob/main/examples/CppEspIdf/components/ESP32MQTTClient/CMakeLists.txt Register the ESP32 MQTT Client component, specifying its source files, include directories, and its dependency on the MQTT component. ```cmake idf_component_register(SRCS "../../../../src/ESP32MQTTClient.cpp" INCLUDE_DIRS "../../../../src" REQUIRES mqtt) ``` -------------------------------- ### Safe Operations Before loopStart() Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/architecture.md These methods are safe to call from any context as they only read internal state without modification. They are typically used for checking connection status or retrieving client configuration. ```cpp bool isConnected() const; bool isMyTurn(handle) const; const char *getClientName(); const char *getURI(); ``` -------------------------------- ### Version-Aware MQTT Event Handling Source: https://github.com/cyijun/esp32mqttclient/blob/main/_autodocs/global-callbacks.md This snippet demonstrates how to set up MQTT event handlers that are compatible with both ESP-IDF versions prior to 5.0 and version 5.0 and later. It uses preprocessor directives to conditionally compile the correct handler signature. ```cpp #include "ESP32MQTTClient.h" #include "esp_idf_version.h" ESP32MQTTClient mqttClient; void onMqttConnect(esp_mqtt_client_handle_t client) { if (mqttClient.isMyTurn(client)) { // Subscribe and publish as needed mqttClient.subscribe("test/topic", [](const std::string &payload) { ESP_LOGI("APP", "Received: %s", payload.c_str()); }); } } // Version-aware MQTT event handler #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) esp_err_t handleMQTT(esp_mqtt_event_handle_t event) { mqttClient.onEventCallback(event); return ESP_OK; } #else // ESP-IDF v5.x void handleMQTT(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { auto *event = static_cast(event_data); mqttClient.onEventCallback(event); } #endif extern "C" void app_main(void) { // ... initialization code ... mqttClient.setURI("mqtt://broker:1883"); mqttClient.loopStart(); // Main application loop while (true) { vTaskDelay(pdMS_TO_TICKS(1000)); } } ```