diff --git a/include/configmanager.h b/include/configmanager.h index a8be749c..a8da2114 100644 --- a/include/configmanager.h +++ b/include/configmanager.h @@ -8,7 +8,7 @@ extern configData_t cfg; void saveConfig(bool erase); -bool loadConfig(void); +void loadConfig(void); void eraseConfig(void); int version_compare(const String v1, const String v2); diff --git a/src/configmanager.cpp b/src/configmanager.cpp index 55282311..7de8d127 100644 --- a/src/configmanager.cpp +++ b/src/configmanager.cpp @@ -98,30 +98,33 @@ void saveConfig(bool erase) { } // load configuration from NVRAM into RAM and make it current -bool loadConfig() { +void loadConfig(void) { + + int readBytes = 0; ESP_LOGI(TAG, "Loading device configuration from NVRAM..."); - if (!nvram.begin(DEVCONFIG, true)) { + if (nvram.begin(DEVCONFIG, true)) { + // load device runtime config from nvram and copy it to byte array + readBytes = nvram.getBytes(DEVCONFIG, buffer, cfgLen + cfgLen2); + nvram.end(); + + // check that runtime config data length matches + if (readBytes != cfgLen + cfgLen2) { + ESP_LOGE(TAG, "No valid configuration found"); + migrateConfig(); + } + + } else { ESP_LOGI(TAG, "NVRAM initialized, device starts with factory settings"); eraseConfig(); } - // simple check that runtime config data matches - // if (nvram.getBytesLength(DEVCONFIG) != (cfgLen + cfgLen2)) { - // ESP_LOGE(TAG, "Configuration invalid"); - // return false; - //} - - // load device runtime config from nvram and copy it to byte array - nvram.getBytes(DEVCONFIG, buffer, cfgLen + cfgLen2); - nvram.end(); - // validate loaded configuration by checking magic bytes at end of array - // if (memcmp(buffer + cfgLen, &cfgMagicBytes, cfgLen2) != 0) { - // ESP_LOGW(TAG, "No configuration found"); - // return false; - //} + if (memcmp(buffer + cfgLen, &cfgMagicBytes, cfgLen2) != 0) { + ESP_LOGE(TAG, "Configuration data corrupt"); + eraseConfig(); + } // copy loaded configuration into runtime cfg struct memcpy(&cfg, buffer, cfgLen); @@ -132,13 +135,13 @@ bool loadConfig() { case -1: // device configuration belongs to newer than current firmware ESP_LOGE(TAG, "Incompatible device configuration"); eraseConfig(); - return true; + break; case 1: // device configuration belongs to older than current firmware ESP_LOGW(TAG, "Device was updated, attempt to migrate configuration"); migrateConfig(); - return true; + break; default: // device configuration version matches current firmware version - return true; + break; // nothing to do here } }