From 5a2c6de2f8ed59305ed2f22cc839aa42d7e8b957 Mon Sep 17 00:00:00 2001 From: Joe Tretter Date: Sat, 9 Sep 2023 14:27:58 -0500 Subject: [PATCH] Reconnect to wifi if connection lost... --- src/main.cpp | 47 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index d5d6fa4..19d7c5a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -16,6 +16,7 @@ const char* mqtt_server = "mqtt.ddns.kawomi.com"; const int buttonPin = 4; // Reed switch - don't forget the pull down resistor. const int ledPin = 2; // Internal LED +int wifiState = WL_DISCONNECTED; // Wifi-Connection Status boolean bForceResend = true; // send initial state to mqtt on startup. int previousState; @@ -174,21 +175,9 @@ void reconnect() { /* * setup function */ -void setup(void) { - Serial.begin(9600); - delay(500); - Serial.println(">>>>>>>>>> Garage Door Monitor <<<<<<<<<<<<<<"); - pinMode(buttonPin, INPUT); - pinMode(ledPin, OUTPUT); - - // if we stat up we need to see what the status is... - digitalWrite(ledPin, previousState = digitalRead(buttonPin)); - Serial.printf("Initial State: %d", previousState); - - randomSeed(micros()); - - // Connect to WiFi network +void wifiSetup(void){ +// Connect to WiFi network WiFi.begin(ssid, password); Serial.println(""); @@ -218,7 +207,24 @@ void setup(void) { } } Serial.println("mDNS responder started"); +} +void setup(void) { + Serial.begin(9600); + delay(500); + + Serial.println(">>>>>>>>>> Garage Door Monitor <<<<<<<<<<<<<<"); + pinMode(buttonPin, INPUT); + pinMode(ledPin, OUTPUT); + + // if we stat up we need to see what the status is... + digitalWrite(ledPin, previousState = digitalRead(buttonPin)); + Serial.printf("Initial State: %d", previousState); + + randomSeed(micros()); + + wifiSetup(); + mqttClient.setServer(mqtt_server, 1883); Serial.println("mqtt server set."); @@ -302,6 +308,19 @@ 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(1000);