diff --git a/src/main.cpp b/src/main.cpp index 7bd51b3..0b91b05 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -424,27 +424,24 @@ static void factoryReset(bool clearWifi) { ESP.restart(); } -static void checkFactoryReset() { - const int THRESHOLD_CONFIG = 5; - const int THRESHOLD_WIFI = 10; +static int incrementResetCount() { int count = 0; File f = LittleFS.open("/reset_count", "r"); - if (f) { - count = f.parseInt(); - f.close(); - } + if (f) { count = f.parseInt(); f.close(); } count++; + f = LittleFS.open("/reset_count", "w"); + if (f) { f.print(count); f.close(); } + Serial.printf("[BOOT] reset count %d\n", count); + return count; +} + +static void applyFactoryResetIfNeeded(int count) { + const int THRESHOLD_CONFIG = 5; + const int THRESHOLD_WIFI = 10; + LittleFS.remove("/reset_count"); if (count >= THRESHOLD_CONFIG) { - LittleFS.remove("/reset_count"); Serial.printf("[BOOT] reset count %d, triggering factory reset\n", count); factoryReset(count >= THRESHOLD_WIFI); - return; - } - f = LittleFS.open("/reset_count", "w"); - if (f) { - f.print(count); - f.close(); - Serial.printf("[BOOT] reset count %d/%d\n", count, THRESHOLD_CONFIG); } } @@ -460,13 +457,13 @@ void setup() { loadConfig(); hostnameParam.setValue(hostname, strlen(hostname)); - checkFactoryReset(); + int resetCount = incrementResetCount(); - // Reset-counter settle window: if the device stays powered past this point it - // wasn't a rapid power-cycle, so clear the counter before the (possibly - // indefinitely blocking) WiFi portal. + // Settle window: if the device stays powered past this point it wasn't a + // rapid power-cycle. After the delay, act on the accumulated count (5x = + // config reset, 10x = config + WiFi reset) then clear the counter. delay(3000); - LittleFS.remove("/reset_count"); + applyFactoryResetIfNeeded(resetCount); Serial.println("[WIFI] starting WiFiManager"); WiFiManager wm;