diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 767bd8f29b..90470d2caf 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -636,9 +636,32 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { return (doc["sv"] | true); } - static const char s_cfg_json[] PROGMEM = "/cfg.json"; +bool backupConfig() { + return backupFile(s_cfg_json); +} + +bool restoreConfig() { + return restoreFile(s_cfg_json); +} + +bool verifyConfig() { + return validateJsonFile(s_cfg_json); +} + +// rename config file and reboot +// if the cfg file doesn't exist, such as after a reset, do nothing +void resetConfig() { + if (WLED_FS.exists(s_cfg_json)) { + DEBUG_PRINTLN(F("Reset config")); + char backupname[32]; + snprintf_P(backupname, sizeof(backupname), PSTR("/rst.%s"), &s_cfg_json[1]); + WLED_FS.rename(s_cfg_json, backupname); + doReboot = true; + } +} + bool deserializeConfigFromFS() { [[maybe_unused]] bool success = deserializeConfigSec(); #ifdef WLED_ADD_EEPROM_SUPPORT @@ -676,6 +699,7 @@ bool deserializeConfigFromFS() { void serializeConfig() { serializeConfigSec(); + backupConfig(); // backup before writing new config DEBUG_PRINTLN(F("Writing settings to /cfg.json...")); diff --git a/wled00/fcn_declare.h b/wled00/fcn_declare.h index 086c107db2..16e4471f31 100644 --- a/wled00/fcn_declare.h +++ b/wled00/fcn_declare.h @@ -24,6 +24,10 @@ void handleIO(); void IRAM_ATTR touchButtonISR(); //cfg.cpp +bool backupConfig(); +bool restoreConfig(); +bool verifyConfig(); +void resetConfig(); bool deserializeConfig(JsonObject doc, bool fromFS = false); bool deserializeConfigFromFS(); bool deserializeConfigSec(); @@ -114,10 +118,15 @@ bool readObjectFromFileUsingId(const char* file, uint16_t id, JsonDocument* dest bool readObjectFromFile(const char* file, const char* key, JsonDocument* dest); void updateFSInfo(); void closeFile(); -inline bool writeObjectToFileUsingId(const String &file, uint16_t id, JsonDocument* content) { return writeObjectToFileUsingId(file.c_str(), id, content); }; -inline bool writeObjectToFile(const String &file, const char* key, JsonDocument* content) { return writeObjectToFile(file.c_str(), key, content); }; -inline bool readObjectFromFileUsingId(const String &file, uint16_t id, JsonDocument* dest) { return readObjectFromFileUsingId(file.c_str(), id, dest); }; -inline bool readObjectFromFile(const String &file, const char* key, JsonDocument* dest) { return readObjectFromFile(file.c_str(), key, dest); }; +inline bool writeObjectToFileUsingId(const String &file, uint16_t id, const JsonDocument* content) { return writeObjectToFileUsingId(file.c_str(), id, content); }; +inline bool writeObjectToFile(const String &file, const char* key, const JsonDocument* content) { return writeObjectToFile(file.c_str(), key, content); }; +inline bool readObjectFromFileUsingId(const String &file, uint16_t id, JsonDocument* dest, const JsonDocument* filter = nullptr) { return readObjectFromFileUsingId(file.c_str(), id, dest); }; +inline bool readObjectFromFile(const String &file, const char* key, JsonDocument* dest, const JsonDocument* filter = nullptr) { return readObjectFromFile(file.c_str(), key, dest); }; +bool copyFile(const char* src_path, const char* dst_path); +bool backupFile(const char* filename); +bool restoreFile(const char* filename); +bool validateJsonFile(const char* filename); +void dumpFilesToSerial(); //hue.cpp void handleHue(); @@ -399,6 +408,15 @@ void enumerateLedmaps(); uint8_t get_random_wheel_index(uint8_t pos); float mapf(float x, float in_min, float in_max, float out_min, float out_max); +void handleBootLoop(); // detect and handle bootloops +#ifndef ESP8266 +void bootloopCheckOTA(); // swap boot image if bootloop is detected instead of restoring config +#endif + +void handleBootLoop(); // detect and handle bootloops +#ifndef ESP8266 +void bootloopCheckOTA(); // swap boot image if bootloop is detected instead of restoring config +#endif // RAII guard class for the JSON Buffer lock // Modeled after std::lock_guard class JSONBufferGuard { diff --git a/wled00/file.cpp b/wled00/file.cpp index bc34672023..efd50123c7 100644 --- a/wled00/file.cpp +++ b/wled00/file.cpp @@ -438,3 +438,156 @@ bool handleFileRead(AsyncWebServerRequest* request, String path){ } return false; } + +// copy a file, delete destination file if incomplete to prevent corrupted files +bool copyFile(const char* src_path, const char* dst_path) { + DEBUG_PRINTF("copyFile from %s to %s\n", src_path, dst_path); + if(!WLED_FS.exists(src_path)) { + DEBUG_PRINTLN(F("file not found")); + return false; + } + + bool success = true; // is set to false on error + File src = WLED_FS.open(src_path, "r"); + File dst = WLED_FS.open(dst_path, "w"); + + if (src && dst) { + uint8_t buf[128]; // copy file in 128-byte blocks + while (src.available() > 0) { + size_t bytesRead = src.read(buf, sizeof(buf)); + if (bytesRead == 0) { + success = false; + break; // error, no data read + } + size_t bytesWritten = dst.write(buf, bytesRead); + if (bytesWritten != bytesRead) { + success = false; + break; // error, not all data written + } + } + } else { + success = false; // error, could not open files + } + if(src) src.close(); + if(dst) dst.close(); + if (!success) { + DEBUG_PRINTLN(F("copy failed")); + WLED_FS.remove(dst_path); // delete incomplete file + } + return success; +} + +// compare two files, return true if identical +bool compareFiles(const char* path1, const char* path2) { + DEBUG_PRINTF("compareFile %s and %s\n", path1, path2); + if (!WLED_FS.exists(path1) || !WLED_FS.exists(path2)) { + DEBUG_PRINTLN(F("file not found")); + return false; + } + + bool identical = true; // set to false on mismatch + File f1 = WLED_FS.open(path1, "r"); + File f2 = WLED_FS.open(path2, "r"); + + if (f1 && f2) { + uint8_t buf1[128], buf2[128]; + while (f1.available() > 0 || f2.available() > 0) { + size_t len1 = f1.read(buf1, sizeof(buf1)); + size_t len2 = f2.read(buf2, sizeof(buf2)); + + if (len1 != len2) { + identical = false; + break; // files differ in size or read failed + } + + if (memcmp(buf1, buf2, len1) != 0) { + identical = false; + break; // files differ in content + } + } + } else { + identical = false; // error opening files + } + + if (f1) f1.close(); + if (f2) f2.close(); + return identical; +} + +static const char s_backup_fmt[] PROGMEM = "/bkp.%s"; + +bool backupFile(const char* filename) { + DEBUG_PRINTF("backup %s \n", filename); + if (!validateJsonFile(filename)) { + DEBUG_PRINTLN(F("broken file")); + return false; + } + char backupname[32]; + snprintf_P(backupname, sizeof(backupname), s_backup_fmt, filename + 1); // skip leading '/' in filename + + if (copyFile(filename, backupname)) { + DEBUG_PRINTLN(F("backup ok")); + return true; + } + DEBUG_PRINTLN(F("backup failed")); + return false; +} + +bool restoreFile(const char* filename) { + DEBUG_PRINTF("restore %s \n", filename); + char backupname[32]; + snprintf_P(backupname, sizeof(backupname), s_backup_fmt, filename + 1); // skip leading '/' in filename + + if (!WLED_FS.exists(backupname)) { + DEBUG_PRINTLN(F("no backup found")); + return false; + } + + if (!validateJsonFile(backupname)) { + DEBUG_PRINTLN(F("broken backup")); + return false; + } + + if (copyFile(backupname, filename)) { + DEBUG_PRINTLN(F("restore ok")); + return true; + } + DEBUG_PRINTLN(F("restore failed")); + return false; +} + +bool validateJsonFile(const char* filename) { + if (!WLED_FS.exists(filename)) return false; + File file = WLED_FS.open(filename, "r"); + if (!file) return false; + StaticJsonDocument<0> doc, filter; // https://arduinojson.org/v6/how-to/validate-json/ + bool result = deserializeJson(doc, file, DeserializationOption::Filter(filter)) == DeserializationError::Ok; + file.close(); + if (!result) { + DEBUG_PRINTF_P(PSTR("Invalid JSON file %s\n"), filename); + } else { + DEBUG_PRINTF_P(PSTR("Valid JSON file %s\n"), filename); + } + return result; +} + +// print contents of all files in root dir to Serial except wsec files +void dumpFilesToSerial() { + File rootdir = WLED_FS.open("/", "r"); + File rootfile = rootdir.openNextFile(); + while (rootfile) { + size_t len = strlen(rootfile.name()); + // skip files starting with "wsec" and dont end in .json + if (strncmp(rootfile.name(), "wsec", 4) != 0 && len >= 6 && strcmp(rootfile.name() + len - 5, ".json") == 0) { + Serial.println(rootfile.name()); + while (rootfile.available()) { + Serial.write(rootfile.read()); + } + Serial.println(); + Serial.println(); + } + rootfile.close(); + rootfile = rootdir.openNextFile(); + } +} + diff --git a/wled00/ota_update.cpp b/wled00/ota_update.cpp index b678def1c9..2f3d6145e6 100644 --- a/wled00/ota_update.cpp +++ b/wled00/ota_update.cpp @@ -73,6 +73,9 @@ static void endOTA(AsyncWebServerRequest *request) { // If the upload is incomplete, Update.end(false) should error out. if (Update.end(context->uploadComplete)) { // Update successful! + #ifndef ESP8266 + bootloopCheckOTA(); // let the bootloop-checker know there was an OTA update + #endif doReboot = true; context->needsRestart = false; } @@ -109,6 +112,7 @@ static bool beginOTA(AsyncWebServerRequest *request, UpdateContext* context) strip.suspend(); strip.resetSegments(); // free as much memory as you can context->needsRestart = true; + backupConfig(); // backup current config in case the update ends badly DEBUG_PRINTF_P(PSTR("OTA Update Start, %x --> %x\n"), (uintptr_t)request,(uintptr_t) context); diff --git a/wled00/util.cpp b/wled00/util.cpp index 41e3d6c235..301b037b70 100644 --- a/wled00/util.cpp +++ b/wled00/util.cpp @@ -1,6 +1,16 @@ #include "wled.h" #include "fcn_declare.h" #include "const.h" +#ifdef ESP8266 +#include "user_interface.h" // for bootloop detection +#else +#include +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) + #include "esp32/rtc.h" // for bootloop detection +#elif ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(3, 3, 0) + #include "soc/rtc.h" +#endif +#endif //helper to get int value at a position in string @@ -594,3 +604,144 @@ uint8_t get_random_wheel_index(uint8_t pos) { float mapf(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } + +// bootloop detection and handling +// checks if the ESP reboots multiple times due to a crash or watchdog timeout +// if a bootloop is detected: restore settings from backup, then reset settings, then switch boot image (and repeat) + +#define BOOTLOOP_INTERVAL_MILLIS 120000 // time limit between crashes: 120 seconds (2 minutes) +#define BOOTLOOP_THRESHOLD 5 // number of consecutive crashes to trigger bootloop detection +#define BOOTLOOP_ACTION_RESTORE 0 // default action: restore config from /bkp.cfg.json +#define BOOTLOOP_ACTION_RESET 1 // if restore does not work, reset config (rename /cfg.json to /rst.cfg.json) +#define BOOTLOOP_ACTION_OTA 2 // swap the boot partition +#define BOOTLOOP_ACTION_DUMP 3 // nothing seems to help, dump files to serial and reboot (until hardware reset) + +// Platform-agnostic abstraction +enum class ResetReason { + Power, + Software, + Crash, + Brownout +}; + +#ifdef ESP8266 +// Place variables in RTC memory via references, since RTC memory is not exposed via the linker in the Non-OS SDK +// Use an offset of 32 as there's some hints that the first 128 bytes of "user" memory are used by the OTA system +// Ref: https://github.com/esp8266/Arduino/blob/78d0d0aceacc1553f45ad8154592b0af22d1eede/cores/esp8266/Esp.cpp#L168 +static volatile uint32_t& bl_last_boottime = *(RTC_USER_MEM + 32); +static volatile uint32_t& bl_crashcounter = *(RTC_USER_MEM + 33); +static volatile uint32_t& bl_actiontracker = *(RTC_USER_MEM + 34); + +static inline ResetReason rebootReason() { + uint32_t resetReason = system_get_rst_info()->reason; + if (resetReason == REASON_EXCEPTION_RST + || resetReason == REASON_WDT_RST + || resetReason == REASON_SOFT_WDT_RST) + return ResetReason::Crash; + if (resetReason == REASON_SOFT_RESTART) + return ResetReason::Software; + return ResetReason::Power; +} + +static inline uint32_t getRtcMillis() { return system_get_rtc_time() / 160; }; // rtc ticks ~160000Hz + +#else +// variables in RTC_NOINIT memory persist between reboots (but not on hardware reset) +RTC_NOINIT_ATTR static uint32_t bl_last_boottime; +RTC_NOINIT_ATTR static uint32_t bl_crashcounter; +RTC_NOINIT_ATTR static uint32_t bl_actiontracker; + +static inline ResetReason rebootReason() { + esp_reset_reason_t reason = esp_reset_reason(); + if (reason == ESP_RST_BROWNOUT) return ResetReason::Brownout; + if (reason == ESP_RST_SW) return ResetReason::Software; + if (reason == ESP_RST_PANIC || reason == ESP_RST_WDT || reason == ESP_RST_INT_WDT || reason == ESP_RST_TASK_WDT) return ResetReason::Crash; + return ResetReason::Power; +} + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) +static inline uint32_t getRtcMillis() { return esp_rtc_get_time_us() / 1000; } +#elif ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(3, 3, 0) +static inline uint32_t getRtcMillis() { return rtc_time_slowclk_to_us(rtc_time_get(), rtc_clk_slow_freq_get_hz()) / 1000; } +#endif + +void bootloopCheckOTA() { bl_actiontracker = BOOTLOOP_ACTION_OTA; } // swap boot image if bootloop is detected instead of restoring config + +#endif + +// detect bootloop by checking the reset reason and the time since last boot +static bool detectBootLoop() { + uint32_t rtctime = getRtcMillis(); + bool result = false; + + switch(rebootReason()) { + case ResetReason::Power: + bl_actiontracker = BOOTLOOP_ACTION_RESTORE; // init action tracker if not an intentional reboot (e.g. from OTA or bootloop handler) + // fall through + case ResetReason::Software: + // no crash detected, reset counter + bl_crashcounter = 0; + break; + + case ResetReason::Crash: + { + uint32_t rebootinterval = rtctime - bl_last_boottime; + if (rebootinterval < BOOTLOOP_INTERVAL_MILLIS) { + bl_crashcounter++; + if (bl_crashcounter >= BOOTLOOP_THRESHOLD) { + DEBUG_PRINTLN(F("!BOOTLOOP DETECTED!")); + bl_crashcounter = 0; + if(bl_actiontracker > BOOTLOOP_ACTION_DUMP) bl_actiontracker = BOOTLOOP_ACTION_RESTORE; // reset action tracker if out of bounds + result = true; + } + } else { + // Reset counter on long intervals to track only consecutive short-interval crashes + bl_crashcounter = 0; + // TODO: crash reporting goes here + } + break; + } + + case ResetReason::Brownout: + // crash due to brownout can't be detected unless using flash memory to store bootloop variables + DEBUG_PRINTLN(F("brownout detected")); + //restoreConfig(); // TODO: blindly restoring config if brownout detected is a bad idea, need a better way (if at all) + break; + } + + bl_last_boottime = rtctime; // store current runtime for next reboot + + return result; +} + +void handleBootLoop() { + DEBUG_PRINTF_P(PSTR("checking for bootloop: time %d, counter %d, action %d\n"), bl_last_boottime, bl_crashcounter, bl_actiontracker); + if (!detectBootLoop()) return; // no bootloop detected + + switch(bl_actiontracker) { + case BOOTLOOP_ACTION_RESTORE: + restoreConfig(); + ++bl_actiontracker; + break; + case BOOTLOOP_ACTION_RESET: + resetConfig(); + ++bl_actiontracker; + break; + case BOOTLOOP_ACTION_OTA: +#ifndef ESP8266 + if(Update.canRollBack()) { + DEBUG_PRINTLN(F("Swapping boot partition...")); + Update.rollBack(); // swap boot partition + } + ++bl_actiontracker; + break; +#else + // fall through +#endif + case BOOTLOOP_ACTION_DUMP: + dumpFilesToSerial(); + break; + } + + ESP.restart(); // restart cleanly and don't wait for another crash +} diff --git a/wled00/wled.cpp b/wled00/wled.cpp index 722182ee89..0a72265831 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -404,6 +404,9 @@ void WLED::setup() DEBUGFS_PRINTLN(F("FS failed!")); errorFlag = ERR_FS_BEGIN; } + + handleBootLoop(); // check for bootloop and take action (requires WLED_FS) + #ifdef WLED_ADD_EEPROM_SUPPORT else deEEP(); #else @@ -419,6 +422,11 @@ void WLED::setup() WLED_SET_AP_SSID(); // otherwise it is empty on first boot until config is saved multiWiFi.push_back(WiFiConfig(CLIENT_SSID,CLIENT_PASS)); // initialise vector with default WiFi + if(!verifyConfig()) { + if(!restoreConfig()) { + resetConfig(); + } + } DEBUG_PRINTLN(F("Reading config")); bool needsCfgSave = deserializeConfigFromFS(); DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());