esp32mqttwifi

Resolving MQTT Disconnect Loops on ESP32 with WiFi Drops

7 September 2026

What causes this

The MQTT disconnect loop on ESP32 often stems from WiFi instability, particularly when the device frequently loses and regains WiFi connectivity. The ESP32's WiFi driver, part of the ESP-IDF, manages this through the WiFiGenericClass::handleEvent function, but persistent fluctuations can cause repeated disconnections from MQTT brokers. Key registers like WIFI_EVENT_STA_DISCONNECTED and WIFI_EVENT_STA_CONNECTED are involved, often triggering a cascade of SYSTEM_EVENT_STA_DISCONNECTED events. The MQTT client, commonly using the PubSubClient library, detects these disconnects and attempts to reconnect, entering a loop if the WiFi connection is unreliable. Error codes such as ERR_WIFI_NOT_CONNECT or ERR_MQTT_NOT_CONNECTED appear in logs, indicating the underlying issue.

Minimal reproduction

The issue can be recreated with a basic setup that involves an unstable WiFi environment:

```cpp

#include

#include

const char* ssid = "yourSSID";

const char* password = "yourPASSWORD";

const char* mqttServer = "mqtt.example.com";

int mqttPort = 1883;

WiFiClient espClient;

PubSubClient client(espClient);

void setup() {

Serial.begin(115200);

WiFi.begin(ssid, password);

client.setServer(mqttServer, mqttPort);

}

void loop() {

if (WiFi.status() != WL_CONNECTED) {

Serial.println("WiFi not connected");

delay(1000);

return;

}

if (!client.connected()) {

Serial.println("MQTT not connected");

if (client.connect("ESP32Client")) {

Serial.println("Connected to MQTT");

} else {

Serial.print("failed with state ");

Serial.println(client.state());

delay(2000);

}

}

client.loop();

}

```

Expected Serial Output / Backtrace:

```

WiFi not connected

MQTT not connected

failed with state -2

WiFi connected

Connected to MQTT

WiFi not connected

MQTT not connected

```

The fix

The solution involves improving the resilience of both WiFi and MQTT connections. Implement exponential backoff in reconnection attempts and leverage WiFi event handling to ensure stability.

Before:

```cpp

if (!client.connected()) {

if (client.connect("ESP32Client")) {

//...

}

}

```

After:

```cpp

long lastReconnectAttempt = 0;

void loop() {

if (WiFi.status() != WL_CONNECTED) {

Serial.println("WiFi not connected");

delay(1000);

return;

}

if (!client.connected()) {

long now = millis();

if (now - lastReconnectAttempt > 5000) {

lastReconnectAttempt = now;

if (reconnect()) {

lastReconnectAttempt = 0;

}

}

} else {

client.loop();

}

}

bool reconnect() {

if (client.connect("ESP32Client")) {

Serial.println("Connected to MQTT");

return true;

} else {

Serial.print("failed with state ");

Serial.println(client.state());

return false;

}

}

```

How SerialDoctor catches this

SerialDoctor rapidly analyzes serial output to pinpoint root causes like MQTT disconnect loops. By parsing error codes and event logs, it identifies patterns indicating unstable WiFi and MQTT connectivity issues. Visit [serialdoctor.com](https://serialdoctor.com) for a quick diagnosis that saves hours of debugging.

Quick checklist

  • Ensure WiFi signal strength is strong and stable.
  • Implement exponential backoff for MQTT reconnections.
  • Use WiFi event handling to detect and manage connection changes.
  • Regularly update ESP-IDF and libraries to latest versions.
  • Consider using a WiFi manager library for enhanced connection management.

Seeing this crash on your board right now?

Connect it to SerialDoctor and get a root cause + code fix in under 3 seconds.

Try SerialDoctor free →