SolarEnergy/esp32_device/main/storage.c

89 lines
2.0 KiB
C

#include "constants.h"
#include "storage.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include <string.h>
#define STORAGE_NAMESPACE "storage"
#define DEV_NAME_KEY "dev_name"
#define PRIVATE_KEY "prikey"
static const char *TAG = "storage";
bool storage_init()
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_LOGI(TAG, "Need to reset storage\n");
// NVS partition was truncated and needs to be erased
// Retry nvs_flash_init
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
return err == ESP_OK;
}
void storage_set_dev_name(const char *name)
{
nvs_handle_t my_handle;
ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle));
ESP_ERROR_CHECK(nvs_set_blob(my_handle, DEV_NAME_KEY, name, strlen(name) + 1));
nvs_close(my_handle);
}
size_t storage_get_dev_name(char *dest)
{
nvs_handle_t my_handle;
ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle));
size_t len = (dest == NULL ? 0 : DEV_NAME_LEN);
esp_err_t res = nvs_get_blob(my_handle, DEV_NAME_KEY, dest, &len);
nvs_close(my_handle);
if (res == ESP_ERR_NVS_NOT_FOUND || len == 0)
return 0;
ESP_ERROR_CHECK(res);
return len;
}
void storage_set_priv_key(unsigned char *key, size_t len)
{
nvs_handle_t my_handle;
ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle));
ESP_ERROR_CHECK(nvs_set_blob(my_handle, PRIVATE_KEY, key, len));
nvs_close(my_handle);
}
size_t storage_get_priv_key(unsigned char *key)
{
nvs_handle_t my_handle;
ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle));
size_t len = (key == NULL ? 0 : PRV_KEY_DER_MAX_BYTES);
esp_err_t res = nvs_get_blob(my_handle, PRIVATE_KEY, key, &len);
nvs_close(my_handle);
if (res == ESP_ERR_NVS_NOT_FOUND || len == 0)
return 0;
ESP_ERROR_CHECK(res);
return len;
}