tzapu / WiFiManager

ESP8266 WiFi Connection manager with web captive portal
http://tzapu.com/esp8266-wifi-connection-manager-library-arduino-ide/
MIT License
6.6k stars 1.97k forks source link

How to use WiFiManager only as a fallback if a certain network is not there? #497

Closed probonopd closed 6 years ago

probonopd commented 6 years ago

I need to use WiFiManager only as a fallback if a certain network (homeNetwork) is not there.

However, if I do the following then apparently the credentials do not get saved and loaded correctly - after a reboot, AutoConnectAP is always spawned.

How to fix this?

#if defined(ESP8266)
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#else
#include <WiFi.h>
#endif

#include <DNSServer.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>

AsyncWebServer server(80);
DNSServer dns;

void setup() {
  Serial.begin(115200);

  bool homeNetworkAvailable = false;

  // Check if the home network is available
  // it needs some special authentication mechanism through a captive portal
  // (not shown in this example)

  int n = WiFi.scanNetworks();
  randomSeed(ESP.getCycleCount());
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.println(WiFi.SSID(i));
      if (WiFi.SSID(i) == "homeNetwork") { // enter the ssid which you want to search
        Serial.println("The homeNetwork network is available, trying to log in");
        homeNetworkAvailable = true;

      }
    }
  }

  // ONLY if the home network is NOT available use AsyncWiFiManager
  // This works only ONCE, after a reboot I get "*WM: No saved credentials
  // FIXME

  if (homeNetworkAvailable == false) {
    AsyncWiFiManager wifiManager(&server, &dns);
    //wifiManager.resetSettings(); // reset settings - for testing
    wifiManager.setTimeout(180);

    if (!wifiManager.autoConnect("AutoConnectAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      ESP.reset();
      delay(5000);
    }
  }

  Serial.println("connected...yeey :)");

}

void loop() {
  // put your main code here, to run repeatedly:

}
tablatronix commented 6 years ago

Whats AsyncWiFiManager ?

probonopd commented 6 years ago

Err, good point @tablatronix - sorry I have mixed up the projects. https://github.com/alanswx/ESPAsyncWiFiManager is a fork of https://github.com/tzapu/WiFiManager/ but async. Closing here and asking there.

I suspect it has something to do with "Using last saved values, should be faster" - apparently doing a network scan confuses this. Is this supposed to work with https://github.com/tzapu/WiFiManager/?