Recommend MQTT Library with ESP8266

Hi, guys
I am starting simple project using ESP8266 that connected to MQTT Broker but the thing is very important to do is detecting that connected to Broker because sometimes the global internet is cut so how to check if still connected to MQTT broker?

Take a look at the PubSubClient library

tested but if global internet cut, ESP8266 detected after 30 seconds that not connected to MQTT Broker
So, how to let ESP8266 detect immediately?

You never specified how quickly the disconnection should become known.

How did you do the check and how often did you do it ?

to implement global internet cut do the followings :

  • router connected to wifi access point
  • ESP8266 connected to wif access point
  • then to cut global internet remove RJ45 between Router & access point

What I meant was, how did the sketch check for an interruption of the Internet or MQTT connection ?

What do you want to happen if such a disconnection occurs ?

void loop() {

  if (!client.connected()) {
 Serial.println("Disconnected");
reconnect();
  }
  client.loop();
  if (client.connected()) {
 Serial.println("Connected");
  }
 unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}
    if (client.connected())
    {
        Serial.println("Connected");
        reconnect();
    }

Why the continual reconnection when already connected ?

it is mistake by copy the code please check again

You have already changed the code 3 times after posting it. Is this the version that took 30 seconds to notice the disconnection ?

Printing a message when the disconnection happens is all very well but what do you really want to do and how quickly must it happen and why ?

yes, it is
when I remove RJ45 cable from router for 1 minute then it takes each 30 seconds to check that disconnected then try to reconnect again

If the sketch responded within say 1 second when disconnected what difference would it make ?

to turn led on if connected and turn it off if disconnected then send request to some API request if internet available

is there any modification can do to code to let detect cut internet immediately?

Why the need to detect the Internet disconnection immediately ?

What will be the consequences of a delay in doing so ?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.