cyijun / ESP32MQTTClient

A thread-safe MQTT client for Arduino ESP32xx, based on ESP-IDF MQTT component. | Need help for adapting the latest mqtt component.
MIT License
15 stars 2 forks source link

isConnected not working #1

Closed strid3r21 closed 4 months ago

strid3r21 commented 1 year ago

hi,

i've been messing around with this library and its pretty great for what i need it for, however i cant seem to get any of the isConnected(), isWifiConnected(),isMqttConnected() options to work at all.

they just sit there and never connect. if i remove those options and just let it try and connect without those checks then it connects just fine. but i would like to do different things if the wifi or mqtt connections fail or disconnect.

here is a basic example of how I've tried to get it working.

void loop () {
  bool USB = bdl.getVbusPresent();
  while(USB == true){
    if(client.isConnected()){
     Serial.println("MQTT Connected");
      if (lostPower == 1){
        lostPowerCounter = lostPowerCounter+1;
        delay(2000);
        readFile(SD, "/backup.txt");
        deleteFile(SD,"/backup.txt");
        Serial.println("Backup Dumped to MQTT");
    }

      lostPower = 0;
      sendMQTT();
      delay(1000);
    }
    else{
       Serial.print("Connecting");
      for(int i = 0; i < 50; i++){
      delay(500);  // Wait for half a second
      Serial.print(".");
      }
      Serial.println("");
      }
    }    
}

if tried it with !isConnected() for false detection, ive tried isConnected() == false; and vise versa for connected. is there something im doing wrong here?

thanks!

cyijun commented 1 year ago

hi, glad to know my work is helpful.

The isConnected() returns the MQTT connection state, so it equals to isMqttConnected(). And it's most likely to work fine, becase the client won't publish anything if it always returns false. Would you please to do more tests on this function for me? I'm busy at work these days.

You can check the WiFi state by using the ESP32 arduino functions. As you can see, there is no "wifi" codes in the source of this library, I want to keep this library decoupled.

By the way, you may decrease the waiting time for checking connection or use exponential backoff.