Imroy / pubsubclient

A client library for the ESP8266 that provides support for MQTT
MIT License
434 stars 115 forks source link

client not detecting drop of broker connection sometimes. #33

Open matbor opened 8 years ago

matbor commented 8 years ago

I am running my esp8266 on a mobile 3g wifi hotspot (so sometimes it has latency/dropout issues as it is always moving) but have been finding that it doesn't always detect that the mqtt broker connection has dropped.

from basic example;

if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
      if (client.connect("arduinoClient")) {
    client.publish("outTopic","hello world");
    client.subscribe("inTopic");
      }
    }

    if (client.connected())
      client.loop();
  }

in the process of researching this problem I found this handy hint here; https://github.com/knolleary/pubsubclient/issues/41

And based my code client.loop(); code off it and it seems to of fixed my problem;

if (!client.loop()) {
    Serial.println("### Client has disconnected...");

    // add you code to reconnect here.
    if (client.connect("arduinoClient")) {
    client.publish("outTopic","hello world");
    client.subscribe("inTopic");
      }
  }

One more thing, I have also found that sometimes just doing this doesn't work, I find I need to force the disconnect. ie, using client.disconnect(); before calling connect again.

if (!client.loop()) {
    Serial.println("### Client has disconnected...");
    client.disconnect();

    // add you code to reconnect here.
    if (client.connect("arduinoClient")) {
    client.publish("outTopic","hello world");
    client.subscribe("inTopic");
      }
  }

As mention on the other issue on knolleary github this probably isn't a issue, just pointing it out for other people if they have similar issues.

Matt.