From f626085e40253619eb7b60ce0472f1707638f046 Mon Sep 17 00:00:00 2001
From: coolneng <akasroua@gmail.com>
Date: Thu, 30 Mar 2023 02:10:49 +0200
Subject: [PATCH] Set a maximum number of connection retries

---
 src/main.cpp | 10 ++++------
 src/wlan.cpp | 27 ++++++++++++++++-----------
 src/wlan.h   |  4 ++--
 3 files changed, 22 insertions(+), 19 deletions(-)

diff --git a/src/main.cpp b/src/main.cpp
index f960cab..d200f45 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -4,20 +4,18 @@
 
 #define DHTTYPE DHT11
 #define DHTPIN 4
-
 DHT dht(DHTPIN, DHTTYPE);
 
-int fc28_pin = A0;
-int soil_threshold = 40;
+const int fc28_pin = A0;
+const int soil_threshold = 40;
 
 void setup() {
   Serial.begin(9600);
   dht.begin();
-  wlan_connection();
+  wlan_connection(60);
 }
 
 void loop() {
-  unsigned long start_time = millis();
   int analog_val = analogRead(fc28_pin);
   int soil_percentage = map(analog_val, 0, 1023, 0, 100);
   char buffer[200];
@@ -25,5 +23,5 @@ void loop() {
           dht.readTemperature(), dht.readHumidity(), soil_percentage);
   Serial.println(buffer);
   delay(30000);
-  enter_deep_sleep(start_time);
+  enter_deep_sleep(false);
 }
diff --git a/src/wlan.cpp b/src/wlan.cpp
index ed9572b..e218be3 100644
--- a/src/wlan.cpp
+++ b/src/wlan.cpp
@@ -2,14 +2,21 @@
 #include "credentials.h"
 #include <ESP8266WiFi.h>
 
-void wlan_connection() {
-  if (WiFi.SSID() != SSID) {
-    WiFi.begin(SSID, PSK);
-    WiFi.persistent(true);
-    WiFi.setAutoConnect(true);
-    WiFi.setAutoReconnect(true);
-  }
+void initial_connection() {
+  WiFi.begin(SSID, PSK);
+  WiFi.persistent(true);
+  WiFi.setAutoConnect(true);
+  WiFi.setAutoReconnect(true);
+}
+
+void wlan_connection(int max_retries) {
+  if (WiFi.SSID() != SSID)
+    initial_connection();
+  int retries = 0;
   while (WiFi.status() != WL_CONNECTED) {
+    retries++;
+    if (retries == max_retries)
+      enter_deep_sleep(true);
     delay(1000);
     Serial.print(".");
   }
@@ -22,10 +29,8 @@ void mqtt_connection(char *server, int port, char *fingerprint) {
   client.connect(server, port);
 }
 
-void enter_deep_sleep(const int start_time) {
-  int elapsed = millis() - start_time;
-  if (elapsed >= WIFI_TIMEOUT) {
+void enter_deep_sleep(bool wifi_timeout) {
+  if (wifi_timeout)
     WiFi.disconnect();
-  }
   ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
 }
diff --git a/src/wlan.h b/src/wlan.h
index 05e2c8f..7014394 100644
--- a/src/wlan.h
+++ b/src/wlan.h
@@ -4,8 +4,8 @@
 const int SLEEP_TIME = 480000000;
 const int WIFI_TIMEOUT = 10000;
 
-void wlan_connection();
+void wlan_connection(int max_retries);
 void prometheus_connection(char *server, int port, char *fingerprint);
-void enter_deep_sleep(const int start_time);
+void enter_deep_sleep(bool wifi_timeout);
 
 #endif /* WLAN_H */