storage.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * SPDX-FileCopyrightText: 2022 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <time.h>
  7. #include <stdio.h>
  8. #include <esp_err.h>
  9. #include <nvs_flash.h>
  10. #include <esp_log.h>
  11. #define TAG "storage"
  12. static nvs_handle_t handle;
  13. static void format_date(struct tm* datetime, char* output) {
  14. char year[12], month[12], day[12];
  15. snprintf(year, 12, "%4d", datetime->tm_year + 1900);
  16. snprintf(month, 12, "%02d", datetime->tm_mon +1);
  17. snprintf(day, 12, "%02d", datetime->tm_mday);
  18. snprintf(output, 9, "%.4s%.2s%.2s", year, month, day);
  19. }
  20. esp_err_t storage_init(char* name) {
  21. return nvs_open(name, NVS_READWRITE, &handle);
  22. }
  23. esp_err_t write_wakeup_time_str(char* key, int16_t value) {
  24. esp_err_t ret = nvs_set_i16(handle, key, value);
  25. return ret | nvs_commit(handle);
  26. }
  27. esp_err_t write_wakeup_time_tm(struct tm* datetime, int16_t value) {
  28. char key[9];
  29. format_date(datetime, key);
  30. return write_wakeup_time_str(key, value);
  31. }
  32. esp_err_t read_wakeup_time_str(char* key, int16_t* value) {
  33. return nvs_get_i16(handle, key, value);
  34. }
  35. esp_err_t read_wakeup_time_tm(struct tm* datetime, int16_t* value) {
  36. char key[9];
  37. format_date(datetime, key);
  38. return read_wakeup_time_str(key, value);
  39. }
  40. esp_err_t delete_wakeup_time_str(char* key) {
  41. esp_err_t ret = nvs_erase_key(handle, key);
  42. return ret | nvs_commit(handle);
  43. }
  44. void delete_outdated_entries(struct tm* datetime, char* namespace) {
  45. char reference_date_str[9];
  46. format_date(datetime, reference_date_str);
  47. int reference_date = atoi(reference_date_str);
  48. if (reference_date == 0) {
  49. ESP_LOGE(TAG, "Error while determining reference date");
  50. return;
  51. }
  52. nvs_iterator_t it = NULL;
  53. esp_err_t res = nvs_entry_find("nvs", namespace, NVS_TYPE_ANY, &it);
  54. while(res == ESP_OK) {
  55. nvs_entry_info_t info;
  56. nvs_entry_info(it, &info);
  57. int entry_date = atoi(info.key);
  58. if (entry_date == 0) {
  59. ESP_LOGI(TAG, "Could not convert key %s to int, skipping entry during cleanup", info.key);
  60. } else if (entry_date < reference_date) {
  61. ESP_LOGI(TAG, "Erasing outdated entry %s", info.key);
  62. nvs_erase_key(handle, info.key);
  63. }
  64. res = nvs_entry_next(&it);
  65. }
  66. nvs_commit(handle);
  67. nvs_release_iterator(it);
  68. }