### Complete PubSubClient Usage Example Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md This Arduino sketch demonstrates a full-fledged PubSubClient implementation. It includes setup for Ethernet connection, MQTT broker connection, message callback registration, subscription to a topic, publishing status and sensor data, and automatic reconnection logic. ```cpp #include #include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient client(ethClient); void messageCallback(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Message on "); Serial.print(topic); Serial.print(": "); for (unsigned int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } void reconnect() { while (!client.connected()) { Serial.print("Connecting..."); if (client.connect("arduinoDevice", "username", "password")) { Serial.println("Connected"); client.subscribe("commands/#"); client.publish("status/startup", "ready"); } else { Serial.print("Failed, rc="); Serial.println(client.state()); delay(5000); } } } void setup() { Serial.begin(9600); Ethernet.begin(mac); delay(1500); client.setServer(broker, 1883); client.setCallback(messageCallback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Publish sensor reading every 10 seconds static unsigned long lastPublish = 0; if (millis() - lastPublish > 10000) { client.publish("sensors/temperature", "22.5"); lastPublish = millis(); } } ``` -------------------------------- ### Complete PubSubClient Configuration and Usage Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/configuration.md This snippet shows a full example of configuring the PubSubClient for an Arduino-like environment. It includes network setup, MQTT broker connection, message handling, and a reconnect loop. Ensure your network is configured before running. ```cpp #include #include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient client; void messageHandler(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Message on "); Serial.print(topic); Serial.print(": "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } void setup() { Serial.begin(9600); Ethernet.begin(mac); delay(1500); // Configure network client client.setClient(ethClient); // Configure server client.setServer(broker, 1883); // Configure callback client.setCallback(messageHandler); // Configure timeouts client.setKeepAlive(30) .setSocketTimeout(20); // Increase buffer for large messages if (!client.setBufferSize(512)) { Serial.println("Buffer resize failed"); } // Optional: debug output client.setStream(Serial); } void reconnect() { while (!client.connected()) { Serial.print("Connecting..."); if (client.connect("deviceID", "mqtt_user", "mqtt_pass")) { Serial.println("Connected"); client.subscribe("commands/#"); } else { Serial.print("Failed: "); Serial.println(client.state()); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Publish sensor data if (millis() % 10000 < 100) { client.publish("sensors/temp", "25.5"); } } ``` -------------------------------- ### Topic Filtering and Routing with Wildcards Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/examples-and-patterns.md This example shows how to subscribe to multiple MQTT topics using wildcards and route incoming messages based on their topic patterns. It includes setup for WiFi and PubSubClient, message callback handling, and specific functions for processing sensor data, device control, and commands. ```cpp #include #include const char* mqtt_server = "mqtt.example.com"; WiFiClient wifiClient; PubSubClient client(wifiClient); void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); client.setServer(mqtt_server, 1883); client.setCallback(onMessage); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { while (!client.connected()) { if (client.connect("device1")) { // Subscribe to multiple topics with wildcards client.subscribe("home/sensors/+/temperature"); // Single level client.subscribe("home/devices/#"); // All levels client.subscribe("commands/+/action"); } else { delay(5000); } } } void onMessage(char* topic, uint8_t* payload, unsigned int length) { String topicStr(topic); String payloadStr = ""; // Convert payload to string for (int i = 0; i < length; i++) { payloadStr += (char)payload[i]; } Serial.print("Topic: "); Serial.println(topicStr); Serial.print("Payload: "); Serial.println(payloadStr); // Route based on topic pattern if (topicStr.startsWith("home/sensors/")) { handleSensorData(topicStr, payloadStr); } else if (topicStr.startsWith("home/devices/")) { handleDeviceControl(topicStr, payloadStr); } else if (topicStr.startsWith("commands/")) { handleCommand(topicStr, payloadStr); } } void handleSensorData(String topic, String payload) { Serial.println("Processing sensor data"); // Extract sensor ID from topic // "home/sensors/sensor1/temperature" -> "sensor1" int startIdx = topic.indexOf("/") + 1; int endIdx = topic.indexOf("/", startIdx + 1); String sensorId = topic.substring(startIdx, endIdx); Serial.print("Sensor ID: "); Serial.println(sensorId); Serial.print("Value: "); Serial.println(payload); } void handleDeviceControl(String topic, String payload) { Serial.println("Processing device control"); // "home/devices/lamp1/brightness" -> "lamp1" int startIdx = topic.indexOf("/") + 1; int endIdx = topic.indexOf("/", startIdx + 1); String deviceId = topic.substring(startIdx, endIdx); Serial.print("Device: "); Serial.println(deviceId); } void handleCommand(String topic, String payload) { Serial.println("Processing command"); // "commands/device1/action" -> "device1" int startIdx = topic.indexOf("/") + 1; int endIdx = topic.indexOf("/", startIdx); String targetId = topic.substring(startIdx, endIdx); Serial.print("Target: "); Serial.println(targetId); Serial.print("Action: "); Serial.println(payload); } ``` -------------------------------- ### Basic Sensor Publishing Example Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/INDEX.md Demonstrates how to publish sensor data at regular intervals. Requires a running MQTT broker. ```cpp #include #include const char* ssid = "your-ssid"; const char* password = "your-password"; const char* mqtt_server = "your-mqtt-server"; const int mqtt_port = 1883; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, mqtt_port); // client.setCallback(callback); // Uncomment if you need to receive messages } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 5000) { // Publish every 5 seconds lastMsg = now; value = random(0, 100); dtostrf(value, 4, 2, msg); // Convert float to string Serial.print("Publishing message: "); Serial.println(msg); client.publish("sensor/temperature", msg); } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP8266Client", "user", "password")) { // Use your MQTT username and password Serial.println("connected"); // Once connected, publish an announcement or subscribe to topics // client.subscribe("inTopic"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } ``` -------------------------------- ### Write Buffer Example Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Example demonstrating how to publish a small byte array by calling beginPublish, writing the buffer using the write() overload, and then calling endPublish. ```cpp uint8_t data[] = {0x01, 0x02, 0x03}; client.beginPublish("binary/data", 3, false); client.write(data, 3); client.endPublish(); ``` -------------------------------- ### Control LED with MQTT Messages (Arduino C++) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/examples-and-patterns.md This example demonstrates how to control an LED connected to an ESP32 board using MQTT messages. It includes WiFi setup, MQTT connection, message subscription, and message handling logic for ON/OFF/TOGGLE commands and brightness control. ```cpp #include #include const char* ssid = "YourSSID"; const char* password = "YourPassword"; const char* mqtt_server = "mqtt.example.com"; const int LED_PIN = 5; WiFiClient wifiClient; PubSubClient client(wifiClient); void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); setupWiFi(); client.setServer(mqtt_server, 1883); client.setCallback(onMessageReceived); } void setupWiFi() { 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(""); Serial.println("WiFi connected"); Serial.println(WiFi.localIP()); } else { Serial.println("WiFi connection failed"); } } void reconnect() { while (!client.connected()) { Serial.print("Connecting MQTT..."); // Create unique client ID String clientId = "ESP32-"; clientId += String(random(0xffff), HEX); if (client.connect(clientId.c_str())) { Serial.println("Connected"); // Subscribe to control topic client.subscribe("home/led/cmd"); client.subscribe("home/led/brightness"); // Announce we're online client.publish("home/led/status", "online"); } else { Serial.print("Failed: "); Serial.println(client.state()); delay(5000); } } } void onMessageReceived(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Message on "); Serial.print(topic); Serial.print(": "); // Convert payload to string String message = ""; for (int i = 0; i < length; i++) { message += (char)payload[i]; } Serial.println(message); // Handle commands if (String(topic) == "home/led/cmd") { if (message == "ON") { digitalWrite(LED_PIN, HIGH); client.publish("home/led/status", "ON"); } else if (message == "OFF") { digitalWrite(LED_PIN, LOW); client.publish("home/led/status", "OFF"); } else if (message == "TOGGLE") { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); client.publish("home/led/status", digitalRead(LED_PIN) ? "ON" : "OFF"); } } else if (String(topic) == "home/led/brightness") { int brightness = message.toInt(); if (brightness >= 0 && brightness <= 255) { analogWrite(LED_PIN, brightness); client.publish("home/led/brightness", message.c_str()); } } } void loop() { if (WiFi.status() != WL_CONNECTED) { setupWiFi(); } if (!client.connected()) { reconnect(); } client.loop(); } ``` -------------------------------- ### Working Examples Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/MANIFEST.txt Collection of complete working examples demonstrating various use cases and patterns for PubSubClient. ```APIDOC ## PubSubClient Examples and Patterns This section provides practical examples of using PubSubClient. ### Example: Basic Sensor Publishing ```cpp #include #include // WiFi and MQTT details const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; const char* mqtt_server = "YOUR_MQTT_SERVER"; const int mqtt_port = 1883; WiFiClient wifiClient; PubSubClient client(wifiClient); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi..."); } client.setServer(mqtt_server, mqtt_port); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Read sensor data (example) float sensorValue = analogRead(A0); char payload[50]; dtostrf(sensorValue, 1, 2, payload); client.publish("sensor/data", payload); delay(5000); } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ArduinoClient")) { Serial.println("connected"); client.subscribe("command/led"); // Example subscription } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" retrying in 5 seconds"); delay(5000); } } } ``` ### Other Examples Include: - LED control with message handling - Authenticated connection with will message - Publishing large messages - Topic filtering and routing - State machine with connection recovery - JSON payload publishing - Multiple topic subscriptions Refer to `examples-and-patterns.md` for the full list and code. ``` -------------------------------- ### Callback Example with Lambda Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/types.md This example demonstrates how to set a callback function using a lambda expression for handling incoming messages on ESP8266. ```cpp client.setCallback([](char* topic, uint8_t* payload, unsigned int len) { Serial.println(topic); }); ``` -------------------------------- ### Basic Sensor Publishing with Arduino Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/examples-and-patterns.md This example demonstrates how to publish temperature readings from an analog sensor every 30 seconds. It requires Ethernet and PubSubClient libraries. Ensure your MQTT broker and network are configured. ```cpp #include #include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient client(ethClient); const int SENSOR_PIN = A0; unsigned long lastPublish = 0; const unsigned long PUBLISH_INTERVAL = 30000; // 30 seconds void setup() { Serial.begin(9600); Ethernet.begin(mac); delay(1500); client.setServer(broker, 1883); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Publish temperature reading at interval unsigned long now = millis(); if (now - lastPublish > PUBLISH_INTERVAL) { publishTemperature(); lastPublish = now; } } void publishTemperature() { int sensorValue = analogRead(SENSOR_PIN); float voltage = sensorValue * (5.0 / 1023.0); float temperature = (voltage - 0.5) * 100; // TMP36 formula char payload[8]; dtostrf(temperature, 5, 2, payload); if (client.publish("home/temperature", payload)) { Serial.print("Published: "); Serial.println(payload); } else { Serial.println("Publish failed"); } } void reconnect() { while (!client.connected()) { Serial.print("Connecting..."); if (client.connect("sensor01")) { Serial.println("Connected"); client.publish("home/status", "online"); } else { Serial.print("Failed: "); Serial.println(client.state()); delay(5000); } } } ``` -------------------------------- ### Subscribe with QoS Levels Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/types.md Examples demonstrating how to subscribe to topics using different QoS levels. QoS 0 offers 'at most once' delivery, while QoS 1 offers 'at least once' delivery. Note that QoS 2 is not supported for subscribing. ```cpp // Subscribe with QoS 0 (at most once) client.subscribe("temp/current", MQTTQOS0); // Subscribe with QoS 1 (at least once) client.subscribe("alerts/critical", MQTTQOS1); ``` -------------------------------- ### Write Single Byte Example Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Example showing how to write three individual bytes to a message after initiating publishing with beginPublish and before finalizing with endPublish. ```cpp client.beginPublish("test/topic", 5, false); client.write(0x01); client.write(0x02); client.write(0x03); client.endPublish(); ``` -------------------------------- ### PubSubClient Constructor with Domain Name Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use this constructor when you want to connect to an MQTT broker using its domain name. An example is provided for initialization. ```cpp PubSubClient(const char* domain, uint16_t port, Client& client) ``` ```cpp EthernetClient ethClient; PubSubClient mqttClient("mqtt.example.com", 1883, ethClient); ``` -------------------------------- ### PubSubClient Constructor with Domain Name and Callback Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use this constructor when you want to connect to an MQTT broker using its domain name and specify a callback function for handling incoming messages. An example is provided for initialization. ```cpp PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) ``` ```cpp void messageHandler(char* topic, uint8_t* payload, unsigned int length) { // Process received message } EthernetClient ethClient; PubSubClient mqttClient("mqtt.example.com", 1883, messageHandler, ethClient); ``` -------------------------------- ### Connect with Client ID Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Connect to the MQTT server using only a client ID. Call state() to get the reason for connection failure. ```cpp if (client.connect("arduinoClient")) { Serial.println("Connected"); } else { Serial.print("Connection failed, code: "); Serial.println(client.state()); } ``` -------------------------------- ### Publish Large Message in Chunks Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Example demonstrating how to publish a large message (2000 bytes) by first calling beginPublish, then writing data in a loop, and finally calling endPublish. ```cpp int messageSize = 2000; if (client.beginPublish("large/data", messageSize, false)) { for (int i = 0; i < messageSize; i++) { client.write((uint8_t)(i & 0xFF)); } client.endPublish(); } ``` -------------------------------- ### Handling Different Message Formats Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/README.md Process messages with varying formats, including binary, text, and numeric data. This example demonstrates how to correctly interpret and handle each type. ```cpp void onMessage(char* topic, uint8_t* payload, unsigned int length) { // Binary data if (strcmp(topic, "binary/data") == 0) { for (int i = 0; i < length; i++) { uint8_t byte = payload[i]; Serial.print(byte, HEX); Serial.print(" "); } Serial.println(); } // String data (NOT null-terminated!) else if (strcmp(topic, "text/message") == 0) { char message[length + 1]; memcpy(message, payload, length); message[length] = '\0'; Serial.println(message); } // Numeric data else if (strcmp(topic, "sensor/temperature") == 0) { String temp = ""; for (int i = 0; i < length; i++) { temp += (char)payload[i]; } float temperature = temp.toFloat(); Serial.println(temperature); } } ``` -------------------------------- ### LED Control with Message Handling Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/INDEX.md Example of controlling an LED remotely via MQTT messages. This snippet requires an LED connected to a GPIO pin. ```cpp #include #include const char* ssid = "your-ssid"; const char* password = "your-password"; const char* mqtt_server = "your-mqtt-server"; const int mqtt_port = 1883; const int ledPin = 2; // GPIO pin connected to the LED WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); setup_wifi(); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived [" ); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // Turn the LED on/off based on the message if ((char)payload[0] == '1') { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ESP8266Client", "user", "password")) { // Use your MQTT username and password Serial.println("connected"); client.subscribe("led/control"); // Subscribe to the topic to control the LED } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } ``` -------------------------------- ### Set and Get Buffer Size Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/configuration.md Configure the MQTT packet buffer size for a client instance. Must be called before connecting. A size of 0 is invalid and fails memory allocation. ```cpp boolean setBufferSize(uint16_t size) uint16_t getBufferSize() ``` ```cpp PubSubClient client(ethClient); // Increase buffer for large messages if (!client.setBufferSize(1024)) { Serial.println("Failed to increase buffer"); } // Later, check current size uint16_t bufSize = client.getBufferSize(); Serial.println(bufSize); // Output: 1024 ``` -------------------------------- ### connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Establishes a full connection with all options, including client ID, credentials, will message, and session control. ```APIDOC ## connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession) ### Description Full connect with all options including session control. ### Method Signature ```cpp boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession) ``` ### Parameters #### Path Parameters - **id** (const char*) - Required - Unique client identifier - **user** (const char*) - Required - MQTT username - **pass** (const char*) - Required - MQTT password - **willTopic** (const char*) - Required - Topic for the will message - **willQos** (uint8_t) - Required - Quality of service for will message (0 or 1) - **willRetain** (boolean) - Required - true to retain the will message - **willMessage** (const char*) - Required - Message content sent on disconnection - **cleanSession** (boolean) - Required - true to discard previous session state ### Returns - **boolean**: true if connection successful, false otherwise. ### Behavior #### Clean Session behavior: - If true: Server discards any previous subscriptions for this client ID - If false: Server restores previous session state and pending messages ### Example ```cpp if (client.connect("device1", "user", "pass", "status/device1", 1, true, "offline", false)) { Serial.println("Connected, session resumed"); } ``` ``` -------------------------------- ### endPublish Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Finalizes a message that was started with beginPublish(). This method must be called after all write() calls to complete message transmission. ```APIDOC ## endPublish() ### Description Finalizes a message that was started with beginPublish(). This method must be called after all write() calls to complete message transmission. ### Method ```cpp int endPublish() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - **int** - 1 if successful, 0 if error ### Must be called after beginPublish() and all write() calls to complete message transmission ``` -------------------------------- ### PubSubClient Constructor (Domain, Port, Client) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a domain name, port, and network client. ```APIDOC ## PubSubClient(const char* domain, uint16_t port, Client& client) ### Description Constructor with domain name string. ### Parameters #### Path Parameters - domain (const char*) - Required - Domain name of the MQTT broker - port (uint16_t) - Required - Port number - client (Client&) - Required - Reference to a network client ### Returns PubSubClient instance ### Example ```cpp EthernetClient ethClient; PubSubClient mqttClient("mqtt.example.com", 1883, ethClient); ``` ``` -------------------------------- ### Get MQTT Connection State String Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/errors.md Converts MQTT connection states into human-readable strings. Useful for debugging connection issues. ```cpp String getStateString(int state) { switch(state) { case MQTT_CONNECTED: return "Connected"; case MQTT_DISCONNECTED: return "Disconnected"; case MQTT_CONNECT_FAILED: return "Network connection failed"; case MQTT_CONNECTION_LOST: return "Connection lost"; case MQTT_CONNECTION_TIMEOUT: return "Connection timeout"; case MQTT_CONNECT_BAD_PROTOCOL: return "Bad protocol version"; case MQTT_CONNECT_BAD_CLIENT_ID: return "Bad client ID"; case MQTT_CONNECT_UNAVAILABLE: return "Service unavailable"; case MQTT_CONNECT_BAD_CREDENTIALS: return "Authentication failed"; case MQTT_CONNECT_UNAUTHORIZED: return "Not authorized"; default: return "Unknown state: " + String(state); } } // Usage: if (!client.connected()) { Serial.println("Connection error: " + getStateString(client.state())); } ``` -------------------------------- ### Connect with Client ID, Username, and Password Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Connect to the MQTT server using a client ID, username, and password for authentication. ```cpp if (client.connect("myDevice", "mqtt_user", "mqtt_pass")) { Serial.println("Authenticated"); } ``` -------------------------------- ### Lambda Callback for ESP8266/ESP32 Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/README.md Example of setting a lambda function as a callback for message reception on ESP8266/ESP32. Ensure WiFiClient is available in the standard library. ```cpp client.setCallback([](char* topic, uint8_t* payload, unsigned int len) { // Lambda callback }); ``` -------------------------------- ### PubSubClient Constructor with Callback Function Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with the MQTT broker's address, port, a callback function for handling incoming messages, and a network client. ```cpp void messageHandler(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Topic: "); Serial.println(topic); } IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient mqttClient(broker, 1883, messageHandler, ethClient); ``` -------------------------------- ### Finalize Message Publishing Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Completes the transmission of a message that was started with beginPublish() and had its data written using write(). Must be called after all write() operations. ```cpp int endPublish() ``` -------------------------------- ### Subscribe with Connection and QoS Checks Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/errors.md Verifies the client is connected and demonstrates subscribing to topics with both QoS 0 and QoS 1, checking for subscription failures. ```cpp if (client.connected()) { // QoS 0 if (!client.subscribe("sensor/temp", 0)) { Serial.println("Subscribe failed"); } // QoS 1 if (!client.subscribe("alerts", 1)) { Serial.println("Subscribe failed"); } } ``` -------------------------------- ### PubSubClient Constructor (Domain, Port, Callback, Client) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a domain name, port, a message handling callback, and a network client. ```APIDOC ## PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) ### Description Constructor with domain name and callback. ### Parameters #### Path Parameters - domain (const char*) - Required - Domain name of the MQTT broker - port (uint16_t) - Required - Port number - callback (MQTT_CALLBACK_SIGNATURE) - Required - Message handling callback - client (Client&) - Required - Reference to a network client ### Returns PubSubClient instance ### Example ```cpp void messageHandler(char* topic, uint8_t* payload, unsigned int length) { // Process received message } EthernetClient ethClient; PubSubClient mqttClient("mqtt.example.com", 1883, messageHandler, ethClient); ``` ``` -------------------------------- ### Convert Topic to String Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/types.md Converts a C-style topic string to an Arduino String object for easier manipulation, such as checking if it starts with a specific prefix. ```cpp void callback(char* topic, uint8_t* payload, unsigned int length) { String topicStr(topic); // Direct conversion if (topicStr.startsWith("sensor/")) { // Handle sensor topic } } ``` -------------------------------- ### MQTT Connection with Authentication in Arduino Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/README.md Demonstrates how to connect to an MQTT broker with authentication (username and password) and set up a callback for received messages. The reconnect function handles disconnections. ```cpp EthernetClient ethClient; PubSubClient client(ethClient); void reconnect() { while (!client.connected()) { if (client.connect("deviceID", "username", "password")) { client.subscribe("commands/#"); } else { Serial.print("Connection failed: "); Serial.println(client.state()); delay(5000); } } } void setup() { client.setServer("mqtt.example.com", 1883); client.setCallback(messageReceived); } void messageReceived(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Message: "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } ``` -------------------------------- ### PubSubClient Constructor (Domain, Port, Client, Stream) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a domain name, port, network client, and a debug output stream. ```APIDOC ## PubSubClient(const char* domain, uint16_t port, Client& client, Stream& stream) ### Description Constructor with domain name and debug stream. ### Parameters #### Path Parameters - domain (const char*) - Required - Domain name of the MQTT broker - port (uint16_t) - Required - Port number - client (Client&) - Required - Reference to a network client - stream (Stream&) - Required - Debug output stream ### Returns PubSubClient instance ``` -------------------------------- ### Get PubSubClient Buffer Size Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use `getBufferSize` to retrieve the current internal buffer size in bytes. The default size is typically 256 bytes. ```cpp uint16_t getBufferSize() ``` ```cpp uint16_t bufSize = client.getBufferSize(); Serial.println(bufSize); // Prints: 256 ``` -------------------------------- ### PubSubClient Constructor (IP, Port, Callback, Client) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a byte array IP address, port, a message handling callback, and a network client. ```APIDOC ## PubSubClient(uint8_t* ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) ### Description Constructor with byte array IP and callback. ### Parameters #### Path Parameters - ip (uint8_t*) - Required - Pointer to 4-byte IP address array - port (uint16_t) - Required - Port number - callback (MQTT_CALLBACK_SIGNATURE) - Required - Message handling callback - client (Client&) - Required - Reference to a network client ### Returns PubSubClient instance ``` -------------------------------- ### connect(const char* id, const char* user, const char* pass) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Connects to the MQTT server with client ID, username, and password for authentication. ```APIDOC ## connect(const char* id, const char* user, const char* pass) ### Description Connect with client ID, username, and password. ### Method Signature ```cpp boolean connect(const char* id, const char* user, const char* pass) ``` ### Parameters #### Path Parameters - **id** (const char*) - Required - Unique client identifier - **user** (const char*) - Required - MQTT username - **pass** (const char*) - Required - MQTT password ### Returns - **boolean**: true if connection successful, false otherwise. ### Example ```cpp if (client.connect("myDevice", "mqtt_user", "mqtt_pass")) { Serial.println("Authenticated"); } ``` ``` -------------------------------- ### Get PubSubClient Connection State Code Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md The state() method returns a numeric code representing the current connection state. This is useful for debugging and handling specific connection issues. ```cpp int connectionState = client.state(); switch(connectionState) { case MQTT_CONNECTED: Serial.println("Connected"); break; case MQTT_CONNECT_BAD_CREDENTIALS: Serial.println("Auth failed"); break; default: Serial.print("State: "); Serial.println(connectionState); } ``` -------------------------------- ### PubSubClient Constructor (Domain, Port, Callback, Client, Stream) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a domain name, port, a message handling callback, network client, and a debug output stream. ```APIDOC ## PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ### Description Constructor with domain name, callback, and debug stream. ### Parameters #### Path Parameters - domain (const char*) - Required - Domain name of the MQTT broker - port (uint16_t) - Required - Port number - callback (MQTT_CALLBACK_SIGNATURE) - Required - Message handling callback - client (Client&) - Required - Reference to a network client - stream (Stream&) - Required - Debug output stream ### Returns PubSubClient instance ``` -------------------------------- ### PubSubClient Constructor with IP Address, Callback, and Debug Stream Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use this constructor when you have the IP address of the MQTT broker as a byte array, want to specify a callback function, and direct debug output to a stream. ```cpp PubSubClient(uint8_t* ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ``` -------------------------------- ### PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) Constructor Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Constructs a PubSubClient instance with the MQTT broker details, a callback function for handling incoming messages, and the network client. ```APIDOC ## PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) ### Description Constructor with callback function for received messages. ### Parameters #### Path Parameters - **addr** (IPAddress) - Required - IP address of the MQTT broker - **port** (uint16_t) - Required - Port number - **callback** (MQTT_CALLBACK_SIGNATURE) - Required - Function pointer or std::function for message handling - **client** (Client&) - Required - Reference to a network client ### Callback signature: ```cpp void callback(char* topic, uint8_t* payload, unsigned int length) ``` ### Returns PubSubClient instance ### Example ```cpp void messageHandler(char* topic, uint8_t* payload, unsigned int length) { Serial.print("Topic: "); Serial.println(topic); } IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient mqttClient(broker, 1883, messageHandler, ethClient); ``` ``` -------------------------------- ### PubSubClient Constructor (IP, Port, Callback, Client, Stream) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a byte array IP address, port, a message handling callback, network client, and a debug output stream. ```APIDOC ## PubSubClient(uint8_t* ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ### Description Constructor with byte array IP, callback, and debug stream. ### Parameters #### Path Parameters - ip (uint8_t*) - Required - Pointer to 4-byte IP address array - port (uint16_t) - Required - Port number - callback (MQTT_CALLBACK_SIGNATURE) - Required - Message handling callback - client (Client&) - Required - Reference to a network client - stream (Stream&) - Required - Debug output stream ### Returns PubSubClient instance ``` -------------------------------- ### PubSubClient Constructor with IP Address and Port Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with the MQTT broker's IP address and port, along with a network client for establishing the connection. ```cpp IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient mqttClient(broker, 1883, ethClient); ``` -------------------------------- ### PubSubClient Constructor with Callback and Debug Stream Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Constructs a PubSubClient instance, specifying the MQTT broker's address, port, a message handling callback function, a network client, and a stream for debug output. ```cpp PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ``` -------------------------------- ### Configuration Options Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/MANIFEST.txt Details on compile-time preprocessor defines and runtime configuration methods for customizing PubSubClient behavior. ```APIDOC ## PubSubClient Configuration This section covers configuration aspects of the PubSubClient library. ### Compile-time Defines - **MQTT_MAX_PACKET_SIZE**: Maximum packet size. - **MQTT_BUFFER_SIZE**: Buffer size for message handling. - ... (Other preprocessor defines) ### Runtime Configuration Methods - **setServer(const char* host, uint16_t port)**: Configures the MQTT broker address. - **setCallback(MQTT_CALLBACK_SIGNATURE)**: Assigns a callback for message reception. - **setSocketTimeout(uint32_t seconds)**: Sets the socket read timeout. - **setBufferSizes(size_t sendBuffSize, size_t recvBuffSize)**: Configures send and receive buffer sizes. - **setKeepAliveInterval(uint16_t interval)**: Sets the keep-alive interval in seconds. - **setCleanSession(bool clean)**: Configures the clean session flag. - **setWill(const char* topic, const char* payload, uint8_t qos, bool retain)**: Sets the will message parameters. - **setCredentials(const char* user, const char* pass)**: Sets username and password for authentication. Refer to `configuration.md` for detailed explanations and default values. ``` -------------------------------- ### PubSubClient Constructor with Domain Name, Callback, and Debug Stream Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use this constructor when you want to connect to an MQTT broker using its domain name, specify a callback function, and direct debug output to a stream. ```cpp PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ``` -------------------------------- ### Connect with Credentials and Will Message Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Connect to the MQTT server using a client ID, username, password, and a will message. ```cpp if (client.connect("device1", "user", "pass", "status/device1", 1, true, "offline")) { Serial.println("Connected"); } ``` -------------------------------- ### Basic MQTT Connection and Publishing in Arduino Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/README.md Establishes a basic MQTT connection using Ethernet and publishes status and sensor readings. Ensure your broker IP and port are correctly set. ```cpp #include #include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress broker(192, 168, 1, 100); EthernetClient ethClient; PubSubClient client(ethClient); void setup() { Serial.begin(9600); Ethernet.begin(mac); delay(1500); client.setServer(broker, 1883); } void loop() { if (!client.connected()) { if (client.connect("arduinoDevice")) { client.subscribe("commands/#"); client.publish("status", "online"); } } client.loop(); // Publish sensor reading every 10 seconds static unsigned long lastMsg = 0; if (millis() - lastMsg > 10000) { client.publish("sensors/temperature", "25.5"); lastMsg = millis(); } } ``` -------------------------------- ### PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) Constructor Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Constructs a PubSubClient instance with MQTT broker details, a message callback, network client, and a stream for debug output. ```APIDOC ## PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) ### Description Constructor with callback and debug stream. ### Parameters #### Path Parameters - **addr** (IPAddress) - Required - IP address of the MQTT broker - **port** (uint16_t) - Required - Port number - **callback** (MQTT_CALLBACK_SIGNATURE) - Required - Message handling callback - **client** (Client&) - Required - Reference to a network client - **stream** (Stream&) - Required - Debug output stream ### Returns PubSubClient instance ``` -------------------------------- ### Run Test Suite Source: https://github.com/knolleary/pubsubclient/blob/master/tests/README.md Executes the Python test suite for the Arduino client. It is assumed that an MQTT server is already running. ```bash python testsuite.py ``` -------------------------------- ### PubSubClient Constructor with IP Address and Callback Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Use this constructor when you have the IP address of the MQTT broker as a byte array and want to specify a callback function for handling incoming messages. ```cpp PubSubClient(uint8_t* ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) ``` -------------------------------- ### PubSubClient Constructor (IP, Port, Client, Stream) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Initializes the PubSubClient with a byte array IP address, port, network client, and a debug output stream. ```APIDOC ## PubSubClient(uint8_t* ip, uint16_t port, Client& client, Stream& stream) ### Description Constructor with byte array IP, port, and debug stream. ### Parameters #### Path Parameters - ip (uint8_t*) - Required - Pointer to 4-byte IP address array - port (uint16_t) - Required - Port number - client (Client&) - Required - Reference to a network client - stream (Stream&) - Required - Debug output stream ### Returns PubSubClient instance ``` -------------------------------- ### Publish Binary Data (QoS 0) Source: https://github.com/knolleary/pubsubclient/blob/master/_autodocs/api-reference-pubsubclient.md Publish raw binary data to a topic with QoS 0 and no retention. Specify the payload pointer and its length. ```cpp boolean publish(const char* topic, const uint8_t* payload, unsigned int plength) { // Implementation details... return true; } ``` ```cpp uint8_t data[] = {0x01, 0x02, 0x03}; client.publish("sensor/raw", data, 3); ```