From 160cbc5ea96d137badbee7c195bb2fcb415588e6 Mon Sep 17 00:00:00 2001 From: Torrie Fischer Date: Sun, 19 Feb 2023 18:40:16 +0100 Subject: [PATCH] bootoptions: use NVRAM instead of wearing out flash for crash detection in esp32 --- src/BootOptions.cpp | 27 ++++++++++++++++++++++++--- src/BootOptions.h | 3 +++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/BootOptions.cpp b/src/BootOptions.cpp index 70f11ba..b469c67 100644 --- a/src/BootOptions.cpp +++ b/src/BootOptions.cpp @@ -1,9 +1,11 @@ #include "BootOptions.h" +#include "Config.h" + +#include + #ifdef BOARD_ESP8266 #include #endif -#include -#include "Config.h" #ifdef PLATFORM_PHOTON LEDStatus serialStatus = LEDStatus(RGB_COLOR_ORANGE, LED_PATTERN_FADE, LED_SPEED_FAST, LED_PRIORITY_BACKGROUND); @@ -12,6 +14,10 @@ retained bool LAST_BOOT_WAS_FLASH; retained bool LAST_BOOT_WAS_SERIAL; #endif +#ifdef BOARD_ESP32 +__NOINIT_ATTR uint8_t s_rebootCount = 0; +#endif + void BootOptions::initPins() { @@ -36,9 +42,24 @@ BootOptions::BootOptions() configStatus.setActive(isSetup); serialStatus.setActive(isSerial); #endif +#ifdef BOARD_ESP32 + resetReason = esp_reset_reason(); + crashCount = s_rebootCount; + if (resetReason >= 4) { // TODO: These values are defined in + // esp32/rom/rtc.h, but not sure if that's included + // on platformio builds + if (crashCount++ >= 3) { + // Boot into safe mode if the watchdog reset us three times in a row. + isSafeMode = true; + } + } else { + crashCount = 0; + } + s_rebootCount = crashCount; +#endif #ifdef BOARD_ESP8266 struct rst_info resetInfo = *ESP.getResetInfoPtr(); - uint8_t crashCount; + resetReason = resetInfo.reason; EEPROM.begin(sizeof(crashCount)); EEPROM.get(sizeof(HardwareConfig) + 32, crashCount); EEPROM.end(); diff --git a/src/BootOptions.h b/src/BootOptions.h index 26acb5e..9340c93 100644 --- a/src/BootOptions.h +++ b/src/BootOptions.h @@ -1,4 +1,5 @@ #pragma once +#include struct BootOptions { static void initPins(); @@ -12,4 +13,6 @@ struct BootOptions { bool isFlash = false; bool lastBootWasFlash = false; bool isSafeMode = false; + uint8_t crashCount = 0; + uint8_t resetReason = 0; };