"Failed, rc=-2" is the error almost everyone meets in their first MQTT project. The good news: every PubSubClient return code points to a specific layer (the network, the broker, or your login), and once you know which, the fix is usually one line.
Quick answer: rc=-2 means the ESP32 couldn't open a network connection to the broker: wrong IP or port, the broker isn't listening on the network (Mosquitto 2.0's default), a firewall, or the ESP32 isn't on Wi-Fi yet. rc=5 means it reached the broker but was not authorised: wrong username or password, or anonymous access is off. rc=4 is also a bad username or password. Test the broker with mosquitto_sub from a PC first; if that fails too, the problem isn't your sketch.
Every PubSubClient Return Code
Print it whenever a connection fails: Serial.println(client.state());
| Code | Name | What it means | Most likely fix |
|---|---|---|---|
| -4 | MQTT_CONNECTION_TIMEOUT | The broker stopped answering keep-alive pings | Weak Wi-Fi, broker overloaded, or loop() not called often enough |
| -3 | MQTT_CONNECTION_LOST | The network connection dropped | Wi-Fi dropout or broker restart; reconnect logic handles it |
| -2 | MQTT_CONNECT_FAILED | Couldn't open a TCP connection to the broker | Wrong IP/port, broker local-only, firewall, TLS mismatch |
| -1 | MQTT_DISCONNECTED | Cleanly disconnected (or never connected) | Normal before the first connect() |
| 0 | MQTT_CONNECTED | Connected | — |
| 1 | MQTT_CONNECT_BAD_PROTOCOL | Broker doesn't support the MQTT version | Very old broker; update it |
| 2 | MQTT_CONNECT_BAD_CLIENT_ID | Client ID rejected | Empty or invalid ID; use a unique, plain-text ID |
| 3 | MQTT_CONNECT_UNAVAILABLE | Broker can't accept connections right now | Broker overloaded or starting up |
| 4 | MQTT_CONNECT_BAD_CREDENTIALS | Username or password wrong | Check both; re-create the user |
| 5 | MQTT_CONNECT_UNAUTHORIZED | Not authorised to connect | No credentials sent, anonymous disabled, or user not allowed |
Negative codes are network problems, positive codes are the broker answering "no". That single rule tells you where to look.
Other libraries use different numbers: Mosquitto's own tools print text such as Connection Refused: not authorised, and Node-RED shows the node status disconnected or connecting. The causes below are the same.
Fixing rc=-2 (Connect Failed)
Work down this list; it's ordered by how often each cause turns up.
- Using
localhostor127.0.0.1on the ESP32. That address means the ESP32 itself. Use the broker's LAN IP, for exampleclient.setServer("192.168.1.20", 1883);. - Mosquitto 2.0 is listening only on the Pi itself. Since 2.0, a broker with no
listenerline refuses everything from other devices. Addlistener 1883and a password setup, as in installing Mosquitto on the Raspberry Pi. - Wrong port or TLS mismatch. 1883 is plain MQTT, 8883 is TLS. A
WiFiClientSecurepointed at 1883, or a plainWiFiClientat 8883, gives -2. - Wi-Fi not ready. Calling
connect()beforeWiFi.status() == WL_CONNECTEDfails instantly. Connect to Wi-Fi first. - Broker IP changed. The Pi got a new address from the router. Reserve it in the router's DHCP settings.
- Firewall or isolated network. Guest Wi-Fi often blocks device-to-device traffic, and a firewall on the broker PC can block port 1883 (Windows Defender Firewall commonly does when Mosquitto runs on Windows).
- TLS certificate problem (cloud brokers such as HiveMQ Cloud or EMQX on port 8883). The ESP32 needs the broker's root CA via
setCACert()and the correct time from NTP; wrong time or a missing certificate also shows as -2.
Prove it from a PC on the same Wi-Fi. If this also fails, the problem is the broker or the network, not your sketch:
mosquitto_sub -h 192.168.1.20 -p 1883 -t 'test/#' -u USER -P PASSWORD -vConnection refused from the PC points to the listener (item 2) or a firewall; a timeout points to the wrong IP or a blocked network.
Fixing rc=5 and rc=4 (Not Authorised, Bad Credentials)
The ESP32 reached the broker, and the broker said no.
- The sketch sends no username.
client.connect("esp32-1")connects anonymously. Withallow_anonymous false, that's rc=5. Useclient.connect("esp32-1", "user", "password"). - Typo in the user or password. Both are case-sensitive. Re-create the user on the broker to be sure:
sudo mosquitto_passwd /etc/mosquitto/passwd user(no-c, or every other user is deleted). - The password file isn't loaded. After editing the config, restart:
sudo systemctl restart mosquitto, then checksudo journalctl -u mosquitto -n 30. - An ACL or per-listener rule. With
per_listener_settings true, each listener needs its ownpassword_file; without it, the login fails on that port. - Cloud brokers often require TLS and a specific username format; copy both exactly from the broker's console.
Don't "fix" rc=5 by turning on allow_anonymous true on a broker other devices can reach: anyone on the network could then switch your relays.
Connected, But Something's Still Wrong
| Symptom | Cause | Fix |
|---|---|---|
| Two devices keep disconnecting each other | Same client ID | Make every ID unique, e.g. include the MAC: "esp32-" + WiFi.macAddress() |
publish() returns false, nothing arrives | Message larger than PubSubClient's 256-byte default buffer | client.setBufferSize(1024); before connecting |
| Connected, but subscribed messages never arrive | client.loop() not called often, or subscribed before connecting | Call loop() every pass; subscribe after each successful connect |
| Messages stop after a reconnect | Subscriptions aren't restored automatically | Subscribe again inside the reconnect code |
| Drops with rc=-4 every minute or so | loop() blocked by long delay()s, so keep-alives are missed | Replace delays with millis() timing; setKeepAlive(30) if needed |
| Topic receives nothing | Spelling or case differs (home/Lamp ≠ home/lamp) | Watch every topic with mosquitto_sub -t '#' -v |
| Old command replays at every boot | It was published with retain | Clear it: publish an empty retained message to that topic |
| JSON parse fails | Payload isn't what you expect | Print the raw payload first |
Test the Broker Without Hardware
Separate the broker from your firmware with three quick tests, each run in its own terminal:
# 1. On the broker: does it work at all?
mosquitto_sub -h localhost -t 'diag/#' -v -u USER -P PASSWORD
mosquitto_pub -h localhost -t 'diag/test' -m hello -u USER -P PASSWORD
# 2. From another computer: is it reachable over the network?
mosquitto_pub -h 192.168.1.20 -t 'diag/test' -m 'from my PC' -u USER -P PASSWORD
# 3. Is the login enforced? This one should FAIL with "not authorised"
mosquitto_pub -h 192.168.1.20 -t 'diag/test' -m 'no login'If all three behave as expected, the broker is fine and the problem is in the device. More test recipes are in test MQTT without hardware.
Read the Broker's Log
The broker usually tells you exactly why it refused a client:
sudo journalctl -u mosquitto -f # follow the log live, then reset the ESP32| Log line | Meaning |
|---|---|
New connection from 192.168.1.42 ... New client connected ... as esp32-1 | Success |
Client esp32-1 disconnected, not authorised. | rc=5: wrong or missing login |
Client esp32-1 already connected, closing old connection. | Duplicate client ID |
Client esp32-1 has exceeded timeout, disconnecting. | Keep-alive missed: loop() not called often enough |
| No line at all when the ESP32 tries | The connection never reached the broker: rc=-2 territory |
Error: Address already in use at start-up | Another broker or a duplicate listener line holds the port |
If Node-RED Is the Client
Double-click any MQTT node and edit its broker settings. If Node-RED runs on the same Pi as Mosquitto, the server is localhost; if it runs on another machine, or in Docker, use the broker's IP. Credentials go in the Security tab. The node status under the MQTT node shows connected, connecting (can't reach the broker: the rc=-2 causes) or disconnected. Watching messages with a debug node after an mqtt in set to topic # shows whether anything arrives at all. Full walkthrough: Node-RED with Mosquitto.
A Diagnostic Sketch for the ESP32
This prints each stage separately, so the Serial Monitor tells you which layer fails. It never prints the password.
#include <WiFi.h>
#include <PubSubClient.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* BROKER = "192.168.1.20";
const int PORT = 1883;
const char* MQTT_USER = "esp32-1";
const char* MQTT_PASS = "YOUR_MQTT_PASSWORD";
WiFiClient net;
PubSubClient client(net);
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(250);
Serial.printf("1. Wi-Fi OK, my IP %s, RSSI %d dBm\n", WiFi.localIP().toString().c_str(), WiFi.RSSI());
// 2. Can we open a raw TCP connection to the broker port?
if (net.connect(BROKER, PORT)) {
Serial.println("2. TCP to broker OK");
net.stop();
} else {
Serial.println("2. TCP to broker FAILED: wrong IP/port, no listener, or firewall (this is rc=-2)");
return;
}
// 3. MQTT login
client.setServer(BROKER, PORT);
String id = "esp32-diag-" + WiFi.macAddress();
if (client.connect(id.c_str(), MQTT_USER, MQTT_PASS)) {
Serial.println("3. MQTT connected");
client.publish("diag/esp32", "hello");
} else {
Serial.printf("3. MQTT refused, rc=%d (4 = bad credentials, 5 = not authorised)\n", client.state());
}
}
void loop() { client.loop(); }Once it connects, move to a proper reconnecting client: non-blocking MQTT auto-reconnect on the ESP32.
Quick Checklist
- Print
client.state(). Negative: network. Positive: login. - Broker IP, not
localhost, on every device except the broker itself. listener 1883in the broker config (Mosquitto 2.0+).mosquitto_subfrom a PC works with the same IP, port and login.- Username and password passed to
connect(). - Unique client ID per device.
client.loop()called every pass, no longdelay()s.- Re-subscribe after every reconnect.
FAQ
What does rc=-2 mean in PubSubClient? The TCP connection to the broker couldn't be opened. It's a network problem: wrong address or port, no network listener on the broker, a firewall, or a TLS mismatch.
What does rc=5 mean? The broker refused the login: not authorised. Send a valid username and password, and check the broker's password file.
Why does it work with test.mosquitto.org but not my own broker? The public test broker accepts anonymous connections on all interfaces. Your Mosquitto 2.x broker accepts neither until you configure a listener and users.
Why does my ESP32 connect, then drop every minute? Usually loop() isn't called often enough to answer keep-alive pings (rc=-4), or another device uses the same client ID.
Related: MQTT explained · ESP32 MQTT tutorial · ESP32 Wi-Fi troubleshooting




