### Basic WiFi Sender Example Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/MANIFEST.txt A simple example demonstrating how to send messages over WiFi using the ArduinoMqttClient library. This snippet is suitable for basic publishing tasks. ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(wifiClient); void setup() { Serial.begin(115200); while (!Serial) { ; } Serial.println("Connecting to WiFi..."); if (WiFi.begin("SSID", "PASSWORD") == WL_CONNECTED) { Serial.println("Connected to WiFi"); } Serial.println("Connecting to MQTT broker..."); if (mqttClient.connect("broker.hivemq.com", 1883)) { Serial.println("Connected to MQTT broker"); } mqttClient.beginMessage("my/topic"); mqttClient.print("Hello from Arduino!"); mqttClient.endMessage(); } void loop() { // Nothing to do here for this example } ``` -------------------------------- ### ArduinoMqttClient Quick Reference Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Demonstrates the basic setup, configuration, connection, subscription, and polling loop for the MqttClient. ```cpp #include // Create client MqttClient mqttClient(wifiClient); // Configure mqttClient.setId("device-01"); mqttClient.setUsernamePassword("user", "pass"); // Connect if (mqttClient.connect("broker.example.com", 1883)) { mqttClient.subscribe("home/status"); mqttClient.onMessage(onMessage); } // Main loop void loop() { mqttClient.poll(); } // Callback void onMessage(int size) { String topic = mqttClient.messageTopic(); // Process message } ``` -------------------------------- ### Home Temperature Monitor Example Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/usage-patterns.md This example demonstrates a complete home temperature monitor using WiFi and MQTT. It covers connection management, periodic sensor readings, publishing data, subscribing to configuration topics, and handling offline status with will messages. ```cpp #include #include // WiFi and MQTT configuration const char *ssid = "MySSID"; const char *password = "MyPassword"; const char *broker = "broker.example.com"; const int brokerPort = 1883; // Topic structure const char *statusTopic = "home/tempmonitor/status"; const char *dataTopic = "home/tempmonitor/temperature"; const char *configTopic = "home/tempmonitor/config"; // Network objects WiFiClient wifiClient; MqttClient mqttClient(wifiClient); // Device state bool isEnabled = true; unsigned long lastMeasure = 0; unsigned long measureInterval = 5000; // 5 seconds void setup() { Serial.begin(115200); delay(1000); Serial.println("\nStarting Temperature Monitor"); // Configure timeouts for WiFi mqttClient.setConnectionTimeout(10000); mqttClient.setKeepAliveInterval(60000); // Connect to WiFi connectWiFi(); // Connect to MQTT connectMQTT(); // Subscribe to configuration topic mqttClient.subscribe(configTopic, 1); // Publish initial status publishStatus("online"); } void loop() { // Maintain connections if (WiFi.status() != WL_CONNECTED) { connectWiFi(); } if (!mqttClient.connected()) { connectMQTT(); } else { // Process incoming messages mqttClient.poll(); // Publish temperature measurements if (isEnabled && millis() - lastMeasure >= measureInterval) { lastMeasure = millis(); publishTemperature(); } } delay(100); } void connectWiFi() { if (WiFi.status() == WL_CONNECTED) return; Serial.print("Connecting to WiFi: "); Serial.println(ssid); WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 20) { delay(500); Serial.print("."); attempts++; } if (WiFi.status() == WL_CONNECTED) { Serial.println(" Connected!"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } else { Serial.println(" Failed!"); } } void connectMQTT() { if (mqttClient.connected()) return; Serial.print("Connecting to MQTT broker: "); Serial.println(broker); // Configure client mqttClient.setId("tempmonitor-001"); // Set will message mqttClient.beginWill(statusTopic, 10, true, 0); mqttClient.print("offline"); mqttClient.endWill(); if (!mqttClient.connect(broker, brokerPort)) { Serial.print("Connection failed! Error: "); Serial.println(mqttClient.connectError()); return; } Serial.println("Connected to MQTT!"); // Resubscribe after reconnection mqttClient.subscribe(configTopic, 1); publishStatus("online"); } void publishTemperature() { // Read temperature (simulated) float temp = 20.0 + (analogRead(A0) / 1024.0) * 10.0; Serial.print("Publishing temperature: "); Serial.println(temp); mqttClient.beginMessage(dataTopic, false, 0); mqttClient.print(temp, 2); mqttClient.endMessage(); } void publishStatus(const char *status) { mqttClient.beginMessage(statusTopic, true, 0); mqttClient.print(status); mqttClient.endMessage(); } // Handle incoming configuration messages void handleIncomingMessage() { int messageSize = mqttClient.parseMessage(); if (messageSize > 0) { String topic = mqttClient.messageTopic(); String payload = ""; while (mqttClient.available()) { payload += (char)mqttClient.read(); } Serial.print("Message from "); Serial.print(topic); Serial.print(": "); Serial.println(payload); if (topic == configTopic) { if (payload == "start") { isEnabled = true; publishStatus("measuring"); } else if (payload == "stop") { isEnabled = false; publishStatus("paused"); } } } } ``` -------------------------------- ### Simple Publisher Example Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Shows how to publish sensor data periodically within the main loop, including MQTT client polling. ```cpp void loop() { mqttClient.poll(); if (millis() - lastPub > 5000) { lastPub = millis(); mqttClient.beginMessage("sensor/temp"); mqttClient.print(getTemperature()); mqttClient.endMessage(); } } ``` -------------------------------- ### Example: Publish a simple test message Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md A basic example of publishing a string message. It begins the message, writes the string content, and then calls endMessage(), checking for success. ```cpp mqttClient.beginMessage("test/topic"); mqttClient.print("Test message"); if (!mqttClient.endMessage()) { Serial.println("Failed to send message"); } ``` -------------------------------- ### Install ArduinoMqttClient and Network Client Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Include the necessary libraries for MQTT and network communication. Ensure you have a network client like WiFiClient available. ```cpp #include #include // or other network client // Create WiFi client WiFiClient wifiClient; // Create MQTT client MqttClient mqttClient(wifiClient); ``` -------------------------------- ### beginMessage() Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Starts the process of publishing a new MQTT message. ```APIDOC ## beginMessage() ### Description Initiates the construction of a new MQTT message to be published. This must be followed by calls to `write()` or `print()` for the payload, and finally `endMessage()`. ### Method POST (Conceptual - this is an SDK method, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `topic` (String): The topic to which the message will be published. - `qos` (int, optional): The Quality of Service level (0, 1, or 2). Defaults to 0. - `retain` (bool, optional): Whether the message should be retained by the broker. Defaults to false. ### Request Example ```cpp mqttClient.beginMessage("home/temperature", 1, true); ``` ### Response #### Success Response (1) - Returns `1` (true) if the message header was successfully prepared. #### Error Response (0) - Returns `0` (false) if preparation failed (e.g., buffer full, not connected). #### Response Example ``` 1 ``` ``` -------------------------------- ### Example: Device Status Will Message Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/configuration.md This example demonstrates how to configure a will message to report a device's 'disconnected' status to the broker upon an unexpected disconnect. It also shows how to publish an 'online' status while connected. ```cpp void setup() { // Tell broker client is offline if unexpected disconnect occurs mqttClient.beginWill("home/devices/sensor1/status", 10, true, 0); mqttClient.print("disconnected"); mqttClient.endWill(); if (!mqttClient.connect("broker.local", 1883)) { Serial.println("Failed to connect"); } } void loop() { mqttClient.poll(); // Publish online status while connected static unsigned long lastStatus = 0; if (millis() - lastStatus > 60000) { lastStatus = millis(); mqttClient.beginMessage("home/devices/sensor1/status"); mqttClient.print("online"); mqttClient.endMessage(); } } // If device crashes or loses power: // Broker publishes to "home/devices/sensor1/status" with payload "disconnected" ``` -------------------------------- ### Complete Arduino MQTT Client Configuration Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/configuration.md This example demonstrates setting up a client ID, authentication, session persistence, connection timeouts, transmit buffer size, and a will message. It also includes WiFi connection and initial subscription logic. ```cpp #include #include #include "arduino_secrets.h" // Contains SECRET_SSID, SECRET_PASS, etc. WiFiClient wifiClient; MqttClient mqttClient(wifiClient); void configureClient() { Serial.println("Configuring MQTT client..."); // 1. Set client identifier String clientId = "arduino_"; clientId += WiFi.macAddress(); clientId.replace(":", ""); mqttClient.setId(clientId); Serial.print(" Client ID: "); Serial.println(clientId); // 2. Set authentication (if broker requires it) mqttClient.setUsernamePassword(SECRET_USERNAME, SECRET_PASSWORD); Serial.println(" Credentials configured"); // 3. Configure session behavior // Use persistent session to maintain subscriptions across disconnects mqttClient.setCleanSession(false); Serial.println(" Session: Persistent"); // 4. Set timeouts based on network if (isSlowNetwork()) { mqttClient.setConnectionTimeout(60000); // 60 seconds mqttClient.setKeepAliveInterval(120000); // 2 minutes } else { mqttClient.setConnectionTimeout(10000); // 10 seconds mqttClient.setKeepAliveInterval(60000); // 1 minute } Serial.println(" Timeouts configured"); // 5. Configure message buffer for streaming publishes mqttClient.setTxPayloadSize(512); Serial.println(" TX buffer: 512 bytes"); // 6. Set will message (status indicator) mqttClient.beginWill("devices/arduino/status", 10, true, 0); mqttClient.print("offline"); mqttClient.endWill(); Serial.println(" Will message configured"); Serial.println("Configuration complete."); } bool isSlowNetwork() { // Simple heuristic based on board type #if defined(__AVR__) return true; // ATmega boards often have slower connections #else return false; // Modern boards typically have fast WiFi #endif } void setup() { Serial.begin(115200); delay(1000); // Connect to WiFi first WiFi.begin(SECRET_SSID, SECRET_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected!"); // Configure MQTT client configureClient(); // Attempt connection Serial.print("Connecting to MQTT broker: "); Serial.println(SECRET_MQTT_BROKER); if (mqttClient.connect(SECRET_MQTT_BROKER, 1883)) { Serial.println("Connected!"); // Subscribe to topics mqttClient.subscribe("home/commands/#", 1); } else { Serial.print("Failed! Error code: "); Serial.println(mqttClient.connectError()); } } void loop() { // Reconnect if needed if (!mqttClient.connected()) { if (mqttClient.connect(SECRET_MQTT_BROKER, 1883)) { Serial.println("Reconnected to MQTT"); mqttClient.subscribe("home/commands/#", 1); } } else { // Essential: Poll for messages mqttClient.poll(); } } ``` -------------------------------- ### Typical Arduino MQTT Client Usage Flow Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Demonstrates a complete usage flow for the Arduino MQTT client library, including setup, connection, message handling, and publishing. ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(wifiClient); void setup() { Serial.begin(9600); // Configure connection mqttClient.setId("arduino-01"); mqttClient.setUsernamePassword("user", "pass"); mqttClient.setKeepAliveInterval(60000); // Set up will message mqttClient.beginWill("arduino/status", false, 0); mqttClient.print("offline"); mqttClient.endWill(); // Register message callback mqttClient.onMessage(onMessage); // Connect if (!mqttClient.connect("broker.example.com", 1883)) { Serial.println("Connection failed!"); } // Subscribe to topics mqttClient.subscribe("home/temperature"); mqttClient.subscribe("home/alerts"); } void loop() { // Essential: call poll regularly mqttClient.poll(); // Publish periodically static unsigned long lastPublish = 0; if (millis() - lastPublish > 10000) { lastPublish = millis(); mqttClient.beginMessage("arduino/uptime"); mqttClient.print(millis()); mqttClient.endMessage(); } } void onMessage(int messageSize) { String topic = mqttClient.messageTopic(); Serial.print("Message from: "); Serial.println(topic); while (mqttClient.available()) { Serial.print((char)mqttClient.read()); } Serial.println(); } ``` -------------------------------- ### Example: Publish a message with known size Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Demonstrates publishing a message with a predefined payload size. The message content is written using print() and then sent with endMessage(). ```cpp if (mqttClient.beginMessage("sensor/temperature", 5)) { mqttClient.print("23.5"); mqttClient.endMessage(); } ``` -------------------------------- ### beginWill Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/configuration.md Starts the configuration of a will message. This method must be called before connecting to the MQTT broker. After calling `beginWill`, you should print the will message payload and then call `endWill` before calling `connect`. ```APIDOC ## beginWill(const char* topic, unsigned short size, bool retain, uint8_t qos) ### Description Starts configuring a will message. This message will be published by the broker if the client disconnects unexpectedly. ### Method Signature `int beginWill(const char* topic, unsigned short size, bool retain, uint8_t qos)` ### Parameters #### Path Parameters - **topic** (const char*) - The topic where the will message will be published. - **size** (unsigned short) - The maximum payload size for the will message. - **retain** (bool) - Whether the broker should retain this message after publishing. - **qos** (uint8_t) - The Quality of Service level for the message (0, 1, or 2). ### Returns - 0 on success. ### Must Call Before - `connect()` ### Usage Pattern ```cpp // Configure will message BEFORE connecting mqttClient.beginWill("arduino/status", 10, true, 0); mqttClient.print("offline"); mqttClient.endWill(); // Then connect mqttClient.connect(broker, port); ``` ### Example - Device Status Will ```cpp void setup() { // Tell broker client is offline if unexpected disconnect occurs mqttClient.beginWill("home/devices/sensor1/status", 10, true, 0); mqttClient.print("disconnected"); mqttClient.endWill(); if (!mqttClient.connect("broker.local", 1883)) { Serial.println("Failed to connect"); } } void loop() { mqttClient.poll(); // Publish online status while connected static unsigned long lastStatus = 0; if (millis() - lastStatus > 60000) { lastStatus = millis(); mqttClient.beginMessage("home/devices/sensor1/status"); mqttClient.print("online"); mqttClient.endMessage(); } } // If device crashes or loses power: // Broker publishes to "home/devices/sensor1/status" with payload "disconnected" ``` ``` -------------------------------- ### Example: Publish binary data Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Shows how to publish binary data by writing a byte buffer to the message payload using the write() method. Ensure endMessage() is called to complete the publish. ```cpp uint8_t data[] = {0x01, 0x02, 0x03}; mqttClient.beginMessage("sensor/binary"); mqttClient.write(data, 3); mqttClient.endMessage(); ``` -------------------------------- ### Handle MQTT Subscribe/Unsubscribe Failures Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/errors.md The subscribe() and unsubscribe() methods return 0 on failure. This example shows how to check for subscription failures and includes logic to reconnect and retry if necessary. ```cpp if (mqttClient.subscribe("home/temperature", 0) == 0) { Serial.println("Subscription failed"); // Possible causes: // - Connection dropped during subscription // - Broker not responding (timeout) // - Invalid topic format // - QoS value > 2 // Reconnect and retry if (mqttClient.connect(broker, port)) { mqttClient.subscribe("home/temperature"); } } ``` -------------------------------- ### Example: Publish a message with streaming payload Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Illustrates publishing a message with a streaming payload where the size is determined during the write operations. Multiple print() calls are used before calling endMessage(). ```cpp // Streaming publish - size determined during write mqttClient.beginMessage("arduino/data"); mqttClient.print("Line1\n"); mqttClient.print("Line2\n"); mqttClient.endMessage(); ``` -------------------------------- ### Get Last Connection Error Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Retrieves the error code from the last connection attempt. ```APIDOC ## connectError() ### Description Retrieves the error code from the last connection attempt. ### Method `int connectError() const` ### Response #### Success Response - **Returns:** Error code (see Error Codes section) ### Error Codes - `MQTT_SUCCESS` (0): No error - `MQTT_CONNECTION_REFUSED` (-2): Connection refused by broker - `MQTT_CONNECTION_TIMEOUT` (-1): Connection timed out - `MQTT_UNACCEPTABLE_PROTOCOL_VERSION` (1): Broker rejected protocol version - `MQTT_IDENTIFIER_REJECTED` (2): Broker rejected client identifier - `MQTT_SERVER_UNAVAILABLE` (3): Server unavailable - `MQTT_BAD_USER_NAME_OR_PASSWORD` (4): Authentication failure - `MQTT_NOT_AUTHORIZED` (5): Authorization failure ### Request Example ```cpp if (!mqttClient.connect(broker, port)) { int errorCode = mqttClient.connectError(); if (errorCode == MQTT_NOT_AUTHORIZED) { Serial.println("Check username and password"); } } ``` ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Configure optional client settings like ID and credentials, then establish a connection to the MQTT broker. Check the connection status. ```cpp // Configure (optional) mqttClient.setId("my-device"); mqttClient.setUsernamePassword("user", "password"); // Connect if (!mqttClient.connect("broker.example.com", 1883)) { Serial.println("Connection failed!"); } ``` -------------------------------- ### Publishing and Subscribing with QoS Levels Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Demonstrates how to publish messages with different QoS levels (0 and 1) and subscribe to a topic with a maximum QoS level (2). QoS 0 is for fast, fire-and-forget messages. QoS 1 guarantees delivery but may result in duplicates. QoS 2 offers the highest reliability. ```cpp // Publish with QoS 0 (fastest, no confirmation) mqttClient.beginMessage("sensor/temp", false, 0); mqttClient.print("23.5"); mqttClient.endMessage(); // Publish with QoS 1 (guaranteed, blocks until acknowledged) mqttClient.beginMessage("alert/critical", false, 1); mqttClient.print("ALERT: Temperature above threshold!"); mqttClient.endMessage(); // Subscribe with maximum QoS 2 (highest reliability) mqttClient.subscribe("commands/critical", 2); ``` -------------------------------- ### Get Granted QoS Level Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Retrieves the QoS level granted by the broker for the most recent subscription. Returns 0x80 if the subscription is still pending. ```cpp int subscribeQoS() const ``` ```cpp mqttClient.subscribe("sensor/data"); int grantedQos = mqttClient.subscribeQoS(); Serial.print("Broker granted QoS: "); Serial.println(grantedQos); ``` -------------------------------- ### connect() Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Establishes a connection to the MQTT broker. ```APIDOC ## connect() ### Description Attempts to establish a connection to the MQTT broker using the configured host and port. ### Method POST (Conceptual - this is an SDK method, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `host` (String): The hostname or IP address of the MQTT broker. - `port` (int): The port number for the MQTT broker (typically 1883 for unencrypted, 8883 for TLS). ### Request Example ```cpp if (mqttClient.connect("broker.example.com", 1883)) { Serial.println("Connected to broker"); } else { Serial.println("Connection failed"); } ``` ### Response #### Success Response (1) - Returns `1` (true) if the connection was successful. #### Error Response (0) - Returns `0` (false) if the connection failed. #### Response Example ``` 1 ``` ``` -------------------------------- ### Simple WiFi Receiver with Callback Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/MANIFEST.txt Demonstrates setting up a basic MQTT subscriber that uses a callback function to handle incoming messages. This is useful for real-time message processing. ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(wifiClient); void messageReceived(const String& topic, const String& payload) { Serial.print("Received message on topic "); Serial.print(topic); Serial.print(": "); Serial.println(payload); } void setup() { Serial.begin(115200); while (!Serial) { ; } Serial.println("Connecting to WiFi..."); if (WiFi.begin("SSID", "PASSWORD") == WL_CONNECTED) { Serial.println("Connected to WiFi"); } Serial.println("Connecting to MQTT broker..."); if (mqttClient.connect("broker.hivemq.com", 1883)) { Serial.println("Connected to MQTT broker"); } mqttClient.subscribe("my/topic", "messageReceived"); } void loop() { mqttClient.poll(); } ``` -------------------------------- ### Constructor Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Initializes the MqttClient with a given Client object, either by pointer or reference. ```APIDOC ## Constructor ### Description Initializes the MqttClient with a given Client object. ### Parameters #### Constructor Parameters - `client` (*Client*) - Pointer to the Client object. - `client` (*Client*) - Reference to the Client object. ``` -------------------------------- ### Get MQTT Message Topic Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Retrieve the topic of the most recently parsed MQTT message using `messageTopic()`. This function is only valid after `parseMessage()` has returned a value greater than 0. ```cpp String messageTopic() const { // ... implementation details ... } ``` ```cpp if (mqttClient.parseMessage() > 0) { String topic = mqttClient.messageTopic(); Serial.println(topic); } ``` -------------------------------- ### Begin MQTT Message with QoS Level Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Initiate a new MQTT message with a specified topic and QoS level. QoS level 2 ensures exactly-once delivery. ```cpp mqttClient.beginMessage(topic, false, 2) ``` -------------------------------- ### Error Codes Reference Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/MANIFEST.txt This section provides a detailed reference for all 8 error codes, including their trigger conditions, and examples for handling errors during connection, subscription, and message publishing. ```APIDOC ## Error Codes Reference This section details the error codes and strategies for handling them. ### Error Codes (8 total) Each error code is described with its specific trigger conditions. ### Error Handling Examples - **Connection Error Checking**: Example demonstrating how to check for connection errors. - **Subscribe/Unsubscribe Error Handling**: Example for handling errors during subscription operations. - **Message Publishing Error Handling**: Example for managing errors during message publishing. - **QoS Acknowledgment Timeout Handling**: Example for dealing with timeouts in QoS acknowledgments. ### Debugging Strategies - **4 Debugging Patterns**: Recommended approaches for debugging issues. ### Common Issues and Solutions - **4 Detailed Issues**: Common problems and their resolutions. ### Reconnection Example - **Reconnection with Exponential Backoff**: A practical example of implementing a reconnection strategy. ``` -------------------------------- ### MqttClient Constructor Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/README.md Initializes the MqttClient with a network client. ```APIDOC ## MqttClient Constructor ### Description Initializes the MqttClient, requiring a pointer or reference to an existing network client (e.g., WiFiClient). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `client` (*Client*): A pointer or reference to a network client object. ### Request Example ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(wifiClient); // Using reference variant // or MqttClient* mqttClient = new MqttClient(&wifiClient); // Using pointer variant ``` ### Response None ``` -------------------------------- ### Bi-directional Communication with MQTT Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/usage-patterns.md This pattern enables a device to publish its status and receive commands. It includes setup for WiFi and MQTT, will messages for offline status, and periodic telemetry publishing. ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(wifiClient); const char *broker = "broker.example.com"; const int port = 1883; // Topic structure const char *statusTopic = "home/device/status"; const char *commandTopic = "home/device/command"; const char *telemetryTopic = "home/device/telemetry"; // Device state bool deviceEnabled = false; unsigned long lastTelemetry = 0; void setup() { Serial.begin(115200); // Setup WiFi and MQTT connection connectToNetwork(); // Configure client mqttClient.setId("home-device-001"); // Set will message mqttClient.beginWill(statusTopic, 7, true, 0); mqttClient.print("offline"); mqttClient.endWill(); if (!mqttClient.connect(broker, port)) { Serial.println("MQTT connection failed!"); while (true) { delay(1000); } } // Subscribe to command topic mqttClient.subscribe(commandTopic, 1); // Publish initial status publishStatus("online"); } void loop() { // Check connection if (!mqttClient.connected()) { if (!mqttClient.connect(broker, port)) { delay(5000); return; } mqttClient.subscribe(commandTopic, 1); publishStatus("online"); } // Process any incoming messages mqttClient.poll(); // Publish telemetry periodically if (millis() - lastTelemetry > 10000) { lastTelemetry = millis(); publishTelemetry(); } } void onMqttMessage(int messageSize) { String topic = mqttClient.messageTopic(); if (topic == commandTopic) { String command = ""; while (mqttClient.available()) { command += (char)mqttClient.read(); } handleCommand(command); } } void handleCommand(String cmd) { if (cmd == "ON") { deviceEnabled = true; digitalWrite(RELAY_PIN, HIGH); publishStatus("on"); } else if (cmd == "OFF") { deviceEnabled = false; digitalWrite(RELAY_PIN, LOW); publishStatus("off"); } } void publishStatus(const char *status) { mqttClient.beginMessage(statusTopic, true, 1); // Retain=true, QoS=1 mqttClient.print(status); mqttClient.endMessage(); } void publishTelemetry() { // Read sensor values float temperature = readSensor(); // Publish with timestamp mqttClient.beginMessage(telemetryTopic, false, 0); mqttClient.print("{\"temp\":"); mqttClient.print(temperature, 2); mqttClient.print(",\"time\":"); mqttClient.print(millis()); mqttClient.print("}"); mqttClient.endMessage(); } float readSensor() { // Placeholder return 22.5; } void connectToNetwork() { // WiFi connection code } ``` -------------------------------- ### Handle MQTT Message Publishing Failures Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/errors.md The beginMessage() and endMessage() methods return 0 on failure. This snippet demonstrates how to check for failures when starting and ending a message, providing potential causes for each. ```cpp int messageSize = 13; // "Hello, World!" if (!mqttClient.beginMessage("test/topic", messageSize)) { Serial.println("Failed to begin message"); // Possible causes: // - Not connected to broker // - Insufficient memory for TX buffer // - Invalid topic format return; } mqttClient.print("Hello, World!"); if (!mqttClient.endMessage()) { Serial.println("Failed to send message"); // Possible causes: // - Connection lost during transmission // - Broker rejected message (QoS timeout) // - Network error } ``` -------------------------------- ### Construct MqttClient with Client Pointer Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Use this constructor when you have a pointer to an underlying transport client, such as WiFiClient. It initializes the MqttClient with default keep-alive, timeout, and clean session settings. ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(&wifiClient); ``` -------------------------------- ### Retrieve MQTT Connection Error Code Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md After a failed connection attempt, use this function to get a specific error code. This helps in diagnosing the reason for the connection failure, such as authentication issues or server unavailability. ```cpp int connectError() const ``` ```cpp if (!mqttClient.connect(broker, port)) { int errorCode = mqttClient.connectError(); if (errorCode == MQTT_NOT_AUTHORIZED) { Serial.println("Check username and password"); } } ``` -------------------------------- ### Handle QoS Acknowledgment Timeouts Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/errors.md For QoS 1 and 2 messages, endMessage() blocks until acknowledgment. This example shows how to set a connection timeout and handle message timeouts, including checking for connection loss and attempting to reconnect. ```cpp mqttClient.setConnectionTimeout(5000); // 5 second timeout if (!mqttClient.endMessage()) { Serial.println("Message timeout - no acknowledgment from broker"); // The broker did not acknowledge the message within 5 seconds // Connection may have been dropped if (!mqttClient.connected()) { Serial.println("Connection lost, reconnecting..."); mqttClient.connect(broker, port); } } ``` -------------------------------- ### String Handling with char* and String Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Demonstrates how to use both C-style char* and Arduino's String objects interchangeably when setting client IDs or topics. This flexibility simplifies integration with different data sources. ```cpp // Can mix char* and String mqttClient.setId("fixed_id"); // char* mqttClient.setId(String("dynamic_") + MAC); // String // Both work String topic = "home/sensor"; mqttClient.beginMessage(topic); // String mqttClient.beginMessage("home/sensor"); // char* ``` -------------------------------- ### Begin MQTT Message with Known Size Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Initiates publishing a message with a known payload size. Use 0xffffffffL for streaming payloads. Ensure endMessage() is called to complete the publish. ```cpp int beginMessage(const char* topic, unsigned long size, bool retain = false, uint8_t qos = 0, bool dup = false) ``` -------------------------------- ### Get MQTT Message Retain Flag Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Check the retain flag of the most recently parsed MQTT message using `messageRetain()`. Returns 1 if the retain flag is set, 0 otherwise. This is only valid after `parseMessage()` has returned a value greater than 0. ```cpp int messageRetain() const { // ... implementation details ... } ``` ```cpp if (mqttClient.messageRetain()) { Serial.println("This is a retained message"); } ``` -------------------------------- ### Configure and Send Will Message Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Use beginWill() to set up a last testament message before connecting. Populate the payload using print() and finalize with endWill(). This message is sent by the broker if the client disconnects unexpectedly. ```cpp mqttClient.beginWill("arduino/status", 10, true, 0); mqttClient.print("offline"); mqttClient.endWill(); // Then connect mqttClient.connect(broker, port); ``` ```cpp mqttClient.beginWill("device/status", false, 0); mqttClient.print("disconnected"); mqttClient.endWill(); ``` -------------------------------- ### MqttClient Configuration Methods Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Configure client settings including client ID, username/password, clean session flag, keep-alive interval, connection timeout, and transmit payload size. ```cpp void setId(const char* id); ``` ```cpp void setId(const String& id); ``` ```cpp void setUsernamePassword(const char* username, const char* password); ``` ```cpp void setUsernamePassword(const String& username, const String& password); ``` ```cpp void setCleanSession(bool cleanSession); ``` ```cpp void setKeepAliveInterval(unsigned long interval); ``` ```cpp void setConnectionTimeout(unsigned long timeout); ``` ```cpp void setTxPayloadSize(unsigned short size); ``` -------------------------------- ### Get MQTT Message Duplicate Flag Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Check the duplicate flag of the most recently parsed MQTT message using `messageDup()`. Returns 1 if the duplicate flag is set, 0 otherwise. This is only valid after `parseMessage()` has returned a value greater than 0. ```cpp int messageDup() const { // ... implementation details ... } ``` ```cpp if (mqttClient.parseMessage() > 0) { int isDup = mqttClient.messageDup(); Serial.println(isDup ? "Duplicate" : "Original"); } ``` -------------------------------- ### Get MQTT Message QoS Level Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Obtain the Quality of Service (QoS) level of the most recently parsed MQTT message using `messageQoS()`. Returns the QoS level (0, 1, or 2). This is only valid after `parseMessage()` has returned a value greater than 0. ```cpp int messageQoS() const { // ... implementation details ... } ``` ```cpp int qos = mqttClient.messageQoS(); if (qos == 2) { Serial.println("Guaranteed delivery"); } ``` -------------------------------- ### Configuration Reference Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/MANIFEST.txt This section details all configuration methods available for the MqttClient, allowing users to customize client identification, authentication, connection behavior, timeouts, and buffer sizes. ```APIDOC ## Configuration Reference This section details the configuration options for the `MqttClient`. ### Configuration Methods (8 total) - **Client Identification**: Set the unique client ID. - `setId(const char*)` - **Authentication**: Set username and password for authentication. - `setUsernamePassword(const char*, const char*)` - **Connection Behavior**: Configure session persistence. - `setCleanSession(bool)` - **Timeout Configuration**: Set connection and keep-alive timeouts. - `setConnectionTimeout(uint32_t)` - `setKeepAliveInterval(uint32_t)` - **Message Buffer Sizing**: Configure the transmit payload size. - `setTxPayloadSize(size_t)` - **Will Message Configuration**: Methods to set up the Will message. ### Configuration Summary Table A table summarizing all configuration options and their effects. ### Trade-off Analysis Analysis of the trade-offs associated with different configuration settings. ``` -------------------------------- ### Construct MqttClient with Client Reference Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Use this constructor when you have a reference to an underlying transport client. It provides an alternative way to initialize the MqttClient with default configuration. ```cpp WiFiClient wifiClient; MqttClient mqttClient(wifiClient); ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Connect to an MQTT broker using the `connect()` method. The return value indicates the success or failure of the connection. ```cpp int result = mqttClient.connect(broker, port) ``` -------------------------------- ### Usage Patterns Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/MANIFEST.txt This section presents 11 complete, real-world usage patterns for the ArduinoMqttClient library, demonstrating various scenarios from basic publishing and subscribing to advanced features like callbacks and network resilience. ```APIDOC ## Usage Patterns This section showcases 11 practical usage patterns for the `ArduinoMqttClient` library. ### Demonstrated Patterns 1. **Basic Publisher**: Sending sensor data. 2. **Basic Subscriber**: Polling for messages. 3. **Callback-based Subscriber**: Using function pointers for message handling. 4. **Advanced `std::function` Callback**: Utilizing `std::function` for flexible callbacks. 5. **Bi-directional Communication**: Implementing two-way message exchange. 6. **Topic Wildcards and Routing**: Demonstrating wildcard usage. 7. **Batch Message Publishing**: Publishing messages in batches (e.g., JSON). 8. **QoS 1 Reliable Delivery**: Ensuring message delivery with QoS level 1. 9. **Retained Messages for State**: Using retained messages to maintain state. 10. **Network Resilience with Reconnection**: Implementing automatic reconnection logic. 11. **Complete Practical Example**: A full example, such as a Home Temperature Monitor. ### Pattern Comparison Table A table comparing the different usage patterns and their suitability for various applications. ### Code Examples All examples are derived from or inspired by the library's source code. ``` -------------------------------- ### Basic Publisher Pattern with WiFi Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/usage-patterns.md Use this pattern for simple sensor data publishing over WiFi. Ensure WiFi and MQTT broker connection before publishing. Call `poll()` in every loop iteration for keep-alive. ```cpp #include #include // Transport client WiFiClient wifiClient; MqttClient mqttClient(wifiClient); // Configuration const char broker[] = "test.mosquitto.org"; int port = 1883; const char topic[] = "sensor/temperature"; void setup() { Serial.begin(115200); // Wait for serial connection while (!Serial) { delay(10); } // Connect to WiFi Serial.println("Connecting to WiFi..."); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" Connected!"); // Set client ID mqttClient.setId("arduino-sensor-01"); // Connect to MQTT broker Serial.print("Connecting to MQTT broker: "); Serial.println(broker); if (!mqttClient.connect(broker, port)) { Serial.print("Connection failed! Error: "); Serial.println(mqttClient.connectError()); while (true) { delay(1000); } } Serial.println("Connected to MQTT broker!"); } void loop() { // Essential: poll for keep-alive mqttClient.poll(); // Publish temperature every 5 seconds static unsigned long lastPublish = 0; if (millis() - lastPublish >= 5000) { lastPublish = millis(); // Read temperature from sensor (example) float temperature = readTemperature(); // Publish message mqttClient.beginMessage(topic); mqttClient.print(temperature, 2); if (!mqttClient.endMessage()) { Serial.println("Publish failed"); } Serial.print("Published: "); Serial.println(temperature); } } float readTemperature() { // Placeholder - connect actual sensor here return 23.5 + (random(0, 100) / 100.0); } ``` -------------------------------- ### MqttClient Connection Methods Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Connect to an MQTT broker using either an IP address and port or a hostname and port. ```cpp int connect(IPAddress ip, uint16_t port); // IPAddress and port ``` ```cpp int connect(const char *host, uint16_t port); // Hostname string and port ``` -------------------------------- ### Connect to MQTT Broker by IP Address Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Use this function to establish an MQTT connection using the broker's IP address. Ensure the IP address and port are correctly specified. ```cpp virtual int connect(IPAddress ip, uint16_t port = 1883) ``` ```cpp IPAddress brokerIP(192, 168, 1, 100); if (!mqttClient.connect(brokerIP, 1883)) { Serial.print("Connection failed! Error code = "); Serial.println(mqttClient.connectError()); } ``` -------------------------------- ### MqttClient Constructor Overloads Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/types.md Instantiate an MqttClient object using either a pointer or a reference to a Client object. ```cpp MqttClient(Client* client); // Pointer to Client ``` ```cpp MqttClient(Client& client); // Reference to Client ``` -------------------------------- ### MqttClient(Client* client) Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Constructs an MqttClient instance using a pointer to an underlying transport client. This allows for flexible integration with various network client implementations like WiFiClient. ```APIDOC ## MqttClient(Client* client) ### Description Constructs an MqttClient with a pointer to an underlying transport client. ### Parameters #### Path Parameters - **client** (Client*) - Required - Pointer to an underlying Client implementation (e.g., WiFiClient) ### Request Example ```cpp #include #include WiFiClient wifiClient; MqttClient mqttClient(&wifiClient); ``` ### Response #### Success Response (200) - **MqttClient instance** - Description of the returned MqttClient instance ``` -------------------------------- ### beginMessage (const char* topic, unsigned long size, ...) Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Initiates publishing a message with a known payload size. Use 0xffffffffL for size to enable streaming. ```APIDOC ## beginMessage (const char* topic, unsigned long size, ...) ### Description Initiates publishing a message with a known payload size. ### Method Signature `int beginMessage(const char* topic, unsigned long size, bool retain = false, uint8_t qos = 0, bool dup = false)` ### Parameters #### Path Parameters - **topic** (const char*) - Required - Topic name to publish to - **size** (unsigned long) - Required - Expected payload size in bytes (use 0xffffffffL for streaming) - **retain** (bool) - Optional - Retain message on broker (default: false) - **qos** (uint8_t) - Optional - Quality of Service level (0, 1, or 2) (default: 0) - **dup** (bool) - Optional - Duplicate flag (default: false) ### Returns - `1` if message initialized successfully - `0` on failure ### Example ```cpp if (mqttClient.beginMessage("sensor/temperature", 5)) { mqttClient.print("23.5"); mqttClient.endMessage(); } ``` ``` -------------------------------- ### Set MQTT Username and Password Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/errors.md Verify that username and password are set before calling connect(). Ensure credentials are correct and properly encoded. ```cpp // Verify credentials are set BEFORE calling connect() Serial.println("Configuring credentials..."); mqttClient.setUsernamePassword("admin", "myPassword123"); Serial.println("Attempting connection..."); if (!mqttClient.connect(broker, port)) { if (mqttClient.connectError() == MQTT_BAD_USER_NAME_OR_PASSWORD) { Serial.println("Check username and password"); } } ``` -------------------------------- ### Connection Configuration Methods Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/keywords.txt Methods for configuring client connection parameters. ```APIDOC ## Connection Configuration Methods ### Description Configure various parameters related to the MQTT client's connection. ### Methods - **setId**: Sets the client identifier (ID) for the MQTT connection. - **setUsernamePassword**: Sets the username and password for authentication. - **setCleanSession**: Configures the clean session flag for the connection. - **setKeepAliveInterval**: Sets the keep-alive interval in seconds. - **setConnectionTimeout**: Sets the connection timeout in seconds. ``` -------------------------------- ### Connect to MQTT Broker by Hostname Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Use this function to establish an MQTT connection using the broker's hostname. This is useful when an IP address is not readily available or may change. ```cpp virtual int connect(const char *host, uint16_t port = 1883) ``` ```cpp if (!mqttClient.connect("broker.example.com", 1883)) { Serial.println("Connection failed!"); } ``` -------------------------------- ### beginMessage (const String& topic, unsigned long size, ...) Source: https://github.com/arduino-libraries/arduinomqttclient/blob/master/_autodocs/mqtt-client-core.md Variant accepting String topic for initiating a message with a known payload size. ```APIDOC ## beginMessage (const String& topic, unsigned long size, ...) ### Description Variant accepting String topic for initiating a message with a known payload size. Converts String to C-string internally. ### Method Signature `int beginMessage(const String& topic, unsigned long size, bool retain = false, uint8_t qos = 0, bool dup = false)` ### Parameters #### Path Parameters - **topic** (const String&) - Required - Topic name as String - **size** (unsigned long) - Required - Expected payload size in bytes (use 0xffffffffL for streaming) - **retain** (bool) - Optional - Retain message on broker (default: false) - **qos** (uint8_t) - Optional - Quality of Service level (0, 1, or 2) (default: 0) - **dup** (bool) - Optional - Duplicate flag (default: false) ### Returns - `1` if successful - `0` on failure ```