### Install via PlatformIO Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Add this dependency to your platformio.ini file for automatic installation. ```ini lib_deps = ArduinoMqtt ``` -------------------------------- ### Implement MQTT Publish and Subscribe on ESP8266 Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt A complete example demonstrating WiFi connection, MQTT client initialization, subscription handling, and periodic data publishing. ```cpp #include #include #define MQTT_LOG_ENABLED 1 #include #define WIFI_SSID "your-ssid" #define WIFI_PASS "your-password" #define MQTT_BROKER "test.mosquitto.org" #define MQTT_PORT 1883 #define MQTT_ID "esp8266-sensor" static MqttClient *mqtt = NULL; static WiFiClient network; const char* TOPIC_PUB = "sensors/esp8266/data"; const char* TOPIC_SUB = "sensors/esp8266/control"; class System: public MqttClient::System { public: unsigned long millis() const { return ::millis(); } void yield(void) { ::yield(); } }; void messageCallback(MqttClient::MessageData& md) { char payload[md.message.payloadLen + 1]; memcpy(payload, md.message.payload, md.message.payloadLen); payload[md.message.payloadLen] = '\0'; Serial.print("Received: "); Serial.println(payload); } void setup() { Serial.begin(115200); // Connect WiFi WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.println("WiFi connected"); // Setup MQTT client MqttClient::System *mqttSystem = new System; MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl(Serial); MqttClient::Network *mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::MessageHandlers *mqttHandlers = new MqttClient::MessageHandlersImpl<2>(); MqttClient::Options mqttOptions; mqttOptions.commandTimeoutMs = 10000; mqtt = new MqttClient(mqttOptions, *mqttLogger, *mqttSystem, *mqttNetwork, *mqttSendBuffer, *mqttRecvBuffer, *mqttHandlers); mqttHandlers->set(TOPIC_SUB, messageCallback); } void loop() { if (!mqtt->isConnected()) { network.stop(); network.connect(MQTT_BROKER, MQTT_PORT); MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = (char*)MQTT_ID; options.cleansession = true; options.keepAliveInterval = 15; MqttClient::ConnectResult result; if (mqtt->connect(options, result) == MqttClient::Error::SUCCESS) { mqtt->subscribe(TOPIC_SUB, MqttClient::QOS0); } } else { // Publish sensor data String payload = "{\"value\":" + String(analogRead(A0)) + "}"; MqttClient::Message msg; msg.qos = MqttClient::QOS0; msg.retained = false; msg.dup = false; msg.payload = (void*)payload.c_str(); msg.payloadLen = payload.length(); mqtt->publish(TOPIC_PUB, msg); mqtt->yield(30000L); } } ``` -------------------------------- ### Instantiate Custom Network Implementation Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Use MqttClient::NetworkImpl to wrap custom network classes that implement read and write methods. This example uses SoftwareSerial for communication. ```c++ #define SW_UART_PIN_RX 10 #define SW_UART_PIN_TX 11 #define SW_UART_SPEED 9600L class Network { public: Network() { mNet = new SoftwareSerial(SW_UART_PIN_RX, SW_UART_PIN_TX); mNet->begin(SW_UART_SPEED); } int read(unsigned char* buffer, int len, unsigned long timeoutMs) { mNet->setTimeout(timeoutMs); return mNet->readBytes((char*) buffer, len); } int write(unsigned char* buffer, int len, unsigned long timeoutMs) { mNet->setTimeout(timeoutMs); for (int i = 0; i < len; ++i) { mNet->write(buffer[i]); } mNet->flush(); return len; } private: SoftwareSerial *mNet; } MqttClient::System *mqttSystem = new System; MqttClient::Network *mqttNetwork = new MqttClient::NetworkImpl(*network, *mqttSystem); ``` -------------------------------- ### Getting Idle Interval Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Returns the time in milliseconds until the next keep-alive transmission is required. Useful for implementing low-power modes. ```APIDOC ## getIdleInterval() ### Description Returns the time in milliseconds until the next keep-alive transmission is required. Useful for implementing low-power modes where the device can sleep between transmissions. ### Method GET (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters None ### Request Example ```cpp void loop() { if (mqtt->isConnected()) { // Get time until next required activity unsigned long idleMs = mqtt->getIdleInterval(); if (idleMs > 1000) { // Safe to sleep for a while Serial.print("Can sleep for "); Serial.print(idleMs); Serial.println(" ms"); // Enter low-power mode (platform specific) // ESP.deepSleep(idleMs * 1000); // microseconds } // Process any pending messages mqtt->yield(100L); } } ``` ### Response #### Success Response (200) - **idleMs** (unsigned long) - The time in milliseconds until the next keep-alive transmission is required. ``` -------------------------------- ### Get MQTT Idle Interval Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Retrieves the time remaining until the next keep-alive packet is required. Useful for optimizing power consumption in sleep modes. ```cpp void loop() { if (mqtt->isConnected()) { // Get time until next required activity unsigned long idleMs = mqtt->getIdleInterval(); if (idleMs > 1000) { // Safe to sleep for a while Serial.print("Can sleep for "); Serial.print(idleMs); Serial.println(" ms"); // Enter low-power mode (platform specific) // ESP.deepSleep(idleMs * 1000); // microseconds } // Process any pending messages mqtt->yield(100L); } } ``` -------------------------------- ### Initialize MqttClient with Dependencies Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Sets up the MqttClient by injecting required dependencies like logger, system interface, network adapter, and buffers. Ensure all dependencies are correctly initialized before creating the client instance. ```cpp #include // System interface for millis() and yield() class System: public MqttClient::System { public: unsigned long millis() const { return ::millis(); } void yield(void) { ::yield(); // Required for ESP8266 } }; // Setup all dependencies MqttClient::System *mqttSystem = new System; MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl(Serial); MqttClient::Network *mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersImpl<2>(); // Configure options MqttClient::Options mqttOptions; mqttOptions.commandTimeoutMs = 10000; // 10 second command timeout // Create MQTT client MqttClient *mqtt = new MqttClient( mqttOptions, *mqttLogger, *mqttSystem, *mqttNetwork, *mqttSendBuffer, *mqttRecvBuffer, *mqttMessageHandlers ); ``` -------------------------------- ### MqttClient Constructor Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Demonstrates how to create a new MQTT client instance by injecting all required dependencies at construction time. This includes setting up system interfaces, network adapters, buffers, and message handlers. ```APIDOC ## MqttClient Constructor Creates a new MQTT client instance with all required dependencies injected at construction time. The client requires a logger, system interface, network adapter, send/receive buffers, and message handlers storage. ### Request Example ```cpp #include // System interface for millis() and yield() class System: public MqttClient::System { public: unsigned long millis() const { return ::millis(); } void yield(void) { ::yield(); // Required for ESP8266 } }; // Setup all dependencies MqttClient::System *mqttSystem = new System; MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl(Serial); MqttClient::Network *mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>(); MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersImpl<2>(); // Configure options MqttClient::Options mqttOptions; mqttOptions.commandTimeoutMs = 10000; // 10 second command timeout // Create MQTT client MqttClient *mqtt = new MqttClient( mqttOptions, *mqttLogger, *mqttSystem, *mqttNetwork, *mqttSendBuffer, *mqttRecvBuffer, *mqttMessageHandlers ); ``` ``` -------------------------------- ### Instantiate Arduino Client Network Implementation Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Use MqttClient::NetworkClientImpl for standard Arduino Client compatible classes like EthernetClient or WiFiClient. ```c++ EthernetClient network; MqttClient::System *mqttSystem = new System; MqttClient::Network * mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); ``` -------------------------------- ### Implement System Interface Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Provide system time access by implementing the MqttClient::System interface. ```c++ class System: public MqttClient::System { public: ... unsigned long millis() const { return ::millis(); } ... } ``` ```c++ #include class TestSystem: public MqttClient::System { ... unsigned long millis() const { return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); } ... ``` -------------------------------- ### Initialize Logger Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Instantiate the logger using the HardwareSerial class for debug output. ```c++ #define HW_UART_SPEED 57600L // Setup hardware serial for logging Serial.begin(HW_UART_SPEED); while (!Serial); // Create MqttClient logger MqttClient::Logger *mqttLogger = new MqttClient::LoggerImpl(Serial); ``` -------------------------------- ### Initialize Message Handlers Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Configure subscription callback storage using different implementation strategies based on memory and allocation requirements. ```c++ // Allows up to 2 subscriptions simultaneously MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersImpl<2>(); ``` ```c++ // Allows up to 2 subscriptions simultaneously // Allows up to 64 bytes for topic string including 1 byte for string termination symbol MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersStaticImpl<2, 64>(); ``` ```c++ // Allows up to 2 subscriptions simultaneously MqttClient::MessageHandlers *mqttMessageHandlers = new MqttClient::MessageHandlersDynamicImpl<2>(); ``` -------------------------------- ### connect() - Basic MQTT Connection Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Establishes a basic MQTT connection to the broker. The TCP connection must be established separately before calling this method. It configures MQTT connection options and returns the connection result. ```APIDOC ## connect() Establishes an MQTT connection to the broker using the provided connection options. Returns error code and populates connect result with session information. TCP connection must be established separately before calling connect. ### Request Example ```cpp // First establish TCP connection WiFiClient network; network.connect("test.mosquitto.org", 1883); if (!network.connected()) { Serial.println("TCP connection failed"); return; } // Configure MQTT connection options MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; // MQTT 3.1.1 options.clientID.cstring = (char*)"my-client-id"; options.cleansession = true; options.keepAliveInterval = 15; // 15 seconds // Connect to MQTT broker MqttClient::ConnectResult connectResult; MqttClient::Error::type rc = mqtt->connect(options, connectResult); if (rc != MqttClient::Error::SUCCESS) { Serial.print("MQTT connection error: "); Serial.println(rc); // Error codes: REFUSED=-2, FAILURE=-1, SUCCESS=0 return; } Serial.println("MQTT connected successfully"); Serial.print("Session present: "); Serial.println(connectResult.sessionPresent); ``` ``` -------------------------------- ### Implement NetworkClientImpl Adapter Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Adapts standard Arduino Client-compatible classes like WiFiClient or EthernetClient for use with the MQTT client. ```cpp #include #include WiFiClient network; // For ESP8266 WiFiClient MqttClient::Network *mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); // For Arduino Ethernet shield // EthernetClient network; // MqttClient::Network *mqttNetwork = new MqttClient::NetworkClientImpl(network, *mqttSystem); ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Registers a message handler before subscribing to a topic pattern. Supports MQTT wildcards for flexible message reception. ```cpp const char* MQTT_TOPIC_SUB = "sensors/+/data"; // Wildcard subscription // First register the message handler void processMessage(MqttClient::MessageData& md) { const MqttClient::Message& msg = md.message; // Extract topic name char topic[64]; memcpy(topic, md.topicName.lenstring.data, md.topicName.lenstring.len); topic[md.topicName.lenstring.len] = '\0'; // Extract payload char payload[msg.payloadLen + 1]; memcpy(payload, msg.payload, msg.payloadLen); payload[msg.payloadLen] = '\0'; Serial.print("Topic: "); Serial.println(topic); Serial.print("Payload: "); Serial.println(payload); Serial.print("QoS: "); Serial.println(msg.qos); } // Register handler before subscribing mqttMessageHandlers->set(MQTT_TOPIC_SUB, processMessage); // Subscribe to topic MqttClient::Error::type rc = mqtt->subscribe(MQTT_TOPIC_SUB, MqttClient::QOS0); if (rc != MqttClient::Error::SUCCESS) { Serial.print("Subscribe error: "); Serial.println(rc); // REFUSED=-2 means broker rejected subscription } ``` -------------------------------- ### Implement NetworkImpl Adapter Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Provides a custom network interface for classes that do not implement the standard Arduino Client interface. ```cpp #include class CustomNetwork { public: CustomNetwork() { serial = new SoftwareSerial(10, 11); // RX, TX serial->begin(9600); } int read(unsigned char* buffer, int len, unsigned long timeoutMs) { serial->setTimeout(timeoutMs); return serial->readBytes((char*)buffer, len); } int write(unsigned char* buffer, int len, unsigned long timeoutMs) { serial->setTimeout(timeoutMs); for (int i = 0; i < len; i++) { serial->write(buffer[i]); } serial->flush(); return len; } private: SoftwareSerial *serial; }; CustomNetwork *customNet = new CustomNetwork; MqttClient::Network *mqttNetwork = new MqttClient::NetworkImpl(*customNet, *mqttSystem); ``` -------------------------------- ### Establish MQTT Connection Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Connects to an MQTT broker after establishing a TCP connection. Configure MQTT connection options including version, client ID, and keep-alive interval. Ensure the TCP connection is successful before attempting to connect to the MQTT broker. ```cpp // First establish TCP connection WiFiClient network; network.connect("test.mosquitto.org", 1883); if (!network.connected()) { Serial.println("TCP connection failed"); return; } // Configure MQTT connection options MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; // MQTT 3.1.1 options.clientID.cstring = (char*)"my-client-id"; options.cleansession = true; options.keepAliveInterval = 15; // 15 seconds // Connect to MQTT broker MqttClient::ConnectResult connectResult; MqttClient::Error::type rc = mqtt->connect(options, connectResult); if (rc != MqttClient::Error::SUCCESS) { Serial.print("MQTT connection error: "); Serial.println(rc); // Error codes: REFUSED=-2, FAILURE=-1, SUCCESS=0 return; } Serial.println("MQTT connected successfully"); Serial.print("Session present: "); Serial.println(connectResult.sessionPresent); ``` -------------------------------- ### Initialize Array Buffers Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Use MqttClient::ArrayBuffer to allocate fixed-size memory for MQTT message transmission and reception. ```c++ // Make 128 bytes send buffer MqttClient::Buffer *mqttSendBuffer = new MqttClient::ArrayBuffer<128>(); // Make 128 bytes receive buffer MqttClient::Buffer *mqttRecvBuffer = new MqttClient::ArrayBuffer<128>(); ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Define the logging macro before including the library header to enable debug output. ```c++ #define MQTT_LOG_ENABLED 1 #include ``` -------------------------------- ### Subscribing to Topics Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Subscribes to a topic pattern to receive messages. Supports MQTT wildcards (+ for single level, # for multi-level). Message handlers must be registered separately. ```APIDOC ## subscribe() ### Description Subscribes to a topic pattern to receive messages. Supports MQTT wildcards (+ for single level, # for multi-level). Message handlers must be registered separately using the MessageHandlers interface. ### Method POST (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters #### Path Parameters - **topic** (const char*) - Required - The MQTT topic pattern to subscribe to. Supports wildcards. - **qos** (MqttClient::QoS) - Required - The desired Quality of Service level for the subscription (e.g., MqttClient::QOS0). ### Request Example ```cpp const char* MQTT_TOPIC_SUB = "sensors/+/data"; // Wildcard subscription // First register the message handler void processMessage(MqttClient::MessageData& md) { const MqttClient::Message& msg = md.message; char topic[64]; memcpy(topic, md.topicName.lenstring.data, md.topicName.lenstring.len); topic[md.topicName.lenstring.len] = '\0'; char payload[msg.payloadLen + 1]; memcpy(payload, msg.payload, msg.payloadLen); payload[msg.payloadLen] = '\0'; Serial.print("Topic: "); Serial.println(topic); Serial.print("Payload: "); Serial.println(payload); Serial.print("QoS: "); Serial.println(msg.qos); } mqttMessageHandlers->set(MQTT_TOPIC_SUB, processMessage); // Subscribe to topic mqtt->subscribe(MQTT_TOPIC_SUB, MqttClient::QOS0); ``` ### Response #### Success Response (200) Returns MqttClient::Error::SUCCESS upon successful subscription. #### Error Response - **MqttClient::Error::REFUSED** (-2) - Broker rejected subscription. ``` -------------------------------- ### Configure MessageHandlersStaticImpl Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Preallocates buffers for topic strings to avoid heap fragmentation during subscription calls. ```cpp // Allow 3 subscriptions with topics up to 64 characters each MqttClient::MessageHandlers *handlers = new MqttClient::MessageHandlersStaticImpl<3, 64>(); handlers->set("home/livingroom/temperature", processTemp); handlers->set("home/livingroom/humidity", processHumidity); // Topic string is copied into preallocated buffer ``` -------------------------------- ### Implement System Yield Source: https://github.com/monstrenyatko/arduinomqtt/blob/master/README.md Implement the yield method to maintain system stability, such as resetting the watchdog timer on ESP8266. ```c++ class System: public MqttClient::System { public: ... void yield(void) { ::yield(); } ... ``` -------------------------------- ### Manage Subscriptions with MessageHandlersImpl Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Stores subscription callbacks with a fixed maximum number of simultaneous subscriptions. ```cpp // Allow up to 5 simultaneous subscriptions MqttClient::MessageHandlers *handlers = new MqttClient::MessageHandlersImpl<5>(); // Register handlers handlers->set("sensors/temp", tempCallback); handlers->set("sensors/humidity", humidityCallback); handlers->set("control/#", controlCallback); // Check if full if (handlers->isFull()) { Serial.println("No more subscription slots available"); } // Remove specific handler handlers->reset("sensors/temp"); // Remove all handlers handlers->reset(); ``` -------------------------------- ### Publish MQTT Messages Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Publishes a message to a topic with configurable QoS and retain settings. Check the return code for common network or encoding failures. ```cpp const char* MQTT_TOPIC_PUB = "sensors/temperature"; // Prepare message payload const char* payload = "{\"temp\": 23.5, \"unit\": \"celsius\"}"; MqttClient::Message message; message.qos = MqttClient::QOS1; // QOS0, QOS1, or QOS2 message.retained = false; // Don't retain message on broker message.dup = false; // Not a duplicate message.payload = (void*)payload; message.payloadLen = strlen(payload); // Publish message MqttClient::Error::type rc = mqtt->publish(MQTT_TOPIC_PUB, message); if (rc != MqttClient::Error::SUCCESS) { Serial.print("Publish failed with error: "); Serial.println(rc); // Common errors: // FAILURE=-1 (not connected) // ENCODING_FAILURE=-3 (buffer too small) // NETWORK_FAILURE=-5 (transmission error) // WAIT_TIMEOUT=-6 (no ACK for QoS1/2) } ``` -------------------------------- ### Unsubscribe from MQTT Topics Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Removes a subscription and its associated message handler. The topic string must match the original subscription exactly. ```cpp const char* MQTT_TOPIC_SUB = "sensors/temperature"; MqttClient::Error::type rc = mqtt->unsubscribe(MQTT_TOPIC_SUB); if (rc == MqttClient::Error::SUCCESS) { Serial.println("Unsubscribed successfully"); // Also remove the message handler mqttMessageHandlers->reset(MQTT_TOPIC_SUB); } ``` -------------------------------- ### connect() - With Last Will and Testament (LWT) Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Connects to the MQTT broker with a Last Will message configured. This message is published automatically if the client disconnects unexpectedly, which is useful for presence detection and status monitoring. ```APIDOC ## connect() with Last Will and Testament (LWT) Connects to the broker with a Last Will message that gets published automatically if the client disconnects unexpectedly. Useful for device presence detection and status monitoring. ### Request Example ```cpp char MQTT_TOPIC_STATUS[] = "devices/sensor-01/status"; MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = (char*)"sensor-01"; options.cleansession = true; options.keepAliveInterval = 15; // Configure Last Will and Testament options.willFlag = true; options.will.topicName.cstring = MQTT_TOPIC_STATUS; options.will.message.cstring = const_cast("offline"); options.will.retained = true; options.will.qos = MqttClient::QOS0; MqttClient::ConnectResult connectResult; MqttClient::Error::type rc = mqtt->connect(options, connectResult); if (rc == MqttClient::Error::SUCCESS) { // Publish online status const char* buf = "online"; MqttClient::Message message; message.qos = MqttClient::QOS0; message.retained = true; message.dup = false; message.payload = (void*)buf; message.payloadLen = strlen(buf) + 1; mqtt->publish(MQTT_TOPIC_STATUS, message); } ``` ``` -------------------------------- ### Define Transmission Buffers with ArrayBuffer Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Allocates fixed-size memory for MQTT packet transmission and reception. ```cpp // Create buffers for send and receive MqttClient::Buffer *sendBuffer = new MqttClient::ArrayBuffer<256>(); // 256 bytes MqttClient::Buffer *recvBuffer = new MqttClient::ArrayBuffer<512>(); // 512 bytes for larger incoming messages // Buffer sizes should account for: // - MQTT fixed header (2-5 bytes) // - Variable header (topic + packet ID) // - Payload data ``` -------------------------------- ### Check MQTT Connection Status Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Use isConnected() to verify the broker connection and trigger reconnection logic if the connection is lost. ```cpp void loop() { if (!mqtt->isConnected()) { Serial.println("Connection lost, reconnecting..."); // Close existing TCP connection network.stop(); // Re-establish TCP connection network.connect("broker.example.com", 1883); // Reconnect MQTT MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = (char*)"my-client"; options.cleansession = true; options.keepAliveInterval = 15; MqttClient::ConnectResult result; mqtt->connect(options, result); } mqtt->yield(1000L); } ``` -------------------------------- ### Connect with Last Will and Testament (LWT) Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Connects to the MQTT broker with a Last Will message. This message is published if the client disconnects unexpectedly, useful for status monitoring. The client also publishes an 'online' status message upon successful connection. ```cpp char MQTT_TOPIC_STATUS[] = "devices/sensor-01/status"; MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = (char*)"sensor-01"; options.cleansession = true; options.keepAliveInterval = 15; // Configure Last Will and Testament options.willFlag = true; options.will.topicName.cstring = MQTT_TOPIC_STATUS; options.will.message.cstring = const_castconnect(options, connectResult); if (rc == MqttClient::Error::SUCCESS) { // Publish online status const char* buf = "online"; MqttClient::Message message; message.qos = MqttClient::QOS0; message.retained = true; message.dup = false; message.payload = (void*)buf; message.payloadLen = strlen(buf) + 1; mqtt->publish(MQTT_TOPIC_STATUS, message); } ``` -------------------------------- ### Publishing Messages Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Publishes a message to a specified topic with configurable QoS level and retain flag. Supports QoS 0 (fire and forget), QoS 1 (at least once), and QoS 2 (exactly once). ```APIDOC ## publish() ### Description Publishes a message to a specified topic with configurable QoS level and retain flag. Supports QoS 0 (fire and forget), QoS 1 (at least once), and QoS 2 (exactly once). ### Method POST (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters #### Request Body - **topic** (const char*) - Required - The MQTT topic to publish to. - **message** (MqttClient::Message) - Required - An object containing the message payload, QoS level, and retain flag. - **qos** (MqttClient::QoS) - Required - Quality of Service level (QOS0, QOS1, QOS2). - **retained** (bool) - Required - Whether the message should be retained by the broker. - **dup** (bool) - Required - Whether the message is a duplicate. - **payload** (void*) - Required - Pointer to the message payload. - **payloadLen** (size_t) - Required - Length of the message payload. ### Request Example ```cpp const char* MQTT_TOPIC_PUB = "sensors/temperature"; const char* payload = "{\"temp\": 23.5, \"unit\": \"celsius\"}"; MqttClient::Message message; message.qos = MqttClient::QOS1; message.retained = false; message.dup = false; message.payload = (void*)payload; message.payloadLen = strlen(payload); mqtt->publish(MQTT_TOPIC_PUB, message); ``` ### Response #### Success Response (200) Returns MqttClient::Error::SUCCESS upon successful publication. #### Error Response - **MqttClient::Error::FAILURE** (-1) - Not connected. - **MqttClient::Error::ENCODING_FAILURE** (-3) - Buffer too small. - **MqttClient::Error::NETWORK_FAILURE** (-5) - Transmission error. - **MqttClient::Error::WAIT_TIMEOUT** (-6) - No ACK for QoS1/2. ``` -------------------------------- ### Process MQTT Yield Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Maintains the connection and processes incoming messages. Must be called regularly within the main loop. ```cpp void loop() { if (mqtt->isConnected()) { // Process messages and keep-alive for 1 second mqtt->yield(1000L); // Do other work here readSensors(); // Process messages for longer period when idle mqtt->yield(30000L); // 30 seconds } } ``` -------------------------------- ### Unsubscribing from Topics Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Unsubscribes from a previously subscribed topic. The topic string must match exactly the one used in the subscribe call. ```APIDOC ## unsubscribe() ### Description Unsubscribes from a previously subscribed topic. The topic string must match exactly the one used in the subscribe call. ### Method DELETE (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters #### Path Parameters - **topic** (const char*) - Required - The MQTT topic to unsubscribe from. Must match the subscribed topic exactly. ### Request Example ```cpp const char* MQTT_TOPIC_SUB = "sensors/temperature"; mqtt->unsubscribe(MQTT_TOPIC_SUB); // Also remove the message handler mqttMessageHandlers->reset(MQTT_TOPIC_SUB); ``` ### Response #### Success Response (200) Returns MqttClient::Error::SUCCESS upon successful unsubscription. #### Error Response - Other error codes may indicate issues during the unsubscription process. ``` -------------------------------- ### Processing Network Events Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Processes incoming messages and sends keep-alive packets. Must be called regularly to maintain the connection and receive subscription messages. ```APIDOC ## yield() ### Description Processes incoming messages and sends keep-alive packets. Must be called regularly to maintain the connection and receive subscription messages. Blocks for the specified timeout period. ### Method GET (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters #### Query Parameters - **timeoutMs** (long) - Required - The maximum time in milliseconds to wait for network activity. ### Request Example ```cpp void loop() { if (mqtt->isConnected()) { // Process messages and keep-alive for 1 second mqtt->yield(1000L); // Do other work here readSensors(); // Process messages for longer period when idle mqtt->yield(30000L); // 30 seconds } } ``` ### Response No specific return value for successful processing, but it handles incoming messages and keep-alives. ``` -------------------------------- ### Disconnecting from Broker Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Gracefully disconnects from the MQTT broker by sending a DISCONNECT packet. The TCP connection should be closed separately. ```APIDOC ## disconnect() ### Description Gracefully disconnects from the MQTT broker by sending a DISCONNECT packet. The TCP connection should be closed separately after calling disconnect. ### Method POST (conceptual, actual implementation is library specific) ### Endpoint N/A (library function) ### Parameters None ### Request Example ```cpp // Gracefully disconnect from MQTT mqtt->disconnect(); // Close TCP connection network.stop(); ``` ### Response #### Success Response (200) Returns MqttClient::Error::SUCCESS upon successful disconnection. #### Error Response - Other error codes may indicate issues during the disconnection process. ``` -------------------------------- ### Disconnect from MQTT Broker Source: https://context7.com/monstrenyatko/arduinomqtt/llms.txt Sends a DISCONNECT packet to the broker. The underlying TCP connection should be closed manually after this call. ```cpp // Gracefully disconnect from MQTT MqttClient::Error::type rc = mqtt->disconnect(); if (rc == MqttClient::Error::SUCCESS) { Serial.println("MQTT disconnected"); } // Close TCP connection network.stop(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.