Move time update logic from display module to time manager

This commit is contained in:
2023-05-17 17:55:13 +01:00
parent d84bb7ac4b
commit 89eb99b80f
5 changed files with 57 additions and 26 deletions

View File

@@ -10,6 +10,8 @@
#include "esp_log.h"
#include "esp_sntp.h"
#include "esp_timer.h"
#include "fatal.h"
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
#include <time.h>
@@ -22,6 +24,12 @@
#define TM_YEAR_OFFSET 1900
#define TM_MONTH_OFFSET 1
#define UPDATE_PERIOD_US 1000000UL
#define MAX_CALLBACKS 8
static TimeCallback callbacks[MAX_CALLBACKS];
static unsigned callback_count;
static void handle_timezone_update(const char *timezone)
{
setenv("TZ", timezone, 1);
@@ -85,6 +93,13 @@ static int store_time(void)
return error == ESP_OK ? 0 : 1;
}
static void run_callbacks(void *arg)
{
const Time time = get_time();
for (unsigned i = 0; i < callback_count; ++i)
callbacks[i](&time);
}
static int time_command_func(int argc, char **argv)
{
if (argc == 1) {
@@ -177,6 +192,8 @@ static void time_saver_func(void *arg)
void time_manager_init(void)
{
callback_count = 0;
char timezone[SETTINGS_MAX_VALUE_SIZE];
(void)settings_get_timezone(timezone, SETTINGS_MAX_VALUE_SIZE);
handle_timezone_update(timezone);
@@ -225,6 +242,34 @@ void time_manager_init(void)
(void)xTaskCreate(
&time_saver_func, "time saver", CONFIG_DEFAULT_TASK_STACK, NULL, 1,
NULL);
// Create and start timer
esp_timer_handle_t update_timer;
const esp_timer_create_args_t update_timer_config = {
.callback = &run_callbacks,
.arg = NULL,
.name = "time updates",
};
error = esp_timer_create(&update_timer_config, &update_timer);
if (error != ESP_OK) {
ESP_LOGE(TAG, "Error creating update timer: %04x", error);
FATAL();
}
error = esp_timer_start_periodic(update_timer, UPDATE_PERIOD_US);
if (error != ESP_OK) {
ESP_LOGE(TAG, "Error starting update timer: %04x", error);
FATAL();
}
}
void add_time_callback(TimeCallback callback)
{
if (callback_count >= MAX_CALLBACKS) {
ESP_LOGE(TAG, "Max number of time callbacks exceeded");
return;
}
callbacks[callback_count] = callback;
++callback_count;
}
Time get_time(void)