diff --git a/src/web_server.cpp b/src/web_server.cpp index 6fadec3..f233089 100644 --- a/src/web_server.cpp +++ b/src/web_server.cpp @@ -567,10 +567,21 @@ static void handle_wifi_post() { cfg.ntp_server_2 = server.arg("ntp2"); } cfg.valid = true; + if (!wifi_save_config(cfg)) { + if (SERIAL_DEBUG_MODE) { + Serial.println("wifi_cfg: save failed, reboot cancelled"); + } + String html = html_header("WiFi/MQTT Config"); + html += "
Save failed. Configuration was not persisted and reboot was cancelled.
"; + html += ""; + html += html_footer(); + server.send(500, "text/html", html); + return; + } + g_config = cfg; g_web_user = cfg.web_user; g_web_pass = cfg.web_pass; - wifi_save_config(cfg); server.send(200, "text/html", "Saved. Rebooting..."); delay(1000); ESP.restart(); diff --git a/src/wifi_manager.cpp b/src/wifi_manager.cpp index 9ea7195..7481768 100644 --- a/src/wifi_manager.cpp +++ b/src/wifi_manager.cpp @@ -5,6 +5,59 @@ static Preferences prefs; +static bool wifi_log_save_failure(const char *key, const char *reason) { + if (SERIAL_DEBUG_MODE) { + Serial.printf("wifi_cfg: save failed key=%s reason=%s\n", key, reason); + } + return false; +} + +static bool wifi_write_string_pref(const char *key, const String &value) { + size_t written = prefs.putString(key, value); + if (written != value.length()) { + return wifi_log_save_failure(key, "write_short"); + } + if (!prefs.isKey(key)) { + return wifi_log_save_failure(key, "missing_key"); + } + String readback = prefs.getString(key, ""); + if (readback != value) { + return wifi_log_save_failure(key, "verify_mismatch"); + } + return true; +} + +static bool wifi_write_bool_pref(const char *key, bool value) { + size_t written = prefs.putBool(key, value); + if (written != sizeof(uint8_t)) { + return wifi_log_save_failure(key, "write_short"); + } + if (!prefs.isKey(key)) { + return wifi_log_save_failure(key, "missing_key"); + } + bool readback = prefs.getBool(key, !value); + if (readback != value) { + return wifi_log_save_failure(key, "verify_mismatch"); + } + return true; +} + +static bool wifi_write_ushort_pref(const char *key, uint16_t value) { + size_t written = prefs.putUShort(key, value); + if (written != sizeof(uint16_t)) { + return wifi_log_save_failure(key, "write_short"); + } + if (!prefs.isKey(key)) { + return wifi_log_save_failure(key, "missing_key"); + } + uint16_t fallback = value == static_cast