From f330bfdb9e495c8ae828192551c8de59a165eac1 Mon Sep 17 00:00:00 2001 From: Joe Tretter Date: Sat, 9 Sep 2023 14:11:00 -0500 Subject: [PATCH] reconnect wifi when connection is lost --- src/main.cpp | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 13bad7a..605a0d1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -22,12 +22,16 @@ interface the file .pio/build/esp32doit-devkit-v1/firmware.bin const char* host = "esp32ota"; const char* ssid = "JoNelsDarlings"; const char* password = "Paris2016"; +/*const char* ssid = "Rucksack"; +const char* password = "Muratina";*/ + // variabls to blink without delay: const int led = 2; unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 1000; // interval at which to blink (milliseconds) int ledState = LOW; // ledState used to set the LED +int wifiState = WL_DISCONNECTED; // Wifi-Connection Status WebServer server(80); @@ -123,11 +127,8 @@ const char* serverIndex = /* * setup function */ -void setup(void) { - pinMode(led, OUTPUT); - - Serial.begin(9600); +void wifiSetup(void){ // Connect to WiFi network WiFi.begin(ssid, password); Serial.println(""); @@ -158,6 +159,13 @@ void setup(void) { } } Serial.println("mDNS responder started"); +} + +void setup(void) { + pinMode(led, OUTPUT); + Serial.begin(9600); + wifiSetup(); + /*return index page which is stored in serverIndex */ server.on("/", HTTP_GET, []() { server.sendHeader("Connection", "close"); @@ -203,6 +211,18 @@ void setup(void) { } void loop(void) { + if (wifiState!=WiFi.status()) { + Serial.print("Wifi Status Change: "); + Serial.println(WiFi.status()); + wifiState=WiFi.status(); + } + + // if we lost connection reconnect... + if (WL_CONNECTED != WiFi.status()){ + WiFi.disconnect(); + delay(1000); + wifiSetup(); + } server.handleClient(); delay(1);