bedside-clock/components/time/time_storage.c

74 lines
1.6 KiB
C

/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) Camden Dixie O'Brien
*/
#include "time_storage.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <sys/time.h>
#define TAG "Time storage"
#define NVS_NAMESPACE "time"
#define TIMESTAMP_KEY "timestamp"
static void time_saver_func(void *arg)
{
(void)arg;
const TickType_t delay = CONFIG_TIME_SAVE_PERIOD_MS / portTICK_PERIOD_MS;
while (1) {
time_storage_save();
vTaskDelay(delay);
}
}
void time_storage_init()
{
esp_err_t error;
nvs_handle_t nvs;
error = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs);
if (error == ESP_OK) {
uint64_t timestamp;
error = nvs_get_u64(nvs, TIMESTAMP_KEY, &timestamp);
if (error == ESP_OK) {
struct timeval tv = { .tv_sec = (time_t)timestamp };
settimeofday(&tv, NULL);
} else {
if (error != ESP_ERR_NVS_NOT_FOUND)
ESP_LOGE(TAG, "Error getting stored time: %04x", error);
}
nvs_close(nvs);
} else {
if (error != ESP_ERR_NVS_NOT_FOUND)
ESP_LOGE(TAG, "Error opening NVS: %04x", error);
}
(void)xTaskCreate(
&time_saver_func, "time saver", CONFIG_DEFAULT_TASK_STACK, NULL, 1,
NULL);
}
void time_storage_save()
{
esp_err_t error;
nvs_handle_t nvs;
error = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs);
if (error != ESP_OK) {
ESP_LOGE(TAG, "Error opening NVS: %04x", error);
return;
}
struct timeval tv;
gettimeofday(&tv, NULL);
error = nvs_set_u64(nvs, TIMESTAMP_KEY, tv.tv_sec);
if (error != ESP_OK)
ESP_LOGE(TAG, "Error storing time: %04x", error);
nvs_close(nvs);
}