Closed wiktor-grochal closed 4 years ago
What console output do you get from the sketch? Any indication where it is getting to in your code?
Hi @knolleary, I'm having the exact same issue. I'm using Mosquitto, running inside Docker, and I have tested it using other MQTT clients with success: https://github.com/toke/docker-mosquitto
But the client using this library does not connect. Please see the example code bellow. In this example, the code keep printing "Attempting MQTT connection..." indefinitely.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "MyNet";
const char* password = "MyNetPassword";
const char* mqtt_server = "192.168.99.100";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "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(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}
@averri sorry to hear that.. perhaps you could also answer the same questions I asked in my previous comment. I cannot help without that information.
Sorry, see that you did...
So is it just the 'attempting' message you get, or do you get the 'failed' message as well?
Hi @knolleary , I get the 'failed' message. The result code is '-2':
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Ok, -2 means the network connection couldn't be established - this is before it gets to anything in this library.
I assume you get the "WiFi connected
message at the beginning? And that 192.168.99.100
is definitely the right IP address of your broker?
Have you tried one of the ESP8266 example sketches (such as the http client one) to verify your hardware setup?
Yes, I have tested, the WiFi is working fine:
Connecting to MyNet
WiFi connected
IP address:
192.168.1.159
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
The IP 192.168.99.100 is the Docker host IP, where the Mosquitto container is running. I have tested the Mosquitto using mqtt-spy client with success.
Are you able to test with Mosquitto running on Docker? docker run -ti -p 1883:1883 -p 9001:9001 toke/mosquitto
Where did you run mqtt-spy? Was it on the same machine as was running docker? Have you tried mqtt-spy from another machine on the network?
Yes, mqtt-spy is running on the same machine as Docker. Tested on a different machine and it works too. Is it possible to enable debugging in the library?
The -2
means the underlying WiFiClient
could not establish a tcp connection to the broker. There's nothing in PubSubClient
that affects this. This is why I suggest you test with one of the other ESP8266 examples that don't involve this library to rule out anything to do with the basic setup.
I have the same issue also. In my case, I suspect its related to the fact that my raspberry pi running mosquitto is connected to network using a wifi dongle, and this dongle "goes to sleep" after a long no activity period. Getting back up after missing some received packets takes it some time, and then connection is established. I have the same issue also when trying to ssh to the raspberry-pi from my windows machine, and also, after few seconds, connection succeeds
Hi Averri, I add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password);. It works.
Hi,
My sketches used to connect to the mqtt server about 2 months ago, however I have a number of boards that just give the above errors, has anyone had any luck with the issues ?
Thanks Stuart
Hi,
Just tried the above fix but still get:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Thanks Stuart
I have the same problem Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
any solution plz
Try This:
Use: IPAddress mqttServer(xxx.xxx.xxx.xxx); Instead of: const PROGMEM char* mqttServer = "xxx.xxx.xxx.xx"; For your setServer: mqttClient.setServer(mqttServer, mqttPort);
Hi, I seem to have a similar issue here. It's neither working for my own script nor working with the Basic ESP8266 MQTT sample.
the following is in my output:
Connecting to homeNet
....wifi evt: 0
.wifi evt: 3
.
WiFi connected
IP address:
192.168.178.60
Attempting MQTT connection...[hostByName] request IP for: mqttServer
[hostByName] Host: homecontrol IP: 192.168.178.50
:ref 1
:wr
:ww
pm open,type:2 0
:ur 1
:close
:del
failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...[hostByName] request IP for: mqttServer
[hostByName] Host: homecontrol IP: 192.168.178.50
:err -8
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...[hostByName] request IP for: mqttServer
[hostByName] Host: homecontrol IP: 192.168.178.50
:err -8
failed, rc=-2 try again in 5 seconds
so the first time I do have a -4, all following connection attempts are -2 Any hints to where to look for a resolution for this would be helpful.
What versions of: Arduino IDE, PubSubClient
I use the latest IDE. PubSubClient 2.6.0
Same here, latest in Arduino IDE / Sloeber PubSubClient 2.6.0
Interesting, the only difference i see between us is that i use Arduino Mega with Ethernet.
on a different note i have a sonoff working with this: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino it is a bit fiddly but if you read the instructions it works! the topic is a bit inverse from all the tutorials, i use: platform: mqtt name: "Sonoff-2" state_topic: "status/sonoff/POWER" command_topic: "switch/sonoff/Power" optimistic: false in homeassistant yaml file.
I Hope this Helps.
Hii, I am new user to mqtt. Kindly support for my few basic question. I have implemented mqtt with pubsubclient.h and it works absolutely fine without any issue. But I am facing an issue when my server is down.. When my server is down or if my LAN connection is broken with my router it takes around 5 secs to get detected and connect and because of that I am unable to function my other functionalities.
Please find my reconnect loop below.
void reconnect() { // Loop until we're reconnected if (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect client.connect("ESP8266Client"); if (client.connect("ESP8266Client")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(outTopic, "MCU Active"); // ... and resubscribe client.subscribe(inTopic); } else { Serial.println("failed"); } } }
Immidiate support will be greatful. Thanks all.
@mitesh6036 please don't add your own question onto someone else's issue. Raise a new issue and someone may be able to help there.
ohkk.. sorry.. will make a new issue..
Just wanted to let you know, the failure is gone. It seems to have been an issue with my local wifi infrastructure.
Rannandas suggestion helped in my case. I had the same trouble with connection fails to mongoose mqtt broker.
For ESP8266 the solution of the issue is;
Add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password);
https://github.com/knolleary/pubsubclient/issues/203#issuecomment-274112911 such as suggested by @rannanda
See #https://github.com/martin-ger/esp_wifi_repeater/issues/44#issuecomment-304994741
My sketches used to connect to the mqtt server about 2 months ago, however I have a number of boards that just give the above errors, has anyone had any luck with the issues>
Same here, I run tasmota on 10 ESP-01 and 3 sonoffs. One ESP-01 and one sonoff cannot connect to mosquitto MQTT. The two devices get " Attempting MQTT connection...failed, rc=-2". Same hardware, same configuration, same network, same sw on the other devices work perfectly. Still do not know what could be the problem.
Should I toss the two failing ESPs?
Are you connecting all the devices at once? If so change the ip addresses the Client name and the topics so each one Is unique.
Also if ur changing them over quickly, you might have an ARP table issue, it depends how long your server caches MAC addresses.
Hello, I'm running into the same problem and addingWiFi.mode(WIFI_STA);
did not solve it for me. Any other ideas?
Having the same issue, running 2.0.0. dev 11 not sure this will help however when connecting to one mosquitto version 1.4.14 I get the error when connecting to another server running mosquitto version 1.4.12 no issues....
after further investigation, once I shutdown websockets listener in the 1.4.14 everything works again
How do you do that "shutdown websockets listener"
Hello: I have the same problem. using a ESP12E DEVKIT from DOIT. Run a local WiFi program, works great. Load a sketch using cloud.arest.io using latest Arduino IDE. And guess what works perfect. Try it a day later and now it does not work. Get that MQTT failed rc=-2 try again later. It has never worked again, same hardware, same software, same everything, nothing but this MQTT error message. I have no idea how to correct this. Tried on a completely different system in a different location, get exact same results. The hardware works perfect on my local wifi sketch, solid as a rock. Thanks for listening..any ideas DarrylG
I have the same issue, wish that there is any solution
This seems to be a common problem when using ESP8266 + Mosquitto broker.
I also had a perfectly working set-up with multiple ESPs and MQTT libraries and they suddenly started showing the same "failed rc=-2" error. Once it starts, there is no way to recover.
The solution is very unexpected:
Explicitly add a
WiFi.mode(WIFI_STA);
before
Wifi.connect(....);
I could not believe it myself, but that seems to reset the wifi module to a sane state.
I also encountered the "failed rc=-2" error combined with Socket error on client <unknown>, disconnecting.
in the mqtt log.
I am using the Arduino WiFiEsp library and setting #define _ESPLOGLEVEL_ 0
here
https://github.com/bportaluri/WiFiEsp/blob/v2.2.1/src/utility/debug.h#L31 made it work for me. I believe there was some debugging output sent via Serial which interfered with the correct communication with the mqtt server.
I personnally had error -4, because my server was running MQTT 3.1 by default on my Raspberry (https://www.raspberrypi.org/forums/viewtopic.php?t=95952), instead of 3.1.1 :-O
The solution provided by @fooman solved it for me. This happens when Serial instead of softserial is used for communication with the esp8266.
A fix has been implemented in WifiESP, but not released yet: https://github.com/bportaluri/WiFiEsp/issues/88
@apeeters I tried the ESPLOGLEVEL change in debug.h and at top of ino, but no change in behavior for me.
@klaasdc Then there is probably more output on Serial. Please refer to these issues for a fix: https://github.com/bportaluri/WiFiEsp/issues/84 https://github.com/bportaluri/WiFiEsp/pull/124
I found out that my problem was related to a bug in my code. Because of a mix-up, the stop() on the pubsubclient WifiClient was called sometimes. Of course the connection to the broker was lost then.
I have the same problem. Attempting MQTT connection... failed, rc=-2. Mosquitto server i try 1.4.10 and 1.4.15. My hardware: Arduino Mega 2560 and W5100 module (not shield). Library: SPI.h, Ethernet.h. I dont found solution in internet. Any solution plz...
Have you verified that your firewall is enabled? I was having this same problem and disabling it was the solution.
Search and allow your broker MQTT in firewall settings, if you´re using windows. @Bagunda
@felipedmsantos95. Firewall is OK. Another tests is work. Server - Debian (Raspbian, OpenHabian).
I'm also having trouble connecting, using an ESP8266 with WiFiClient...
A few things I've debugged so far:
Here is my serial output:
(i) [WIFI] Connecting to [network].. [WIFI] Already connected, exiting
(i) [WIFI] IP: 192.168.1.230
(i) [OTA] Started
(i) [MQTT] Logging in as client WeMosD1-[mac]-b3
(e) [MQTT] Connect failed rc=-2, trying again
(e) [MQTT] Connect failed rc=-2, trying again
This sketch was working previously but the project was sidelined, now that I'm picking things up again this is no longer is working. I'm happy to provide any more information and any insight on what to try/do next would be greatly appreciated.
Update:
Using the same setup as I was previously using with PusSubClient I was able to get MQTT working with Arduino-MQTT
Hi guys,
I had the same problem and found this thread while trying to fix it. I have a solution that wasn't mentioned here before, but also might not work for most of you, because you already have it in your code.
I was using WiFiClientSecure wifiClient;
Now I changed to: WiFiClient wifiClient;
And suddenly it's working.
I am having the same problem as @averri
Everything was working for ESP8266 and mosquitto on a Raspberry. Now I moved the mosquitto into a Docker (pascaldevink/rpi-mosquitto) and the ESP is returning "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" every 5 seconds. The mosquitto inside the docker is working fine for several other mqtt clients.
Would be great to know how @averri solved his issue ;)
Hi,
I solved the issue the same way @carnifex82 did. I replaced WiFiClientSecure
by WiFiClient
In my case switching the DNS Server from a special one back to the Default in my AVM FritzBox Router solved the issue...
Hi, i cant connect to broker on my raspberry. Broker: Mosquitto 1.4.10
on serial i m getting rc=-2 acording to documentation it is network connection failed. On mosquitto log i m getting
New connection from 192.168.1.111 on port 1883
for the first few minutes and then these errors occur:As you can see networking seems fine and there is some other issue with communication between arduino and rpi. Remote client on my laptop connects to the broker without any problems.
Hardware i m using is: arduino nano with ethernet shield (the one with the sd card slot)
my sketch: basicly copied example with delay between connections rised to 20s:
if u need more information i will be happy to share