WiFiManager icon indicating copy to clipboard operation
WiFiManager copied to clipboard

Example for making (re-)connecting to WLAN robust

Open probonopd opened this issue 2 years ago • 1 comments

Often one finds this

#include <WiFiManager.h>

void setup() {
  WiFiManager wifiManager;
  wifiManager.autoConnect();
}

void loop() {
  // main program logic here
}

This has two downsides:

  • If the WLAN connection drops while the device is connected, it never re-connects when the WLAN re-appears
  • If the WLAN is not in range while the device is powered on, then the device will hang on the configuration portal forever

To make it more robust, I would suggest an approach that:

  • If the WLAN is not in range or is not configured, opens the configuration portal only for 180 seconds
  • After the timeout, continously tries to reconnect to the WLAN
  • If the WLAN is in range when the device is powered on but goes out of range thereafter, then the device should not open the configuration portal forever but should periodically try to join the network again

Is the following code suitable to do that?

#include <WiFiManager.h> 

WiFiManager wifiManager;

void setup() {
  wifiManager.setConnectTimeout(60); // Set the connection timeout to 60 seconds
  wifiManager.setConfigPortalTimeout(180); // Set the configuration portal timeout to 180 seconds
  wifiManager.autoConnect(); // Try to connect to the WLAN with saved credentials, or create an AP with a default name if not successful for 180 seconds
}

void loop() {
  if (WiFi.status() !=
      WL_CONNECTED) { // Check if the device is not connected to the WLAN
    wifiManager.setConfigPortalTimeout(0); // Disable the configuration portal
    while (WiFi.status() !=
           WL_CONNECTED) { // Continue attempting to connect until a successful
                           // connection is made
      delay(5000);
      WiFi.begin(); // Try to connect to the WLAN again
    }
  }
  
   // main program logic here
}

Do you think the logic could be further improved?

I suggest to add such an example to the documentation.

probonopd avatar Apr 16 '23 18:04 probonopd

I also see this problem

Laxilef avatar Sep 15 '23 11:09 Laxilef