Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempting MQTT connection...failed, rc=-2 try again in 5 seconds #185

Open
mohitsachan33 opened this issue Jul 29, 2016 · 40 comments
Open

Comments

@mohitsachan33
Copy link

// Control ESP8266 anywhere
// Import required libraries

include <ESP8266WiFi.h>

include <PubSubClient.h>

include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);
// Create aREST instance
aREST rest = aREST(client);
// Unique ID to identify the device for cloud.arest.io
char* device_id = "e49n2di";
// WiFi parameters
const char* ssid = "Quasar";
const char* password = "quablu49476";
// Functions
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Set callback
client.setCallback(callback);

// Give name and ID to device
rest.set_id(device_id);
rest.set_name("relay_anywhere");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Set output topic
char* out_topic = rest.get_topic();
}
void loop() {
// Connect to the cloud
rest.loop(client);
}
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
rest.handle_callback(client, topic, payload, length);
}

this is my code and when i opened serial monitor in arduino ide then continuously its shows like--

..
WiFi connected
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...Connected to aREST.io
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...Connected to aREST.io
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...Connected to aREST.io
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

@knolleary
Copy link
Owner

Have you checked one of the basic http examples to verify you have the network configuration and setup correct? -2 means it's failing to create a network connection to the broker.

@cvramanan
Copy link

I too get the same error

@foadem
Copy link

foadem commented Jul 31, 2017

I get the same error

@DarrylMG
Copy link

It actually worked once for me a whole day just like it is suppose to. Powered all off at night and the next day it will not work, get the same message as above, and has not worked since, no matter what machine I try it on.
thank you
any ideas

@maovidal
Copy link

Issue #[203] is related

@pirelly
Copy link

pirelly commented Nov 26, 2017

You can have one more client in the network the same MQTT Client ID. I have the same problem but I found that I have two clients with the same Client ID.

@alwashe
Copy link

alwashe commented Aug 24, 2018

Same Problem here.
I am able to connect to broker.mqttdashboard.com
I get the same error when trying to connect to a local broker: reconnect...failed, rc=-2 try again in 5 seconds
I am able to connect to the local broker over a Windows Client without any Problems.

`#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#include "DHT.h"

DHT dht(2, DHT22);

const char* ssid = "Funkzelle1212";
const char* password = "Password";
const char* mqtt_server = "openhab1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
dht.begin();

}

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
}

}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("reconnect...");
// Attempt to connect
if (client.connect("ESP8266Client1235")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("tempo", "halo world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.println(WiFi.localIP());
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
delay(5000);
float h = dht.readHumidity();
float t = dht.readTemperature();

if (!client.connected()) {
reconnect();
}

client.loop();

snprintf (msg, 75, "T: %.1f" , t);
client.publish("tempo", msg);

// snprintf (msg, 75, "Nr %d", value);
// client.publish("tempo", msg);

}`

@Raja-Raman
Copy link

try adding
WiFi.mode(WIFI_STA);
before attempting wi-fi connection. See this thread:
#138

@alwashe
Copy link

alwashe commented Aug 27, 2018

it was the host, it works with ip adress:
solved: #486 (comment)

@marcos2069
Copy link

The connection to my MQTT broker on a raspberry worked for months... probably after an upgrade it started to fail, but not always... just most of the time. The solution for me was to move to broker from wireless to wired. Now using the wired-ip it works, on the wireless-ip most of time not!

@kolalde
Copy link

kolalde commented Apr 9, 2019

Any recent comments on this? I've got two boards, running the same code with some local changes (like client/host name, etc). Both publishing to the same wired MQTT broker.

For some reason I don't understand, one (or the other) will start reporting a MQTT connection failure that it doesn't recover from. The other board won't exhibit the condition.

Very infrequent, resetting the chip clears the issue. Durring the failure condition, other wifi functions are working, for instance I can still get weather over a different WiFiClient.

I've not yet tried either the items suggested here:

  • WiFi.mode(WIFI_STA) call
  • moving to referring to the broker by IP instead of hostName.local

Thought I'd ask before taking shots. Thanks,

@Rajkumar181
Copy link

Same problem i am facing now. it is not able to reconnect again. when MQTT Broker is running that time its working fine. When i restarted the MQTT Broker is not able to reconnect.

Attempting MQTT connection...failed, rc=-2
Attempting MQTT connection...failed, rc=-2

@lazarusCantini
Copy link

Hey I've got the same Problem here. Looking for a Solution for three days, today nothing changed, it works. I know this is the wrong location for this Question, but I found no solution for this: My Mosquitto MQTT Broker (running at a Ubuntu Mashine) is on Protocol Version 3.1. How can I change it to Version 3.1.1?
Kindly regards,
Bastian

@anderl80
Copy link

Same problem here...

@Spackstor
Copy link

When this happens to me, I reload 0x00000 bin file using esp_flasher and presto, problem goes away.

@kravviec
Copy link

kravviec commented Jan 5, 2020

I had a similar issue (connecting and reconnecting in 8-10 sec), the solution was changing the place of some variables used inside loop() function.

@manuelfgm
Copy link

I solved this issue this way (similar thread): #604 (comment)

@niteshydv
Copy link

My raspberry pi worked as a broker and esp8266 as client. whenever raspberry pi disconnected from wifi network and reconnected, i had this issue of esp disconnecting and could not reconnect. I tried to reconnect esp to the raspberry wifi by disconnecting WiFi.disconnect(), and it worked.

@Pi-And-More
Copy link

I had the same issues and it was driving me mad because I had it working and after delivering a few working devices (and of course updating my code). It stopped working. I finally figured it out. I changed the mqttServer from a DNS name to an IP. I just changed it back without changing anything else and the error disappeared.

@climategadgets
Copy link

climategadgets commented Apr 13, 2020

My ¢2, in case it helps:

One thing that nobody mentioned above is VLAN, I'm running this on a tightly locked network.

UPDATE: VLAN matters.

@Pi-And-More
Copy link

Changing from IP to server name like I mentioned before was not the answer unfortunately. I do however have something stable working now. I found that frequently the code does not connect after initial upload but does connect after a restart. What I have done is count the number of connect attempts and if there are more than 3 in succession I restart the ESP. If it connects, I reset the counter. Don’t know why but it works quite well. I have 15 ESPs connected this way know to my Domoticz MQTT and can see they report in every 2 minutes.
Also found, slightly related, that you cannot post multiple messages after each other to the broker because it will freeze your ESP. You need to give it a little time. I don’t post often so I build in maximum of 1 message per second.

@climategadgets
Copy link

I figured it out - the connection fails on Client::connect() level if the target host is on a VLAN'd network. It is irrelevant whether that clone is VLAN'd or not, only target matters.

@eku
Copy link

eku commented Apr 14, 2020

@climategadgets VLAN should be transparent at IP level.

@climategadgets
Copy link

@eku That would be my expectation, too. Here's the facts: several MQTT brokers, different platforms, some of them on VLAN, some not. Independently, several WiFi networks, some on VLAN, some not. The only case when connect() fails is when the target is on VLAN'd network, nothing else matters. I'll have time for more tests tonight, will see if there are any other variables I could overlook.

@Pi-And-More
Copy link

I don’t think it’s just a VLAN problem as I have seen it on public internet addresses as well

@ingeltro
Copy link

ingeltro commented May 6, 2020

Hola bueno por si le sirve a alguien, el problema es cuando se pasa al bróker a través de un repetidor Wifi, extensor Wifi, o si es un bróker local se esta utilizando el Wifi, solo sucede con el esp8266, si utilizan el ESP32 no tendrán ese problema, saludos

@climategadgets
Copy link

@ingeltro , I think it may not be the ESP8266 per se, but the particular TCP/IP stack implementation for it on this platform. I almost gave up on ESP8266 as well, but then tried https://esphome.io/components/mqtt.html and, surprisingly, it worked.

@LMA-Robotics
Copy link

You should modify this line in the example code if you are using a secure account on your MQTT broker
client.connect(clientId.c_str(),"username","password")

@pkerspe
Copy link

pkerspe commented Jun 18, 2021

For those of you who have this issue and using WiFiClientSecure at the same time: I ran into this issue too and basically I had an issue with the certificates I provided to WiFiClientSecure.
So if you feed it the wrong or no certificates you will get the above mentioned error message as well, since the pubsub client will not be able to open the SSL Secure HTTP connection.
If you are not connecting to a secured broker and you do not use certificates, than this probably will not help you. But at least in my case it was the issue.

@VeeruSubbuAmi
Copy link

I found this video as a problem solver, This may help you.
All MQTT Errors explained very well and Suggester Different trouble shooting techniques
https://youtu.be/CbodTTk-D18

@Jayendrarnaik
Copy link

Hello,
I was facing same issue with the locally installed mosquitto broker on my windows system. I thought that it is the iasue with the windows firewall inbound, but it was not . Then i came to realise that the it is the issue with the mqtt server id that is " my PC's physical address" it changed from "1**..105." to "1**..158.". Then i changed the mqtt server id it worked fine.
Go to settings ->network and internet->view hardware properties-> check the wifi ipv4 address
Uploading 16250314510046044569794395893882.jpg…

@Xesphome
Copy link

@ingeltro , I think it may not be the ESP8266 per se, but the particular TCP/IP stack implementation for it on this platform. I almost gave up on ESP8266 as well, but then tried https://esphome.io/components/mqtt.html and, surprisingly, it worked.

Would you please share the code you used and worked? I am using:

mqtt:
broker: broker.mqttdashboard.com
port: 8000

But I can't connect. Thanks for your help

@climategadgets
Copy link

@Xesphome , https://esphome.io/components/mqtt.html. I eventually just ported all the sensors and actuators to it, and there was no longer a need for custom code.

@egamor18
Copy link

egamor18 commented Feb 3, 2022

I had this problem. It turned that the reason for this -2 connection status was the broker; It was down. I turned the mosquitto broker on and the issue was resolved.

@b0ssi
Copy link

b0ssi commented May 30, 2022

Hopefully this will be of use to some: The not-quite-underlying but mid-layer reason in a case I had run into was that the Arduino framework, in my case its core, referenced by Espressif platform libraries I was using, had been updated to a new major version, including an array of breaking changes. Both, Arduino Core (implicitly referenced by the Espressif platform) and the Espressif platform (context: PlatformIO) were bumped to 3.0.0. Forcing back to 2.x.x solved the issue, though I didn't investigate further as to what the underlying causes had been.

Symptoms were as described numerous times above: WiFi connected, acquired IP through DHCP just fine but PubSubClient kept failing to connect (rc: -2).

I'd be happy to test if it might help in finding the root cause. I'm fairly certain my setup is as described in the examples (at least hasn't changed since in the last ~1.5 years) but I haven't tried to isolate the setup as complexity would make it a bigger effort.

@MaherDyayn
Copy link

Hi I have a Teensy 4.1 and im using the Nativeethernet library and Pubsubclient library to connect to MQTT.
My MQTT broker in running locally on my PC and is named "localhost" and port 1883
I am running the mqtt_basic example in the Pubsubclient library and keep gettign this rc=-2 error
this is the code
should I change server name or IP address or something
`#include <SPI.h>
#include <NativeEthernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[6];
IPAddress ip(172, 16, 0, 100);
//IPAddress server(142, 66, 215, 171);
const char* server = "localhost";
void teensyMAC(uint8_t mac);
void callback(char
topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

EthernetClient ethClient;
PubSubClient client(ethClient);

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection....");
// Attempt to connect
if (client.connect("localhost1122")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("Sensor","hello world");
// ... and resubscribe
//client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void setup()
{
Serial.begin(57600);
teensyMAC(mac);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
}
else
{Serial.println("Success");}

client.setServer(server, 1883);
client.setCallback(callback);

Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}

void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}

void teensyMAC(uint8_t *mac)
{for(uint8_t by=0; by<2; by++) mac[by]=(HW_OCOTP_MAC1 >> ((1-by)*8)) & 0xFF;
for(uint8_t by=0; by<4; by++) mac[by+2]=(HW_OCOTP_MAC0 >> ((3-by)*8)) & 0xFF;
Serial.printf("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}`

@Kyuugeki
Copy link

Kyuugeki commented Oct 5, 2022

If there is someone facing this problem, i found the solution.

By default, Mosquitto only listen to local connections (127.0.0.1)
You need to add this line to /etc/mosquitto/mosquitto.conf so mosquitto will listen to all interfaces (0.0.0.0)

listener 1883 0.0.0.0

And more important: If you're using the examples from PubSubClient, you might notice that they doesn't use client authentication, so this line must also be in yout config file:

allow_anonymous true

Hope it helps!

@rmdvector
Copy link

rmdvector commented Mar 8, 2023

I'm getting this error on a new ESP8266 node. I've allowed anonymous connections, and am listening on 0.0.0.0. The other two nodes connect, but this last one fails with rc=-2 continuously. From /var/log/mosquitto/mosquitto.log I don't even see an attempt to connect.
Should add that the ESP8266 is getting an IP, and I can ping it from other hosts on the network.

@SteinVT2
Copy link

SteinVT2 commented May 4, 2023

The fix from Kyuugeki worked for me. Thank-you

@reiniheini
Copy link

I tried the fix off Kyuugeki but unfortunately the problem remains the same.
Mosquitto log file is showing "protocol error" until some time the ESP conncects successfully. (This can take up to 30mins)

Weirdly I found a way to force the conncection by just starting a terminal conncection to the raspberry from a computer in the same network. (just opening putty conncection is enough, password wasn't provided yet for the terminal but this somehow makes the ESP8266 connect suddenly to the MQTT server)

Has somebody an idea what could be the reason behind that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests