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

Can't connect to Broker #203

Closed
wiktor-grochal opened this issue Sep 21, 2016 · 91 comments
Closed

Can't connect to Broker #203

wiktor-grochal opened this issue Sep 21, 2016 · 91 comments

Comments

@wiktor-grochal
Copy link

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
Copy link
Owner

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

@averri
Copy link

averri commented Nov 20, 2016

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
Copy link
Owner

@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
Copy link
Owner

Sorry, see that you did...

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

@averri
Copy link

averri commented Nov 20, 2016

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

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

@knolleary
Copy link
Owner

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
Copy link

averri commented Nov 20, 2016

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
Copy link
Owner

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
Copy link

averri commented Nov 20, 2016

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
Copy link
Owner

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
Copy link

gilmntg commented Nov 21, 2016

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
Copy link

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

@acestu
Copy link

acestu commented Feb 10, 2017

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
Copy link

acestu commented Feb 10, 2017

Hi,

Just tried the above fix but still get:

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

Thanks
Stuart

@amineBenguesmia
Copy link

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

any solution plz

@chenirl
Copy link

chenirl commented Mar 18, 2017

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
Copy link

ANierbeck commented Mar 19, 2017

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
Copy link

chenirl commented Mar 19, 2017

What versions of:
Arduino IDE, PubSubClient

I use the latest IDE.
PubSubClient 2.6.0

@ANierbeck
Copy link

Same here, latest in Arduino IDE / Sloeber
PubSubClient 2.6.0

@chenirl
Copy link

chenirl commented Mar 19, 2017

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
Copy link

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
Copy link
Owner

@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
Copy link

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

@ANierbeck
Copy link

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

@Midgie75
Copy link

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

@roboticboyer
Copy link

For ESP8266 the solution of the issue is;
Add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password);
#203 (comment) such as suggested by @rannanda

See #martin-ger/esp_wifi_repeater#44 (comment)

@mrohner
Copy link

mrohner commented Jul 11, 2017

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
Copy link

chenirl commented Jul 11, 2017

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.

@djbristow
Copy link

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.

@djbristow
Copy link

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

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

@trevorjdaniel
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!

Exactly what happened to me...

@mslawo95
Copy link

What does mean -1 in mqttClient.state?

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

@Ajtimstoj
Copy link

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.

@mslawo95
Copy link

mslawo95 commented Dec 17, 2018

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:

esp8266/Arduino#5508

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

@msbannert
Copy link

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

@h0jeZvgoxFepBQ2C
Copy link

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!

@frankygoop
Copy link

frankygoop commented May 13, 2019

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.

@vikash121
Copy link

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.

@skittleson
Copy link

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

This worked perfectly!

@RshmanGit
Copy link

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.

@sasmit-hota
Copy link

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

@travisghansen
Copy link

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.

@sasmit-hota
Copy link

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.

@travisghansen
Copy link

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

@sasmit-hota
Copy link

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

@travisghansen
Copy link

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

@sasmit-hota
Copy link

sasmit-hota commented Jun 1, 2020 via email

@travisghansen
Copy link

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

@pierotoscano1496
Copy link

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 <WiFi.h>
#include <PubSubClient.h>

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.

@thijsdebont
Copy link

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.

@knolleary
Copy link
Owner

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.

@ajinkya-open
Copy link

[ tested and workinf for my case ] check if your case it help
i made a routing in code like below
im not testin gmqttclient connection, but the underlying espclient i checking with connection with 80 port, i hosted a apache just for pining purpose nothing elsem , in main loop i check it for connection purpose and in global variable i setting the indication of internet avalabel if ping is success as belo, and in connect loop of mq tt i check if internet is availeble then only i reconect to it, elese i dont, and one more obseration , using IP it workes satisfacotry but if i use domain instead of ip , it wont work as intended, Im stuck to manage broker ip , because shoing ip directoly is not a good solution

ping function

boolean pingServer()
{
  // if (pinger.connect("broker.pongohome.in", 80))
  if (pinger.connect(brokerIP, 80))
  {
    // Serial.println("ping : true");
    internetAvailable = true;
    // Make a HTTP request:
  }
  else
  {
    // Serial.println("ping : false");
    internetAvailable = false;
  }
  return internetAvailable;
}

in reconnec logic of mqtt do this

void reconnect()
{
  // Loop until we're reconnected
  if (internetAvailable)
  {
    while (!client.connected())
    {
      // Serial.print("Attempting MQTT connection...");
      // Create a random client ID
      String clientId = "XXXXX-";
      clientId += String(random(0xffff), HEX);
      // Attempt to connect
      if (client.connect(clientId.c_str()))
      {
        // Serial.println("connectedMQTT");
        client.subscribe(topicX.c_str());
//publish to some topi to know status of connectivity
      }
      else
      {
        // Serial.print("failed, rc=");
        // Serial.print(client.state());
        // Wait 5 seconds before retrying
      }
     
    }
  }
  else
  {
    // Serial.println("Internet not present so not pinging 1883"); // it continuesly print it, better keep commended this line
  }
}

let know if it work in your case also, pub sub lib, generic async mqtt lib has same underlying issue , that breakage of internet from ISP causes continuous disconnection status, keep ing pending reconnect state, but in this patch try if working in your case

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