IoT25S IoT Klocka 0.1
Grupparbete för IoT25S på Jensen YH
Loading...
Searching...
No Matches
time_service.c File Reference
#include "time_service.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "esp_check.h"
#include "esp_log.h"
#include "esp_sntp.h"
#include "sdkconfig.h"
#include "app_state.h"
+ Include dependency graph for time_service.c:

Go to the source code of this file.

Data Structures

struct  time_service_tz_entry_t
 

Macros

#define CONFIG_TIME_SERVICE_SNTP_ENABLE   1
 
#define CONFIG_TIME_SERVICE_SNTP_SERVER   "pool.ntp.org"
 
#define CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS   15000
 
#define CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS   3
 
#define CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS   5000
 

Functions

static esp_err_t time_service_store_epoch_from_system (void)
 
static esp_err_t time_service_set_system_epoch (int64_t epoch)
 
static esp_err_t time_service_try_sntp_init (void)
 
static void time_service_sntp_sync_task (void *arg)
 
static void time_service_posix_from_offset (int16_t offset_min, char *buf, size_t buf_len)
 
void time_service_apply_timezone (const char *location_id, int16_t fallback_offset_min)
 Apply a timezone by IANA location ID with DST support.
 
esp_err_t time_service_init (void)
 Initialize time service state and restore persisted time fallback.
 
esp_err_t time_service_set_epoch (int64_t epoch)
 Set current UTC epoch and persist it as valid time.
 
void time_service_notify_network_connected (bool connected)
 Notify the service about network connectivity changes.
 
bool time_service_get_local_time (struct tm *out_tm, int64_t *out_epoch)
 Get local time adjusted by the configured timezone offset.
 

Variables

static const char * TAG = "time_service"
 
static SemaphoreHandle_t s_time_lock
 
static bool s_time_valid
 
static bool s_network_connected
 
static bool s_sntp_initialized
 
static bool s_sntp_sync_task_running
 
static const time_service_tz_entry_t s_tz_table []
 
static const size_t s_tz_table_count = sizeof(s_tz_table) / sizeof(s_tz_table[0])
 

Macro Definition Documentation

◆ CONFIG_TIME_SERVICE_SNTP_ENABLE

#define CONFIG_TIME_SERVICE_SNTP_ENABLE   1

Definition at line 22 of file time_service.c.

◆ CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS

#define CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS   3

Definition at line 34 of file time_service.c.

◆ CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS

#define CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS   5000

Definition at line 38 of file time_service.c.

◆ CONFIG_TIME_SERVICE_SNTP_SERVER

#define CONFIG_TIME_SERVICE_SNTP_SERVER   "pool.ntp.org"

Definition at line 26 of file time_service.c.

◆ CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS

#define CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS   15000

Definition at line 30 of file time_service.c.

Function Documentation

◆ time_service_apply_timezone()

void time_service_apply_timezone ( const char *  location_id,
int16_t  fallback_offset_min 
)

Apply a timezone by IANA location ID with DST support.

Looks up a POSIX TZ string for the given IANA location ID and calls setenv("TZ", ...) + tzset() to activate it. For the "custom" ID or any unknown ID, generates a fixed-offset POSIX string from fallback_offset_min (no DST is applied in that case).

Must be called after any timezone configuration change and once during init.

Parameters
location_idIANA timezone location string, or "custom".
fallback_offset_minUTC offset in minutes east of UTC (used only for custom/unknown IDs).

Definition at line 207 of file time_service.c.

208{
209 const char *posix_str = NULL;
210 char generated[32];
211 size_t i;
212
213 if (location_id != NULL) {
214 for (i = 0; i < s_tz_table_count; ++i) {
215 if (strcmp(location_id, s_tz_table[i].location_id) == 0) {
216 posix_str = s_tz_table[i].posix_tz;
217 break;
218 }
219 }
220 }
221
222 if (posix_str == NULL) {
223 time_service_posix_from_offset(fallback_offset_min, generated, sizeof(generated));
224 posix_str = generated;
225 }
226
227 setenv("TZ", posix_str, 1);
228 tzset();
229
230 ESP_LOGI(TAG, "Timezone: location=\"%s\" posix=\"%s\"",
231 location_id ? location_id : "custom", posix_str);
232}
const char * posix_tz
static const size_t s_tz_table_count
static const char * TAG
static const time_service_tz_entry_t s_tz_table[]
static void time_service_posix_from_offset(int16_t offset_min, char *buf, size_t buf_len)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_get_local_time()

bool time_service_get_local_time ( struct tm *  out_tm,
int64_t *  out_epoch 
)

Get local time adjusted by the configured timezone offset.

Offset may be set directly or derived from a selected timezone location.

Parameters
[out]out_tmOptional pointer to receive broken-down local time.
[out]out_epochOptional pointer to receive local epoch seconds.
Returns
true if valid time is available, false otherwise.

Definition at line 315 of file time_service.c.

316{
317 bool persist_valid_epoch = false;
318 time_t utc_time = time(NULL);
319 struct tm local_tm;
320
321 if (utc_time <= 0) {
322 return false;
323 }
324
325 xSemaphoreTake(s_time_lock, portMAX_DELAY);
326 if (!s_time_valid) {
327 s_time_valid = true;
328 persist_valid_epoch = true;
329 }
330 xSemaphoreGive(s_time_lock);
331
332 if (persist_valid_epoch) {
333 app_state_set_time_epoch((int64_t)utc_time, true);
334 }
335
336 /* localtime_r respects the TZ env var set by time_service_apply_timezone(),
337 * giving correct DST-aware broken-down time. */
338 memset(&local_tm, 0, sizeof(local_tm));
339 localtime_r(&utc_time, &local_tm);
340
341 if (out_tm != NULL) {
342 *out_tm = local_tm;
343 }
344
345 if (out_epoch != NULL) {
346 /* Return UTC epoch. Callers that need display-local time use out_tm. */
347 *out_epoch = (int64_t)utc_time;
348 }
349
350 return true;
351}
esp_err_t app_state_set_time_epoch(int64_t epoch, bool valid)
Update stored epoch and validity flag.
Definition app_state.c:242
static SemaphoreHandle_t s_time_lock
static bool s_time_valid
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_init()

esp_err_t time_service_init ( void  )

Initialize time service state and restore persisted time fallback.

Returns
ESP_OK on success, otherwise an ESP_ERR_* code.

Definition at line 234 of file time_service.c.

235{
236 int64_t saved_epoch = 0;
237 bool saved_valid = false;
238
239 if (s_time_lock == NULL) {
240 s_time_lock = xSemaphoreCreateMutex();
241 if (s_time_lock == NULL) {
242 return ESP_ERR_NO_MEM;
243 }
244 }
245
246 app_state_get_time_epoch(&saved_epoch, &saved_valid);
247
248 xSemaphoreTake(s_time_lock, portMAX_DELAY);
249 s_network_connected = false;
250 s_sntp_initialized = false;
252 s_time_valid = saved_valid && (saved_epoch > 0);
253 xSemaphoreGive(s_time_lock);
254
255 if (s_time_valid) {
256 ESP_RETURN_ON_ERROR(time_service_set_system_epoch(saved_epoch), TAG,
257 "restore saved epoch failed");
258 }
259
260 /* Apply persisted timezone so localtime_r() is DST-aware from boot. */
261 {
262 app_config_t cfg;
265 }
266
267 return ESP_OK;
268}
void app_state_get_time_epoch(int64_t *epoch, bool *valid)
Get stored epoch value and validity flag.
Definition app_state.c:234
void app_state_get_config(app_config_t *config)
Get current persisted configuration.
Definition app_state.c:214
Persisted configuration model.
Definition app_state.h:40
char timezone_location[APP_TIMEZONE_LOCATION_MAX_LEN+1]
Definition app_state.h:48
int16_t tz_offset_min
Definition app_state.h:49
void time_service_apply_timezone(const char *location_id, int16_t fallback_offset_min)
Apply a timezone by IANA location ID with DST support.
static bool s_network_connected
static bool s_sntp_initialized
static bool s_sntp_sync_task_running
static esp_err_t time_service_set_system_epoch(int64_t epoch)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_notify_network_connected()

void time_service_notify_network_connected ( bool  connected)

Notify the service about network connectivity changes.

Used to trigger SNTP synchronization when connectivity is available.

Parameters
connectedtrue if network is connected, false otherwise.

Definition at line 283 of file time_service.c.

284{
285 bool start_sync_task = false;
286
287 xSemaphoreTake(s_time_lock, portMAX_DELAY);
288 s_network_connected = connected;
289
290#if CONFIG_TIME_SERVICE_SNTP_ENABLE
291 if (connected && !s_sntp_sync_task_running) {
293 start_sync_task = true;
294 }
295#endif
296
297 xSemaphoreGive(s_time_lock);
298
299 if (start_sync_task) {
300 BaseType_t task_ok = xTaskCreate(time_service_sntp_sync_task,
301 "time_sntp_sync",
302 4096,
303 NULL,
304 4,
305 NULL);
306 if (task_ok != pdPASS) {
307 xSemaphoreTake(s_time_lock, portMAX_DELAY);
309 xSemaphoreGive(s_time_lock);
310 ESP_LOGE(TAG, "Failed to create SNTP sync task");
311 }
312 }
313}
static void time_service_sntp_sync_task(void *arg)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_posix_from_offset()

static void time_service_posix_from_offset ( int16_t  offset_min,
char *  buf,
size_t  buf_len 
)
static

Definition at line 189 of file time_service.c.

190{
191 int sign = (offset_min >= 0) ? 1 : -1;
192 int abs_min = (offset_min >= 0) ? (int)offset_min : -(int)offset_min;
193 int h = abs_min / 60;
194 int m = abs_min % 60;
195 /* POSIX convention: offset is west of UTC (opposite sign to UTC+N) */
196 int posix_h = -(sign * h);
197
198 if (m == 0) {
199 snprintf(buf, buf_len, "<%s%02d>%d",
200 sign >= 0 ? "+" : "-", h, posix_h);
201 } else {
202 snprintf(buf, buf_len, "<%s%02d%02d>%d:%02d",
203 sign >= 0 ? "+" : "-", h, m, posix_h, m);
204 }
205}
+ Here is the caller graph for this function:

◆ time_service_set_epoch()

esp_err_t time_service_set_epoch ( int64_t  epoch)

Set current UTC epoch and persist it as valid time.

Parameters
epochUTC epoch seconds.
Returns
ESP_OK on success, otherwise an ESP_ERR_* code.

Definition at line 270 of file time_service.c.

271{
272 ESP_RETURN_ON_FALSE(epoch > 0, ESP_ERR_INVALID_ARG, TAG, "epoch must be > 0");
273
274 ESP_RETURN_ON_ERROR(time_service_set_system_epoch(epoch), TAG, "settimeofday failed");
275
276 xSemaphoreTake(s_time_lock, portMAX_DELAY);
277 s_time_valid = true;
278 xSemaphoreGive(s_time_lock);
279
280 return app_state_set_time_epoch(epoch, true);
281}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_set_system_epoch()

static esp_err_t time_service_set_system_epoch ( int64_t  epoch)
static

Definition at line 59 of file time_service.c.

60{
61 struct timeval now = {
62 .tv_sec = (time_t)epoch,
63 .tv_usec = 0,
64 };
65
66 return (settimeofday(&now, NULL) == 0) ? ESP_OK : ESP_FAIL;
67}
+ Here is the caller graph for this function:

◆ time_service_sntp_sync_task()

static void time_service_sntp_sync_task ( void *  arg)
static

Definition at line 88 of file time_service.c.

89{
90 (void)arg;
91
92#if CONFIG_TIME_SERVICE_SNTP_ENABLE
93 const TickType_t retry_delay = pdMS_TO_TICKS(CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS);
94 const TickType_t poll_delay = pdMS_TO_TICKS(1000);
95 bool synchronized = false;
96
97 for (int attempt = 1; attempt <= CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS; ++attempt) {
98 bool connected;
99 int waited_ms = 0;
100
101 xSemaphoreTake(s_time_lock, portMAX_DELAY);
102 connected = s_network_connected;
103 xSemaphoreGive(s_time_lock);
104
105 if (!connected) {
106 ESP_LOGW(TAG, "SNTP sync aborted (network disconnected)");
107 break;
108 }
109
110 if (time_service_try_sntp_init() != ESP_OK) {
111 ESP_LOGW(TAG, "SNTP init failed (attempt %d)", attempt);
113 vTaskDelay(retry_delay);
114 }
115 continue;
116 }
117
118 while (waited_ms < CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS) {
119 if (esp_sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED) {
120 if (time_service_store_epoch_from_system() == ESP_OK) {
121 synchronized = true;
122 xSemaphoreTake(s_time_lock, portMAX_DELAY);
123 s_time_valid = true;
124 xSemaphoreGive(s_time_lock);
125 ESP_LOGI(TAG, "SNTP synchronized using %s", CONFIG_TIME_SERVICE_SNTP_SERVER);
126 }
127 break;
128 }
129
130 vTaskDelay(poll_delay);
131 waited_ms += 1000;
132 }
133
134 if (synchronized) {
135 break;
136 }
137
138 ESP_LOGW(TAG, "SNTP sync timeout (attempt %d/%d)",
139 attempt,
141
143 vTaskDelay(retry_delay);
144 }
145 }
146
147 if (!synchronized) {
148 ESP_LOGW(TAG, "SNTP not synchronized on this network session");
149 }
150#endif
151
152 xSemaphoreTake(s_time_lock, portMAX_DELAY);
154 xSemaphoreGive(s_time_lock);
155
156 vTaskDelete(NULL);
157}
#define CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS
#define CONFIG_TIME_SERVICE_SNTP_SERVER
static esp_err_t time_service_try_sntp_init(void)
#define CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS
static esp_err_t time_service_store_epoch_from_system(void)
#define CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_store_epoch_from_system()

static esp_err_t time_service_store_epoch_from_system ( void  )
static

Definition at line 49 of file time_service.c.

50{
51 time_t now = time(NULL);
52 if (now <= 0) {
53 return ESP_ERR_INVALID_STATE;
54 }
55
56 return app_state_set_time_epoch((int64_t)now, true);
57}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ time_service_try_sntp_init()

static esp_err_t time_service_try_sntp_init ( void  )
static

Definition at line 69 of file time_service.c.

70{
71#if CONFIG_TIME_SERVICE_SNTP_ENABLE
73 return ESP_OK;
74 }
75
76 esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
77 esp_sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED);
78 esp_sntp_setservername(0, CONFIG_TIME_SERVICE_SNTP_SERVER);
79 esp_sntp_init();
80
81 s_sntp_initialized = true;
82 return ESP_OK;
83#else
84 return ESP_ERR_NOT_SUPPORTED;
85#endif
86}
+ Here is the caller graph for this function:

Variable Documentation

◆ s_network_connected

bool s_network_connected
static

Definition at line 45 of file time_service.c.

◆ s_sntp_initialized

bool s_sntp_initialized
static

Definition at line 46 of file time_service.c.

◆ s_sntp_sync_task_running

bool s_sntp_sync_task_running
static

Definition at line 47 of file time_service.c.

◆ s_time_lock

SemaphoreHandle_t s_time_lock
static

Definition at line 43 of file time_service.c.

◆ s_time_valid

bool s_time_valid
static

Definition at line 44 of file time_service.c.

◆ s_tz_table

const time_service_tz_entry_t s_tz_table[]
static
Initial value:
= {
{"Europe/Stockholm", "CET-1CEST,M3.5.0,M10.5.0/3"},
{"Europe/London", "GMT0BST,M3.5.0/1,M10.5.0"},
{"America/New_York", "EST5EDT,M3.2.0,M11.1.0"},
{"America/Chicago", "CST6CDT,M3.2.0,M11.1.0"},
{"America/Denver", "MST7MDT,M3.2.0,M11.1.0"},
{"America/Los_Angeles", "PST8PDT,M3.2.0,M11.1.0"},
{"America/Sao_Paulo", "<-03>3"},
{"Asia/Dubai", "<+04>-4"},
{"Asia/Kolkata", "<+0530>-5:30"},
{"Asia/Bangkok", "<+07>-7"},
{"Asia/Singapore", "<+08>-8"},
{"Asia/Tokyo", "JST-9"},
{"Australia/Sydney", "AEST-10AEDT,M10.1.0,M4.1.0/3"},
{"Pacific/Auckland", "NZST-12NZDT,M9.5.0,M4.1.0/3"},
}

Definition at line 169 of file time_service.c.

169 {
170 {"Europe/Stockholm", "CET-1CEST,M3.5.0,M10.5.0/3"},
171 {"Europe/London", "GMT0BST,M3.5.0/1,M10.5.0"},
172 {"America/New_York", "EST5EDT,M3.2.0,M11.1.0"},
173 {"America/Chicago", "CST6CDT,M3.2.0,M11.1.0"},
174 {"America/Denver", "MST7MDT,M3.2.0,M11.1.0"},
175 {"America/Los_Angeles", "PST8PDT,M3.2.0,M11.1.0"},
176 {"America/Sao_Paulo", "<-03>3"},
177 {"Asia/Dubai", "<+04>-4"},
178 {"Asia/Kolkata", "<+0530>-5:30"},
179 {"Asia/Bangkok", "<+07>-7"},
180 {"Asia/Singapore", "<+08>-8"},
181 {"Asia/Tokyo", "JST-9"},
182 {"Australia/Sydney", "AEST-10AEDT,M10.1.0,M4.1.0/3"},
183 {"Pacific/Auckland", "NZST-12NZDT,M9.5.0,M4.1.0/3"},
184};

◆ s_tz_table_count

const size_t s_tz_table_count = sizeof(s_tz_table) / sizeof(s_tz_table[0])
static

Definition at line 186 of file time_service.c.

◆ TAG

const char* TAG = "time_service"
static

Definition at line 41 of file time_service.c.