123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- /*
- * SPDX-FileCopyrightText: 2022 Helmut Pozimski <helmut@pozimski.eu>
- *
- * SPDX-License-Identifier: GPL-2.0-only
- */
- #include <time.h>
- #include <stdio.h>
- #include <esp_err.h>
- #include <nvs_flash.h>
- #include <esp_log.h>
- #define TAG "storage"
- static nvs_handle_t handle;
- static void format_date(struct tm* datetime, char* output) {
- char year[12], month[12], day[12];
- snprintf(year, 12, "%4d", datetime->tm_year + 1900);
- snprintf(month, 12, "%02d", datetime->tm_mon +1);
- snprintf(day, 12, "%02d", datetime->tm_mday);
- snprintf(output, 9, "%.4s%.2s%.2s", year, month, day);
- }
- esp_err_t storage_init(char* name) {
- return nvs_open(name, NVS_READWRITE, &handle);
- }
- esp_err_t write_wakeup_time_str(char* key, uint16_t value) {
- esp_err_t ret = nvs_set_u16(handle, key, value);
- return ret | nvs_commit(handle);
- }
- esp_err_t write_wakeup_time_tm(struct tm* datetime, uint16_t value) {
- char key[9];
- format_date(datetime, key);
- return write_wakeup_time_str(key, value);
- }
- esp_err_t read_wakeup_time_str(char* key, uint16_t* value) {
- return nvs_get_u16(handle, key, value);
- }
- esp_err_t read_wakeup_time_tm(struct tm* datetime, uint16_t* value) {
- char key[9];
- format_date(datetime, key);
- return read_wakeup_time_str(key, value);
- }
- esp_err_t delete_wakeup_time_str(char* key) {
- esp_err_t ret = nvs_erase_key(handle, key);
- return ret | nvs_commit(handle);
- }
- void delete_outdated_entries(struct tm* datetime, char* namespace) {
- char reference_date_str[9];
- format_date(datetime, reference_date_str);
- int reference_date = atoi(reference_date_str);
- if (reference_date == 0) {
- ESP_LOGE(TAG, "Error while determining reference date");
- return;
- }
- nvs_iterator_t it = NULL;
- esp_err_t res = nvs_entry_find("nvs", namespace, NVS_TYPE_ANY, &it);
- while(res == ESP_OK) {
- nvs_entry_info_t info;
- nvs_entry_info(it, &info);
- int entry_date = atoi(info.key);
- if (entry_date == 0) {
- ESP_LOGI(TAG, "Could not convert key %s to int, skipping entry during cleanup", info.key);
- } else if (entry_date < reference_date) {
- ESP_LOGI(TAG, "Erasing outdated entry %s", info.key);
- nvs_erase_key(handle, info.key);
- }
- res = nvs_entry_next(&it);
- }
- nvs_commit(handle);
- nvs_release_iterator(it);
- }
|