IoT25S IoT Klocka 0.1
Grupparbete för IoT25S på Jensen YH
Loading...
Searching...
No Matches
time_service.c
Go to the documentation of this file.
1#include "time_service.h"
2
3#include <stdbool.h>
4#include <stdlib.h>
5#include <string.h>
6#include <sys/time.h>
7#include <time.h>
8
9#include "freertos/FreeRTOS.h"
10#include "freertos/semphr.h"
11#include "freertos/task.h"
12
13#include "esp_check.h"
14#include "esp_log.h"
15#include "esp_sntp.h"
16
17#include "sdkconfig.h"
18
19#include "app_state.h"
20
21#ifndef CONFIG_TIME_SERVICE_SNTP_ENABLE
22#define CONFIG_TIME_SERVICE_SNTP_ENABLE 1
23#endif
24
25#ifndef CONFIG_TIME_SERVICE_SNTP_SERVER
26#define CONFIG_TIME_SERVICE_SNTP_SERVER "pool.ntp.org"
27#endif
28
29#ifndef CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS
30#define CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS 15000
31#endif
32
33#ifndef CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS
34#define CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS 3
35#endif
36
37#ifndef CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS
38#define CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS 5000
39#endif
40
41static const char *TAG = "time_service";
42
43static SemaphoreHandle_t s_time_lock;
44static bool s_time_valid;
48
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}
58
59static esp_err_t time_service_set_system_epoch(int64_t epoch)
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}
68
69static esp_err_t time_service_try_sntp_init(void)
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}
87
88static void time_service_sntp_sync_task(void *arg)
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}
158
159/* ---------------------------------------------------------------------------
160 * POSIX TZ string lookup table.
161 * Strings encode full DST rules; for zones without DST the string is a
162 * simple fixed-offset form e.g. "<+04>-4".
163 * ---------------------------------------------------------------------------*/
164typedef struct {
165 const char *location_id;
166 const char *posix_tz;
168
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};
185
186static const size_t s_tz_table_count = sizeof(s_tz_table) / sizeof(s_tz_table[0]);
187
188/* Generate a POSIX fixed-offset TZ string from minutes east of UTC. */
189static void time_service_posix_from_offset(int16_t offset_min, char *buf, size_t buf_len)
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}
206
207void time_service_apply_timezone(const char *location_id, int16_t fallback_offset_min)
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}
233
234esp_err_t time_service_init(void)
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}
269
270esp_err_t time_service_set_epoch(int64_t epoch)
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}
282
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}
314
315bool time_service_get_local_time(struct tm *out_tm, int64_t *out_epoch)
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}
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
esp_err_t app_state_set_time_epoch(int64_t epoch, bool valid)
Update stored epoch and validity flag.
Definition app_state.c:242
Thread-safe application state and persisted configuration APIs.
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
const char * location_id
const char * posix_tz
static void time_service_sntp_sync_task(void *arg)
void time_service_apply_timezone(const char *location_id, int16_t fallback_offset_min)
Apply a timezone by IANA location ID with DST support.
#define CONFIG_TIME_SERVICE_SNTP_SYNC_TIMEOUT_MS
static SemaphoreHandle_t s_time_lock
esp_err_t time_service_init(void)
Initialize time service state and restore persisted time fallback.
static const size_t s_tz_table_count
#define CONFIG_TIME_SERVICE_SNTP_SERVER
static esp_err_t time_service_try_sntp_init(void)
static const char * TAG
esp_err_t time_service_set_epoch(int64_t epoch)
Set current UTC epoch and persist it as valid time.
#define CONFIG_TIME_SERVICE_SNTP_MAX_SYNC_ATTEMPTS
static bool s_network_connected
static esp_err_t time_service_store_epoch_from_system(void)
static bool s_sntp_initialized
static const time_service_tz_entry_t s_tz_table[]
void time_service_notify_network_connected(bool connected)
Notify the service about network connectivity changes.
static bool s_sntp_sync_task_running
bool time_service_get_local_time(struct tm *out_tm, int64_t *out_epoch)
Get local time adjusted by the configured timezone offset.
static bool s_time_valid
static void time_service_posix_from_offset(int16_t offset_min, char *buf, size_t buf_len)
#define CONFIG_TIME_SERVICE_SNTP_RETRY_DELAY_MS
static esp_err_t time_service_set_system_epoch(int64_t epoch)
Time service APIs for local time access and synchronization triggers.