[SYS] Avoid nvs errors (#1588)

Avoid nvs errors when trying to load or erase non-existent nvs preferences.
This commit is contained in:
DigiH authored and GitHub committed 2023-04-05 14:18:59 -05:00
1 parent 9b6133ff03
commit e560bd7904
3 files changed
+46 -37

No files matched your search

+20 -16
View File
@@ -46,10 +46,12 @@ void ONOFFConfig_fromJson(JsonObject& ONOFFdata) {
if (ONOFFdata.containsKey("erase") && ONOFFdata["erase"].as<bool>()) {
// Erase config from NVS (non-volatile storage)
preferences.begin(Gateway_Short_Name, false);
preferences.remove("ONOFFConfig");
preferences.end();
Log.notice(F("ONOFF config erased" CR));
return; // Erase prevails on save, so skipping save
if (preferences.isKey("ONOFFConfig")) {
preferences.remove("ONOFFConfig");
preferences.end();
Log.notice(F("ONOFF config erased" CR));
return; // Erase prevails on save, so skipping save
}
}
if (ONOFFdata.containsKey("save") && ONOFFdata["save"].as<bool>()) {
StaticJsonDocument<JSON_MSG_BUFFER> jsonBuffer;
@@ -69,19 +71,21 @@ void ONOFFConfig_fromJson(JsonObject& ONOFFdata) {
void ONOFFConfig_load() {
StaticJsonDocument<JSON_MSG_BUFFER> jsonBuffer;
preferences.begin(Gateway_Short_Name, true);
auto error = deserializeJson(jsonBuffer, preferences.getString("ONOFFConfig", "{}"));
preferences.end();
if (error) {
Log.error(F("ONOFF config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity());
return;
if (preferences.isKey("ONOFFConfig")) {
auto error = deserializeJson(jsonBuffer, preferences.getString("ONOFFConfig", "{}"));
preferences.end();
if (error) {
Log.error(F("ONOFF config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity());
return;
}
if (jsonBuffer.isNull()) {
Log.warning(F("ONOFF config is null" CR));
return;
}
JsonObject jo = jsonBuffer.as<JsonObject>();
ONOFFConfig_fromJson(jo);
Log.notice(F("ONOFF config loaded" CR));
}
if (jsonBuffer.isNull()) {
Log.warning(F("ONOFF config is null" CR));
return;
}
JsonObject jo = jsonBuffer.as<JsonObject>();
ONOFFConfig_fromJson(jo);
Log.notice(F("ONOFF config loaded" CR));
}
# else
void ONOFFConfig_init(){};