knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.82k stars 1.47k forks source link

Can't connect to Broker #203

Closed wiktor-grochal closed 4 years ago

wiktor-grochal commented 7 years ago

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:

1474494793: New connection from 192.168.1.111 on port 1883.
1474494802: Client <unknown> has exceeded timeout, disconnecting.
1474494802: Socket error on client <unknown>, disconnecting.
1474494813: New connection from 192.168.1.111 on port 1883.
1474494822: Client <unknown> has exceeded timeout, disconnecting.
1474494822: Socket error on client <unknown>, disconnecting.
1474494833: New connection from 192.168.1.111 on port 1883.
1474494842: Client <unknown> has exceeded timeout, disconnecting.
1474494842: Socket error on client <unknown>, disconnecting.

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:

/*
 Basic MQTT example

 This sketch demonstrates the basic capabilities of the library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic"
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary

 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.

*/

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xBD, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 111);
IPAddress server(192, 168, 1, 100);

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(server, 1883, callback, ethClient);

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient1234")) {
      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(20000);
    }
  }
}

void setup()
{
  Serial.begin(57600);

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

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(5000);
  Serial.print("waiting 5s");
  client.connect("arduinoClient1234");
  delay(5000);
  if (client.connected()) {
    Serial.print("ok");
  }
  else {
    Serial.print("not ok");
  }

}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("outTopic","hello world");
  delay(5000);

}

if u need more information i will be happy to share

knolleary commented 7 years ago

What console output do you get from the sketch? Any indication where it is getting to in your code?

averri commented 7 years ago

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);
    }
}
knolleary commented 7 years ago

@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.

knolleary commented 7 years ago

Sorry, see that you did...

So is it just the 'attempting' message you get, or do you get the 'failed' message as well?

averri commented 7 years ago

Hi @knolleary , I get the 'failed' message. The result code is '-2':

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

knolleary commented 7 years ago

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?

averri commented 7 years ago

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

knolleary commented 7 years ago

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?

averri commented 7 years ago

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?

knolleary commented 7 years ago

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.

gilmntg commented 7 years ago

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

rannanda commented 7 years ago

Hi Averri, I add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password);. It works.

acestu commented 7 years ago

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

acestu commented 7 years ago

Hi,

Just tried the above fix but still get:

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

Thanks Stuart

amineBenguesmia commented 7 years ago

I have the same problem Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

any solution plz

chenirl commented 7 years ago

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);

ANierbeck commented 7 years ago

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.

chenirl commented 7 years ago

What versions of: Arduino IDE, PubSubClient

I use the latest IDE. PubSubClient 2.6.0

ANierbeck commented 7 years ago

Same here, latest in Arduino IDE / Sloeber PubSubClient 2.6.0

chenirl commented 7 years ago

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.

mitesh6036 commented 7 years ago

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.

knolleary commented 7 years ago

@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.

mitesh6036 commented 7 years ago

ohkk.. sorry.. will make a new issue..

ANierbeck commented 7 years ago

Just wanted to let you know, the failure is gone. It seems to have been an issue with my local wifi infrastructure.

Midgie75 commented 7 years ago

Rannandas suggestion helped in my case. I had the same trouble with connection fails to mongoose mqtt broker.

roboticboyer commented 7 years ago

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

mrohner commented 7 years ago

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?

chenirl commented 7 years ago

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.

thiagodasilva commented 7 years ago

Hello, I'm running into the same problem and addingWiFi.mode(WIFI_STA); did not solve it for me. Any other ideas?

lelcuk commented 7 years ago

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....

lelcuk commented 7 years ago

after further investigation, once I shutdown websockets listener in the 1.4.14 everything works again

mrohner commented 7 years ago

How do you do that "shutdown websockets listener"

DarrylMG commented 7 years ago

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

ahmedyounes commented 7 years ago

I have the same issue, wish that there is any solution

hotkeymuc commented 7 years ago

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.

fooman commented 6 years ago

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.

cmoine commented 6 years ago

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

apeeters commented 6 years ago

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

klaasdc commented 6 years ago

@apeeters I tried the ESPLOGLEVEL change in debug.h and at top of ino, but no change in behavior for me.

apeeters commented 6 years ago

@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

klaasdc commented 6 years ago

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.

Bagunda commented 6 years ago

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...

felipedmsantos95 commented 6 years ago

Have you verified that your firewall is enabled? I was having this same problem and disabling it was the solution.

felipedmsantos95 commented 6 years ago

Search and allow your broker MQTT in firewall settings, if you´re using windows. @Bagunda

Bagunda commented 6 years ago

@felipedmsantos95. Firewall is OK. Another tests is work. Server - Debian (Raspbian, OpenHabian).

ZachMyers3 commented 6 years ago

I'm also having trouble connecting, using an ESP8266 with WiFiClient...

A few things I've debugged so far:

  1. I'm able to connect to my broker within the same network on other machines and other clients. Both publishing and subscribing.
  2. I am able to connect to the WiFi network with my ESP8266 and am able to use WiFiClient for other purposes with success (scraping a simple html page, etc.)
  3. I'm not recieving any feedback from the broker (mosquitto, have also tried HiveMQTT) at all when attempting to connect from the ESP8266.
  4. I have tried simple sketches of connecting just to WiFi and doing this and this works, but a simple sketch (like the ones linked in this thread) to connect to MQTT have failed.

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

carnifex82 commented 6 years ago

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.

dustXman commented 6 years ago

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 ;)

captnbp commented 6 years ago

Hi,

I solved the issue the same way @carnifex82 did. I replaced WiFiClientSecure by WiFiClient

dustXman commented 6 years ago

In my case switching the DNS Server from a special one back to the Default in my AVM FritzBox Router solved the issue...