From c9cacc540f6f9a650f1d37164fee962b46958029 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Mon, 16 May 2022 21:05:07 -0500 Subject: [PATCH] main: Deep sleep after network failures Instead of entering a "hot" reboot loop when there is a problem connecting to WiFi or the MQTT broker, the chip will now go into deep sleep for a minute before trying again. This should conserve battery in situations where simply trying again right away won't fix the problem (e.g. WiFi is actually down, or the band conditions are just really bad for now). --- gardensensor.ino | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/gardensensor.ino b/gardensensor.ino index 333d398..49e852a 100644 --- a/gardensensor.ino +++ b/gardensensor.ino @@ -33,11 +33,11 @@ void setup() { if (!wifi_connect()) { Serial.printf("Failed to connect to WiFi, status %s\n", WiFi.status()); - reboot(); + retry_after_minutes(1); } if (!mqtt_connect()) { Serial.println("Could not connect to MQTT"); - reboot(); + retry_after_minutes(1); } if (!publish_all_config(&mqtt, WiFi.macAddress().c_str())) { @@ -49,7 +49,7 @@ void setup() { auto msg = "Seesaw not found"; Serial.println(msg); mqtt_send_error(msg); - reboot(); + retry_after_minutes(1); } values.boot_count = boot_count; @@ -57,7 +57,7 @@ void setup() { auto msg = "Failed to get sensor values"; Serial.println(msg); mqtt_send_error(msg); - reboot(); + retry_after_minutes(1); } else { Serial.println("Got Values:"); Serial.printf(" Moisture: %d\n", values.moisture); @@ -87,15 +87,6 @@ void loop() { while (1) delay(1471228928); } -void error_led_blink() { - while (1) { - digitalWrite(13, 1); - delay(500); - digitalWrite(13, 0); - delay(500); - } -} - boolean wifi_connect() { Serial.printf("Connecting to WiFi (%s) ", CFG_WIFI_SSID); WiFi.begin(CFG_WIFI_SSID, CFG_WIFI_PSK); @@ -148,10 +139,6 @@ boolean mqtt_connect() { return true; } -void mqtt_send_error(const __FlashStringHelper* msg) { - mqtt_send_error((const char*)msg); -} - void mqtt_send_error(const char* msg) { if (!mqtt.connected()) { Serial.println("MQTT client not connected, cannot send error message"); @@ -160,11 +147,10 @@ void mqtt_send_error(const char* msg) { mqtt.publish(TOPIC_ERRORS, msg); } -void reboot() { +void retry_after_minutes(int minutes) { if (mqtt.connected()) { mqtt.disconnect(); } - Serial.println("Rebooting in 2 seconds"); - delay(2000); - ESP.restart(); + esp_sleep_enable_timer_wakeup(minutes * 60 * 1000 * 1000); + esp_deep_sleep_start(); }