Skip to content
CommunicationMITv2.8

PubSubClient

by Nick O'Leary

PubSubClient is the most widely used MQTT client for Arduino-family boards. It handles MQTT packet framing, keep-alive pings and the publish/subscribe protocol over any network Client object (WiFiClient, EthernetClient or WiFiClientSecure). You give it a broker address, a client and a callback function for incoming messages, and it takes care of the rest. It is the usual choice for sending sensor data to a broker, controlling relays from Home Assistant and connecting ESP boards to Node-RED.

Know its limits before you build on it. It speaks MQTT 3.1 and 3.1.1, not MQTT 5. It can subscribe at QoS 0 or 1, but it can only publish at QoS 0. It has no TLS of its own: for an encrypted connection (port 8883) you pass it a WiFiClientSecure and set the certificate on that client. If you need guaranteed delivery or MQTT 5, look at a different library.

The best-known problem is the packet buffer. In version 2.8 the default buffer is 256 bytes, and that must hold the topic, the header and the payload together. If a message is bigger, publish() simply returns false and nothing is sent, which looks like a silent failure. The fix is one line before you connect: client.setBufferSize(512); (or larger). Always check the return value of publish().

The second problem is dropped connections. The library does nothing in the background: you must call client.loop() on every pass of your main loop, and the default keep-alive is 15 seconds. A long delay(), a slow sensor read or a blocking HTTP call stops loop() from running, and the broker disconnects you. Use millis() timing instead of delay(), and reconnect when client.connected() is false. Every client also needs its own unique client ID: if two devices use the same ID, the broker kicks one off as soon as the other connects, and both fight in an endless reconnect loop.

When a connection fails, print client.state(). The codes you will see most are -4 (timed out waiting for the broker), -3 (connection lost), -2 (could not connect, usually a wrong address, port or network), 2 (bad client ID), 4 (bad username or password) and 5 (not authorised). Code 0 means connected.

In the callback, the payload is raw bytes and is not null-terminated. Copy it into a buffer and add the terminator yourself before treating it as text, as in the example below. For devices that appear in Home Assistant, publish an "online" message with the retain flag and register a Last Will message, so the broker announces "offline" automatically if the device vanishes.

Setup

Installation

Arduino IDE — Library Manager

Sketch → Include Library → Manage Libraries → search PubSubClient

PlatformIO

lib_deps = knolleary/PubSubClient

Compatibility

Supported boards

Arduino UnoESP32STM32 Blue Pill

Code

Examples

ESP32: connect, reconnect, subscribe and publish

A complete, working skeleton. It reconnects automatically, uses a unique client ID, calls loop() every pass and publishes every 5 seconds without blocking.

#include <WiFi.h>
#include <PubSubClient.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* MQTT_HOST = "192.168.1.10";   // your broker's IP or hostname
const uint16_t MQTT_PORT = 1883;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

unsigned long lastPublish = 0;

void connectWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void reconnect() {
  while (!client.connected()) {
    // client ID must be unique per device
    String clientId = "esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
    if (client.connect(clientId.c_str())) {
      client.subscribe("solderhub/led");
    } else {
      Serial.print("MQTT failed, rc=");
      Serial.println(client.state());   // see the state codes in the description
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  connectWiFi();
  client.setServer(MQTT_HOST, MQTT_PORT);
}

void loop() {
  if (!client.connected()) reconnect();
  client.loop();                         // required: keep-alive and incoming messages

  if (millis() - lastPublish > 5000) {
    lastPublish = millis();
    client.publish("solderhub/temp", "24.5");
  }
}

Handling incoming messages safely

The payload is not null-terminated, so copy it into a buffer first. This example switches the built-in LED on a message of ON or OFF.

void callback(char* topic, byte* payload, unsigned int length) {
  char msg[64];
  unsigned int n = (length < sizeof(msg) - 1) ? length : sizeof(msg) - 1;
  memcpy(msg, payload, n);
  msg[n] = '\0';                         // add the terminator yourself

  Serial.print(topic);
  Serial.print(": ");
  Serial.println(msg);

  if (strcmp(topic, "solderhub/led") == 0) {
    digitalWrite(LED_BUILTIN, strcmp(msg, "ON") == 0 ? HIGH : LOW);
  }
}

// in setup():
//   pinMode(LED_BUILTIN, OUTPUT);
//   client.setCallback(callback);

Publishing a larger JSON payload

Raise the buffer before connecting, then check publish() so a payload that is too big is never ignored silently. Uses ArduinoJson v7.

#include <ArduinoJson.h>

// in setup(), BEFORE the first connect:
//   client.setBufferSize(512);

void publishReadings(float temp, float hum) {
  JsonDocument doc;
  doc["device"] = "esp32-01";
  doc["temp"]   = temp;
  doc["hum"]    = hum;

  char buf[256];
  serializeJson(doc, buf, sizeof(buf));

  if (!client.publish("solderhub/sensors", buf)) {
    Serial.println("Publish failed - payload larger than the MQTT buffer?");
  }
}

Non-blocking reconnect

Tries to reconnect every 5 seconds without ever blocking, so the rest of your program (sensors, display, buttons) keeps running while the broker is down.

unsigned long lastAttempt = 0;

bool mqttReady() {
  if (client.connected()) return true;

  if (millis() - lastAttempt > 5000) {
    lastAttempt = millis();
    if (client.connect("esp32-01")) {      // use a unique ID per device
      client.subscribe("solderhub/led");
      return true;
    }
  }
  return false;
}

void loop() {
  if (mqttReady()) {
    client.loop();
  }
  // ...the rest of your program keeps running either way
}

Last Will and retained online status

The broker publishes 'offline' for you if the device disappears. Pair it with a retained 'online' message so Home Assistant and dashboards always show the true state.

const char* STATUS_TOPIC = "solderhub/esp32-01/status";

// connect(clientId, user, pass, willTopic, willQos, willRetain, willMessage)
if (client.connect("esp32-01", MQTT_USER, MQTT_PASS, STATUS_TOPIC, 1, true, "offline")) {
  client.publish(STATUS_TOPIC, "online", true);   // true = retained
}