Pubsubclient: Can't connect to Broker

Created on 21 Sep 2016  Â·  90Comments  Â·  Source: knolleary/pubsubclient

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

Most helpful comment

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

All 90 comments

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:

  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

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

I was able to fix it by placing the following before I set up my mqttClient.

if(wifiClient.connect(mqtt_server, 80)){
Serial.println("Wifi client connected");
}

mqttClient.setServer(mqtt_server, 1883);
mqttClient.setCallback(callback);

I was able to solve the issue on an ESP8266 connecting to MQTT broker running on my
Raspberry PI by adding the following to the reconnection loop after failure

if(wifiClient.connect(MQTT_SERVER, 1883))
{
Serial.println("Wifi client connected to 1883");
}
It appears that doing a simple wifi connect clears the issue. Similar logic that alcialex offered above.

Have running 6 tasmota flashed Sonoff Clone identical devices and all where running fine.
Until one day, one of them started suddenly to have the issue described here: Connecting to mqtt server returns -2 and does not respond to mqtt command anymore.
All of these devices are using the same wifi router and the same wifi password.
However, web interface and REST interface ( of the mqtt damaged device ) are working fine.
I'm running the following setup:
Mqtt Server in docker container (image) eclipse-mosquitto on a ubuntu server.
Im using a mqtt password protection, so the suggestions to use the "not secure" wificlient is no option for me.
What I have tried to far without success was:
-Using a plain mosquitto server outside a docker container
-Using another mosquitto user
-Using the Serial.println after connection.
-Reseting image and configuration and reflashing the whole device.
When investigating the mosquitto server log, however I do see the connection tries of the device.
It is really a very strange problem. If anyone has more hint for a solution, feel free to write it down here.

The following seems to have resolved my issue. I am running the client on an esp8266 and the broker on a Raspberry Pi. I found the reconnect logic on another thread offered by knolleary. Essentially removing all blocking delay() s from the sketch. I added logic to try up to 15 times. So far (after two days) it has never gone above one attempt. Interesting that it when entering the function, it is almost always disconnected and tries one time . I am monitoring a moisture sensor for an auto watering solution so connection attempts are not often.

void reconnect() {
attempts = 0;
while (!client.connected() && attempts < 15) {
if (millis() - lastReconnectAttempt > 5000) {
lastReconnectAttempt = millis();
++attempts;
client.connect("GardenClient");
Serial.println(attempts);
if (client.connected()) {
// Once connected, publish an announcement...
client.publish("/test/","hello world garden here");
}
}
}
}

Update to the code in my post above. The MQTT reconnect issue is resolved. However, while looking over the serial output, I noticed that from time to time, I would get a WDT software reset. I added a yield() statement right after "while (!client.connected() && attempts < 15) {" and the watch dog timer is now happy. I'm also happy.

I'm also getting occasional WDT resets, could you please share your amended code (Inc 'yeild').
Thanks

Here it is Paul. Note: msg is a variable that contains the payload from my sketch. I have the subscribe commented out. This sketch does not subscribe only publishes.

void reconnect() {
attempts = 0;
while (!client.connected() && attempts < 15) {
yield();
if (millis() - lastReconnectAttempt > 5000) {
lastReconnectAttempt = millis();
++attempts;
client.connect("GardenClient");
Serial.println(attempts);
if (client.connected()) {
// Once connected, publish
client.publish("/test/Status/Drip",msg);
// ... and resubscribe
//client.subscribe("inTopic");

}

}
}

}

My ESP8266 is showing : Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
and the Mosca Server is printing this error :
{"pid":27492,"hostname":"JALLILU-PC","name":"IoTChain MQTT Server","level":30,"time":1529353170654,"msg":"authentication denied","client":"IoTChain MQTT Client","v":1}

The problem is the authentification !!! Please How to add user and password to the Mqtt connection !?

@abdoutech93 not sure your question is related to this issue... but as you ask, the docs show you there's a connect function that takes username and password as arguments - https://pubsubclient.knolleary.net/api.html#connect3

I had this issue too and it was driving me insane...

Thankfully I have just fixed it - basically, in your loop() one simple analogRead(A0) is enough to create the above issue.

I replaced:

dimv = analogRead(DIMMER1_PIN);

with:

if(now % 50 == 0)
{
dimv = analogRead(DIMMER1_PIN);
}

(now is millis() further up)

... and it works perfectly!

So if you are using anything ESP8266 related then be very careful with the analogRead stuff, it's expensive, only do it every X amount of loops.

[Note: I was only able to spot this as I had another sketch that used a button (digital read) rather than a potentiometer and it worked flawlessly].

still have the same problem....Attempting MQTT connection...failed, rc=-2 try again in 5 second.
i tried above all advices ...but no output

include

include

const char* ssid = "vivo V1";
const char* password = "qwer1234";
const char* mqtt_server = "192.168.137.72";

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.mode(WIFI_STA);
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()) {
   yield(); 
    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);
}

}

I have not got a definitive answer but I have managed to get my system up and running.

I am running an ESP01 and I had a working system. It worked for weeks. Then it just stopped. I have never found out why.

I then ran the PubSubClient example included in the Arduino IDE. Its pretty much basic. Just a connection via WiFi and then a connection to the MQTT server running on my Raspberry Pi

It failed with connection error everyone is mentioning above.

I tried everything above with no luck. I then installed Mosquito on my PC and tried the same example code against my PC and it worked perfectly.

I upgraded Mosquito on my Pi to version 1.5 and it still wouldn't work.....

At this point I am completely stumped.... I spent days trying every possible solution i could find on the internet.

I then removed the Wifi dongle from my Pi and connected it to my router directly with a cable and rebooted.

The ip address changed...

I changed the ip address in the example sketch, uploaded it, and it now works perfectly!!!

Gulp!

So, the only things that changed is changing from WiFi to a hard wired Ethernet connection and the change of ip address.

HTH

Try another broker like: HiveMQ
https://www.hivemq.com/try-out/

All who are trying to connect to the mosquitto broker on Pi...try removing the username & password from the broker and try this:
while (!client.connected()) {
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 3 seconds");
// Wait 3 seconds before retrying
delay(3000);
}

I'm having the same "Attempting MQTT connection...failed, rc=-2"
I'm using a docker version of eclipse-mosquitto for my broker its version 1.5.4. I my Docker runs on Centos7 on a Lenovo W510 and it uses a wired Ethernet connection to my home network. I had a TI 1294 with the PubSubClient working using a wired Ethernet connection. For a number of reasons I decide to switch to using an ESP8266WiFi device. I started by getting the RFID reader to read RFID tags and to output a JSON string, which worked, in fact the output looks like this:
{"epochTime":"1543034961","sensor":"rfidRdr01","rfid":"0000000735"}
In searching various web sites for assistance I came across quite a few, many suggesting network issues, but my epochTime comes from an NTP server I set up on a different Linux machine in my network, so I figure I'm ok on the network.
Here's my code (I've removed the RFID tag processing code to reduce the size, the code still runs)

define useID12LA_Reader

//#define use7491E_Reader

include

include

include

include

include

// Variables
WiFiClient rfidRdr01; // change name when multiple readers are in the network
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "192.168.0.7", 3600, 60000);
SoftwareSerial RFID(13, 15); // RX and TX
PubSubClient client(rfidRdr01);
const char* ssid = "xxxxxxxxxx"; // Credentials to connects to WiFi router
const char* password = "xxxxxxxxxx";
const char* mqtt_server = "192, 168, 0, 200"; // MQTT broker IP address
int mqttPort = 1883;
char mqttMsg[800]; //buffer used to publish messages via mqtt
unsigned long epochTime = 0;
char pubtopic[] = "sensors/rfid";
String clientId = "rfidRdr01";

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

// This function connects the ESP8266 to the LAN
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}

// This function reconnects the ESP8266 to the MQTT broker
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId.c_str())) {
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println();
// Wait 5 seconds before retrying
delay(5000);
}
}
}

ifdef useID12LA_Reader // This function reads the RFID ID-12LA transmission

String getTagId() {
return "0000000000";
}

endif

ifdef use7491E_Reader // these functions gets the RFID Tag froma 7491E

String getTagId() {
return "0000000000";
}

endif

// This function builds the Json message
String buildJson(String id, String sensor, String et) {
String mqttMsg = "{\"epochTime\":\"";
mqttMsg = mqttMsg + et;
mqttMsg = mqttMsg + "\",\"sensor\":\"";
mqttMsg = mqttMsg + sensor;
mqttMsg = mqttMsg + "\",\"rfid\":\"";
mqttMsg = mqttMsg + id;
mqttMsg = mqttMsg + "\"}";
return mqttMsg;
}

void setup() {
Serial.begin(115200);
RFID.begin(9600); // start serial to RFID reader
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
String rfTagId = getTagId();
timeClient.update();
epochTime = timeClient.getEpochTime();
String rfidJsonPayload = buildJson(rfTagId, "rfidRdr01", String(epochTime));
Serial.println(rfidJsonPayload );
char buf[67];
rfidJsonPayload.toCharArray(buf, 67);
// connect to mqtt broker
if (!client.connected()) {
reconnect();
}
if (client.connected()) {
client.publish(pubtopic, buf);
}
}

As you can see my code looks like most of the others here and the MQTT code was mimicked from the PubSubClient library provided by Arduino
Here's the end of the compile prior to move the code to the ESP8266:
Using library ESP8266WiFi at version 1.0 in folder: /home/dbristow/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi
Using library PubSubClient at version 2.7 in folder: /home/dbristow/Arduino/libraries/PubSubClient
Using library NTPClient-master at version 3.1.0 in folder: /home/dbristow/Arduino/libraries/NTPClient-master
Using library SoftwareSerial at version 1.0 in folder: /home/dbristow/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/SoftwareSerial

Going by my own experience I think your issue is this. In your loop() each time you are dealing with creating a json payload, printing it and publishing it. You seem to do this every time.

The issue is that the PubSubClient object needs to be running its update function repeatedly and without significant delays between multiple calls. By having a large chunk of other code that runs each time between the update function it messes with the ability for it to connect properly to the server.

Right now I can't actually see your update call, but I have a strong hunch that that is the issue. Look at my solution further up the thread, I had your issue and the solution fixed it.

Thanks for the suggestion, but I'm not using an analog read I'm using a SoftwareSerial connection to the RFID reader. Furthermore, each time a tag rolls over the reader I need to get its value and due to the speed at which the reader works I don't try to read a tag any faster than one per second. So I recall somewhere there was a warning about the SoftwareSerial code interfering with the TCP of the ESP WiFi code. So I ran the "getTagId" function with no SoftwareSerial use by simply waiting for 30 seconds an the return a constant of a known RFID tag ie "0000000735". But alas I still get the dreaded rc=-2 response.
To eliminate the possibility my MQTT broker is not working properly I have a Java application which simulates the RFID reader and creates an MQTT message in the same format as the sketch I shared earlier. I ran this application on the NTP server and another linux laptop and in both cases I can see the message gets processed by the Eclipse-Mosquito Docker container.

Well it certainly helps if you read what others have written! I feel a little foolish... the problem identified above by chenirl is what mine was. I ended up reviewing the source code to the PubSubClient and saw that the connect uses a couple of different set of parameters. Once I declared IPAddress mqtt_server(192, 168, 0, 200); instead of a char* my sketch worked. :)

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!

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!

Exactly what happened to me...

What does mean -1 in mqttClient.state?

I have problem with connection and state rc = - 1... What is this?

What does mean -1 in mqttClient.state?

I have problem with connection and state rc = - 1... What is this?

https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.h line 48.

Could you help me? I have problem with connect to my Losant device I have mqttClient.state -1 I don't know how can I repair it...

My issue:

https://github.com/esp8266/Arduino/issues/5508

But closed.. I would like to help with it. :(

I built a device based on homie on esp8266 which used to connect to mosquitto on raspberry 2 for months without any issues.
Now i upgraded to raspberry 3 and got the same issues as described above (Attempting to connect endlessly, mosquitto log showed "Socket error on client , disconnecting".
When changing the configuration to use raw IP adress instead of hostnames, the problem dissappeared.

After some investigation i found out that the rpi3 was connected both, wired and wireless, having two different IP adresses. A nslookup showed this (homer is the name of the rpi3):

C:\Users\foo>nslookup homer
Server:  fritz.box
Address:  192.168.1.250

Name:    homer
Addresses:  192.168.1.96    <- the Wifi adress
          192.168.1.97     <- the wired adress

After deactivating the Wifi and removing (force recreation) of all DNS entried in my router the problem disappeared. Even the device which was in the Attempt to connect - loop suddenly got a connection.
The nslookup command proved that the rpi3 now was available only by one IP adress:

C:\Users\foo>nslookup homer
Server:  fritz.box
Address:  192.168.1.250

Name:    homer
Address:  192.168.1.97

Just for completeness here my solution - my errorcode was rc=-1 (tried to connect via tasmota esp8226 firmware).

Reason: I used a too long username/password in my mosquitto server.
Solution: Reduced my username/password to 12 chars and it worked!

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

Thanks, This solution fixed my reboot issue. basically eliminating the PROGMEM.

Use:
IPAddress mqttServer(xxx.xxx.xxx.xxx);
Instead of:
const PROGMEM char* mqttServer = "xxx.xxx.xxx.xx";
For your setServer:
mqttClient.setServer(mqttServer, mqttPort);

i also tried all hack but now able to get communication with broker on cloud with above suggestion on this form. Thank you so much all.

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

This worked perfectly!

I had the same error. In my case the broker was rabbitmq and rabbitmq does not allow connection with guest user. You might wanna try providing user credentials.
client.connect(client_id.c_str(), mqtt_user.c_str(), mqtt_pass.c_str());
something like this.

The solution to this problem is to enable authentication on the mosquitto broker and use user name and password on the client connect call.

Just updated a device that's been running for years and ran into this same issue :( I'm running rabbitmq with authentication enabled and here's a snippet of the server-side output:

2020-05-31 17:08:19.168 [error] <0.5894.59> MQTT cannot parse frame for connection '10.42.2.0:29335 -> 10.42.1.175:1883', unparseable payload.......,[{file,"src/rabbit_mqtt_frame.erl"},{line,145}]},{rabbit_mqtt_frame,parse_frame,3,[{file,"src/rabbit_mqtt_frame.erl"},{line,59}]},{rabbit_mqtt_reader,parse,2,[{file,"src/rabbit_mqtt_reader.erl"},{line,311}]},{rabbit_mqtt_reader,process_received_bytes,2,[{file,"src/rabbit_mqtt_reader.erl"},{line,260}]},{gen_server2,handle_msg,2,[{file,"src/gen_server2.erl"},{line,1050}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]} 

I get similar message every time it attempts to reconnect.

What I found to be a problem is , if you leave the connection idle for more than a sec, it gets closed with socket errors, In the original example published for this library, if you remove the continuous message publish in the main loop, you can replicate the same error.
In my code I just kept this continuous ping every 2 secs , apart from my other message publish/subscribe needs. Havent faced this issue after that. The "AP mode" fix is not a solution.

I never get a connection. It fails to even make the connection successfully. All I did was update the board definitions in the IDE. Flashed and it failed so then I updated this lib..flashed again and failure. Failure all around now :)

Are you using any sort of MDNS discovery or similar before attempting the MQTT broker connection ?For me this was also an issue, ESP8266 MDNS library seems to do something to the Wifi stack after running a mdns query. It would actually not even appear on the router's device list although connection status on wifi library would still return 3. The solution for me was to save the IP and port after discovery to eeprom and then do a restart and attempt connection with mqtt broker.
To verify this, check the device list on your router. I am sure your board wont be in the connected device list, thats the reason its failing with rc - 2

I don't think that's the case or a I wouldn't be seeing the attempts on the rabbitmq server to authenticate. I have an IP etc and it is attempting to connect..

Seems to be a new issue , are you using authentication? I was using
Mosquitto broker on the raspberry pi. May be whatever I faced is typical to
Mosquitto.

On Mon, Jun 1, 2020 at 12:11 PM Travis Glenn Hansen <
[email protected]> wrote:

I don't think that's the case or a I wouldn't be seeing the attempts on
the rabbitmq server to authenticate. I have an IP etc and it is attempting
to connect..

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/knolleary/pubsubclient/issues/203#issuecomment-636643217,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ACL7KNJXVC5AA6ZSU5W4RS3RUNERZANCNFSM4CQNJPTQ
.

I’ve been using authentication with rabbitmq on the device for years.

Hi everyone. I'm using a Raspberry Pi running Mosquitto over websockets on port 9001 with username and password. The username and password are less than 10 characters I don't know why I'm getting error -1 in the client state. However, I can connect to the server with a JavaScript client with the same data. This is my code:

include

include

const char* ssid = "my_ssid";
const char* password = "my_network_password";
const char* mqtt_server = "192.168.1.36";
const int mqtt_port = 9001;
const char* mqtt_username = "user";
const char* mqtt_password = "password";

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

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}

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();
// Rest of code
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
Serial.println("connected");
// Rest of code
} else {
Serial.print("failed, rc=");
Serial.print(client.state()); // I'm getting -1
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Rest of code
}

The output is: Attempting MQTT connection...failed, rc=-1 try again in 5 seconds.
I will appreciate your help, thanks.

I don't see any websocket implementation in your sketch. And AFAIK this is not supported out of the box by Pubsubclient. Try the regular MQTT connection (1883) if your broker supports this.

This issue is 4 years old and too generic to be worth keeping open. Lots of people have issues connecting and every single one is a different underlying reason.

Was this page helpful?
0 / 5 - 0 ratings