Set a maximum number of connection retries

This commit is contained in:
coolneng 2023-03-30 02:10:49 +02:00
parent 8658148646
commit f626085e40
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
3 changed files with 22 additions and 19 deletions

View File

@ -4,20 +4,18 @@
#define DHTTYPE DHT11 #define DHTTYPE DHT11
#define DHTPIN 4 #define DHTPIN 4
DHT dht(DHTPIN, DHTTYPE); DHT dht(DHTPIN, DHTTYPE);
int fc28_pin = A0; const int fc28_pin = A0;
int soil_threshold = 40; const int soil_threshold = 40;
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
dht.begin(); dht.begin();
wlan_connection(); wlan_connection(60);
} }
void loop() { void loop() {
unsigned long start_time = millis();
int analog_val = analogRead(fc28_pin); int analog_val = analogRead(fc28_pin);
int soil_percentage = map(analog_val, 0, 1023, 0, 100); int soil_percentage = map(analog_val, 0, 1023, 0, 100);
char buffer[200]; char buffer[200];
@ -25,5 +23,5 @@ void loop() {
dht.readTemperature(), dht.readHumidity(), soil_percentage); dht.readTemperature(), dht.readHumidity(), soil_percentage);
Serial.println(buffer); Serial.println(buffer);
delay(30000); delay(30000);
enter_deep_sleep(start_time); enter_deep_sleep(false);
} }

View File

@ -2,14 +2,21 @@
#include "credentials.h" #include "credentials.h"
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
void wlan_connection() { void initial_connection() {
if (WiFi.SSID() != SSID) {
WiFi.begin(SSID, PSK); WiFi.begin(SSID, PSK);
WiFi.persistent(true); WiFi.persistent(true);
WiFi.setAutoConnect(true); WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true); WiFi.setAutoReconnect(true);
} }
void wlan_connection(int max_retries) {
if (WiFi.SSID() != SSID)
initial_connection();
int retries = 0;
while (WiFi.status() != WL_CONNECTED) { while (WiFi.status() != WL_CONNECTED) {
retries++;
if (retries == max_retries)
enter_deep_sleep(true);
delay(1000); delay(1000);
Serial.print("."); Serial.print(".");
} }
@ -22,10 +29,8 @@ void mqtt_connection(char *server, int port, char *fingerprint) {
client.connect(server, port); client.connect(server, port);
} }
void enter_deep_sleep(const int start_time) { void enter_deep_sleep(bool wifi_timeout) {
int elapsed = millis() - start_time; if (wifi_timeout)
if (elapsed >= WIFI_TIMEOUT) {
WiFi.disconnect(); WiFi.disconnect();
}
ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT); ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
} }

View File

@ -4,8 +4,8 @@
const int SLEEP_TIME = 480000000; const int SLEEP_TIME = 480000000;
const int WIFI_TIMEOUT = 10000; const int WIFI_TIMEOUT = 10000;
void wlan_connection(); void wlan_connection(int max_retries);
void prometheus_connection(char *server, int port, char *fingerprint); 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 */ #endif /* WLAN_H */