NVS not saving arrays inside blob correctly
Posted: Tue Oct 30, 2018 5:32 pm
I'm using NVS to save an array of structures. My code is based on the ESP32 example project that saves an int and a blob. The code works and I get no errors but when I retrieve the data it does not match the data I saved. The integer values in the structure are saved correctly but the arrays"name" and "week_days" are not. I guess it's saving the pointer instead of saving the value but i don't know how to save the value correctly.
The structure I am trying to save is as follows:
Here is the code I use to save the array 'events':
And here is the code I use to retrieve the saved 'events' array:
Can anyone see what I am doing wrong?
The structure I am trying to save is as follows:
Code: Select all
typedef struct Events {
char *name;
int hour;
int minutes;
int *week_days;
} Event;
Code: Select all
nvs_handle my_handle;
size_t required_size = 0;
err = nvs_get_blob(my_handle, "events", NULL, &required_size);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) return err;
Event* events = malloc(required_size + sizeof(event));
if (required_size > 0) {
err = nvs_get_blob(my_handle, "events", events, &required_size);
if (err != ESP_OK) return err;
}
required_size += sizeof(event);
events[required_size / sizeof(event) - 1] = event;
err = nvs_set_blob(my_handle, "events", events, required_size);
free(events);
if (err != ESP_OK) return err;
err = nvs_commit(my_handle);
if (err != ESP_OK) return err;
nvs_close(my_handle);
Code: Select all
nvs_handle my_handle;
size_t required_size = 0;
err = nvs_get_blob(my_handle, "events", NULL, &required_size);
Event* events = malloc(required_size);
err = nvs_get_blob(my_handle, "events", events, &required_size);
if (err != ESP_OK) return err;
for (int i = 0; i < required_size / sizeof(Event); i++) {
printf("%d: %s\n", i + 1, events[i].name);
printf("%d: %d\n", i + 1, events[i].hour);
printf("%d: %d\n", i + 1, events[i].minutes);
printf("%d: %d\n", i + 1, events[i].week_days[0]);
printf("%d: %d\n", i + 1, events[i].week_days[1]);
}
free(events);
nvs_close(my_handle);