diff options
| author | jacqueline <me@jacqueline.id.au> | 2023-08-08 20:25:42 +1000 |
|---|---|---|
| committer | jacqueline <me@jacqueline.id.au> | 2023-08-08 20:25:42 +1000 |
| commit | e1181fbe59a835ea9c93d6e067e9757e8c522d3c (patch) | |
| tree | 2fd61bb93713de8c2205b7b6d0a8c84c49832e93 /src/drivers/nvs.cpp | |
| parent | c3f40a8cc37114365ef3ec6f2888df64e5206b39 (diff) | |
| parent | 592f231627843bc44ebaaa4506aec26da1f56499 (diff) | |
| download | tangara-fw-e1181fbe59a835ea9c93d6e067e9757e8c522d3c.tar.gz | |
Merge branch 'main' into opus
Diffstat (limited to 'src/drivers/nvs.cpp')
| -rw-r--r-- | src/drivers/nvs.cpp | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/src/drivers/nvs.cpp b/src/drivers/nvs.cpp new file mode 100644 index 00000000..a2de9518 --- /dev/null +++ b/src/drivers/nvs.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2023 jacqueline <me@jacqueline.id.au> + * + * SPDX-License-Identifier: GPL-3.0-only + */ + +#include "nvs.hpp" +#include <stdint.h> + +#include <cstdint> +#include <memory> + +#include "esp_log.h" +#include "nvs.h" +#include "nvs_flash.h" + +namespace drivers { + +static constexpr char kTag[] = "nvm"; +static constexpr uint8_t kSchemaVersion = 1; + +static constexpr char kKeyVersion[] = "ver"; + +auto NvsStorage::Open() -> NvsStorage* { + esp_err_t err = nvs_flash_init(); + if (err == ESP_ERR_NVS_NO_FREE_PAGES) { + ESP_LOGW(kTag, "partition needs initialisation"); + nvs_flash_erase(); + err = nvs_flash_init(); + } + if (err != ESP_OK) { + ESP_LOGE(kTag, "failed to init nvm"); + return nullptr; + } + + nvs_handle_t handle; + if ((err = nvs_open("tangara", NVS_READWRITE, &handle)) != ESP_OK) { + ESP_LOGE(kTag, "failed to open nvs namespace"); + return nullptr; + } + + std::unique_ptr<NvsStorage> instance = std::make_unique<NvsStorage>(handle); + if (instance->SchemaVersion() < kSchemaVersion) { + ESP_LOGW(kTag, "namespace needs downgrading"); + nvs_erase_all(handle); + nvs_set_u8(handle, kKeyVersion, kSchemaVersion); + err = nvs_commit(handle); + if (err != ESP_OK) { + ESP_LOGW(kTag, "failed to init namespace"); + return nullptr; + } + } + + ESP_LOGI(kTag, "nvm storage initialised okay"); + return instance.release(); +} + +NvsStorage::NvsStorage(nvs_handle_t handle) : handle_(handle) {} + +NvsStorage::~NvsStorage() { + nvs_close(handle_); + nvs_flash_deinit(); +} + +auto NvsStorage::SchemaVersion() -> uint8_t { + uint8_t ret; + if (nvs_get_u8(handle_, kKeyVersion, &ret) != ESP_OK) { + return UINT8_MAX; + } + return ret; +} + +} // namespace drivers |
