/* * SPDX-FileCopyrightText: 2022-2023 Helmut Pozimski * * SPDX-License-Identifier: GPL-2.0-only */ #include #include #include #include #include #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(const char* name) { return nvs_open(name, NVS_READWRITE, &handle); } esp_err_t write_wakeup_time_str(const char* key, int16_t value) { esp_err_t ret = nvs_set_i16(handle, key, value); return ret | nvs_commit(handle); } esp_err_t write_wakeup_time_tm(struct tm* datetime, int16_t value) { char key[9]; format_date(datetime, key); return write_wakeup_time_str(key, value); } esp_err_t read_wakeup_time_str(const char* key, int16_t* value) { return nvs_get_i16(handle, key, value); } esp_err_t read_wakeup_time_tm(struct tm* datetime, int16_t* value) { char key[9]; format_date(datetime, key); return read_wakeup_time_str(key, value); } esp_err_t delete_wakeup_time_str(const char* key) { esp_err_t ret = nvs_erase_key(handle, key); return ret | nvs_commit(handle); } void delete_outdated_entries(struct tm* datetime, const 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); }