Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jindrichsirucek/26ca5ca52a2a5bdf8366e11646585b3c to your computer and use it in GitHub Desktop.
Save jindrichsirucek/26ca5ca52a2a5bdf8366e11646585b3c to your computer and use it in GitHub Desktop.
ESP8266 - There is list of saved wifi credentials, it tries to connect one by one to them until success - on next boot it remembers last network and try to connect first to it.. if unsucsefull look throw all list of saved networks
struct WiFiCredential{
const char *ssid;
const char *pass;
};
bool wifiConnect()
{
if(isWifiConnected())
return true;
WiFi.mode(WIFI_STA);
if(wifiConnectToLastNetwork())
return true;
WiFiCredential savedWifiCredentials[] = {
{"D","dan"},
{"Kfer_net_7","lya456"},
{"U326803","PDFG"},
{"Ainra","cargoo"},
{"Sucovi","eAAADD64fe"},
{"U309010","RXYD"},
};//The most prefereable at the end!
Serial.print(E("Scanning available WiFinetworks.. Found: "));
yield();
uint8_t n = WiFi.scanNetworks();
yield_debug();
Serial.println(n);
uint8_t c = SIZE_OF_LOACAL_ARRAY(savedWifiCredentials);
while(--c)
{
if(WIFI_DEBUG) DEBUG_OUTPUT.print(sE("Searching for: ") + savedWifiCredentials[c].ssid);
for (int i = 0; i < n; ++i)
{
if(WiFi.SSID(i) == savedWifiCredentials[c].ssid)
{
Serial.println(sE(" - Found!"));
if(wifiConnectTo(savedWifiCredentials[c].ssid, savedWifiCredentials[c].pass))
return true;
else
break;//for lopp
}
yield_debug();
}
Serial.println();
}
return false;
}
bool wifiConnectTo(char const* ssid, char const* pass)
{
Serial.printf(cE("Wifi connecting to: %s..\n"), ssid);
WiFi.begin(ssid, pass);
uint8_t attempt = 200;
while (--attempt)
{
delay(100);
Serial.print(E("."));
if(WiFi.status() == WL_CONNECTED)
break; //Succesfully connected
if(WiFi.status() == WL_CONNECT_FAILED)
attempt = 1; //Falied to connect, attempt = 1 ends loop imediately
}
if(attempt)
return true;
Serial.println(sE("\n!!Warning: WIFi NOT connected to: ") + ssid + E(" because: ") + WiFi.status());
return false;
}
bool isWifiConnected()
{
yield_debug();
if(WIFI_DEBUG) DEBUG_OUTPUT.printf(cE("Wifi status: (%d)"), WiFi.status());
return (WiFi.status() == WL_CONNECTED);
}
bool wifiConnectToLastNetwork()
{
Serial.print(sE("WiFi: trying to connect to last network: ") + WiFi.SSID());
wifi_station_set_auto_connect(true);
wifi_station_connect();
WiFi.waitForConnectResult();
if(isWifiConnected())
return onWiFiSuccesfullyConnected();
else
Serial.println(E(" - Unsuccesfull!"));
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment