Print client.state() after a failed connect. The number tells you where it failed.
What the message means
The state is -4 for a timeout, -3 for a lost connection, -2 when the network connection failed, -1 when disconnected, and 1 to 5 for refusals by the broker.
Fix it in this order
- State -2: check the broker address and port, and that the board is on the network. Port 1883 is the usual plain port.
- State -4: check the network and any firewall between you and the broker.
- State 2: the client ID was rejected. Use a unique ID for each device.
- State 4 or 5: check the user name and password, and the access rules on the broker.
- Call client.loop() often, and reconnect when the state is not 0.
- Raise the buffer size with setBufferSize if large messages fail to publish.
If you see this, do this
| You see | Do this |
|---|---|
| -2 on every try | Address, port or network. |
| 4 or 5 | Credentials or permissions. |
Related
MQTT on the ESP32, Wi-Fi keeps disconnecting.
Last reviewed: November 2026. These are the usual causes and the order that finds them fastest. Test on your own board; clones and cables differ.