#include "nvs_flash.h" #include "esp_log.h" #include #include "nvs.h" #define NVS_GOAM_NAMESPACE "goam" static const char *TAG = "nvs"; static void nvs_init_partition(const char* partition) { esp_err_t ret = nvs_flash_init_partition(partition); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase_partition(partition)); ret = nvs_flash_init_partition(partition); } ESP_ERROR_CHECK(ret); } void nvs_init() { nvs_init_partition("nvs"); ESP_LOGI(TAG, "NVS initialized"); } void nvs_write(const char* key, const char* value) { nvs_handle_t outHandle; ESP_ERROR_CHECK(nvs_open(NVS_GOAM_NAMESPACE, NVS_READWRITE, &outHandle)); ESP_ERROR_CHECK(nvs_set_str(outHandle, key, value)); ESP_ERROR_CHECK(nvs_commit(outHandle)); nvs_close(outHandle); } void nvs_read(const char* key, char** output) { nvs_handle_t inHandle; esp_err_t err = nvs_open(NVS_GOAM_NAMESPACE, NVS_READONLY, &inHandle); if (err == ESP_ERR_NVS_NOT_FOUND) { *output = NULL; nvs_close(inHandle); return; } ESP_ERROR_CHECK(err); size_t size = 0; err = nvs_get_str(inHandle, key, NULL, &size); if (err != ESP_OK) { *output = NULL; nvs_close(inHandle); return; } if (size == 0) { *output = NULL; nvs_close(inHandle); return; } free(*output); *output = malloc(size * sizeof(char)); ESP_ERROR_CHECK(nvs_get_str(inHandle, key, *output, &size)); nvs_close(inHandle); } void nvs_write_i32(const char* key, int32_t value) { nvs_handle_t outHandle; ESP_ERROR_CHECK(nvs_open(NVS_GOAM_NAMESPACE, NVS_READWRITE, &outHandle)); ESP_ERROR_CHECK(nvs_set_i32(outHandle, key, value)); ESP_ERROR_CHECK(nvs_commit(outHandle)); nvs_close(outHandle); } void nvs_read_i32(const char* key, int32_t* output) { nvs_handle_t inHandle; esp_err_t err = nvs_open(NVS_GOAM_NAMESPACE, NVS_READONLY, &inHandle); if (err == ESP_ERR_NVS_NOT_FOUND) { nvs_close(inHandle); return; } ESP_ERROR_CHECK(err); err = nvs_get_i32(inHandle, key, output); if (err != ESP_OK) { nvs_close(inHandle); return; } nvs_close(inHandle); }