ESP8266 Unable to Connect to MQTT Broker (rc=-2)

Hello,

I am trying to control an LED using ESP8266 via MQTT in Node-RED. The MQTT broker is running on my local machine, and the Node-RED debug node correctly shows the switch payload ("ON"/"OFF"). However, my ESP8266 fails to connect to the MQTT broker, showing the following error:

Attempting MQTT connection...Failed, rc=-2 Trying again in 5 seconds

Wi-Fi is connected successfully, and the correct IP address is assigned. The MQTT broker is also running, and messages are being published from Node-RED.

Hi, strictly speaking, this is not a node-red issue but no worries, let's get you up and running.

Since you have not stated which broker or version, I will assume Mosquitto v2.x.

As of Mosquitto v2 the default config will only bind to localhost (secure by default).

If you want to access the broker from other machines on your network (i.e. your esp) you will need to edit the config to either add a new listener that binds to the external IP address, or 0.0.0.0, or add a bind entry for the default listener.

More details in the v2.0 release notes: Version 2.0.0 released. | Eclipse Mosquitto

I prefer to add a config override file (so it will survive a mosquitto upgrade). To do that,assuming you are running on a Debian based system such as the PI OS, you can add a .conf file to /etc/mosquitto/conf.d/. For example you could create a file /etc/mosquitto/conf.d/mossy.conf containing

# Since mosquitto 2.0, have to specify listener and allow anonymous
listener 1883
allow_anonymous true

If you would like human readable timestamps in the log then also add

log_timestamp true
log_timestamp_format %Y-%m-%d %H:%M:%S
3 Likes