12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- /**
- * @Author: 李建
- * @Date: 2025/3/24 10:09
- * Description: 时钟同步任务
- * Copyright: Copyright (©) 2025 永续绿建. All rights reserved.
- */
- #include <freertos/FreeRTOS.h>
- #include <esp_log.h>
- #include <esp_netif_sntp.h>
- #include <time.h>
- #include <freertos/task.h>
- #include "time_sync.h"
- #include "lvgl_port.h"
- #include "main.h"
- static const char *TAG = "time_sync";
- // SNTP同步时间函数
- void initialize_sntp(void)
- {
- ESP_LOGI(TAG, "Initializing SNTP");
- esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
- config.servers[1] = "ntp1.aliyun.com";
- config.servers[2] = "ntp.ntsc.ac.cn";
- esp_netif_sntp_init(&config);
- // 将时区设置为中国标准时间
- setenv("TZ", "CST-8", 1);
- tzset();
- if (esp_netif_sntp_sync_wait(pdMS_TO_TICKS(60000)) != ESP_OK) {
- printf("Failed to update system time within 60s timeout");
- }
- }
- static void timer_Task(void *pvParameter)
- {
- time_t now;
- struct tm timeinfo;
- char strftime_buf[32];
- char strfdata_buf[32];
- char strfweek_buf[12];
- char weekday[][4] = {"日", "一", "二", "三", "四", "五", "六"};
- initialize_sntp();
- while(1)
- {
- time(&now);
- localtime_r(&now, &timeinfo);
- // strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
- // 如果时间已同步(年份大于 2020)
- if (timeinfo.tm_year > (2020 - 1900)) {
- // snprintf(strfdata_buf, sizeof(strfdata_buf), "%d/%02d/%02d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday);
- // sniprintf(strftime_buf, sizeof(strftime_buf), "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
- // sniprintf(strfweek_buf, sizeof(strfweek_buf), "星期%s", weekday[timeinfo.tm_wday]);
- // lvgl_port_lock(-1);
- // lv_label_set_text_static(guider_ui.screen_lab_time, strftime_buf);
- // lv_label_set_text_static(guider_ui.screen_lab_date, strfdata_buf);
- // lv_label_set_text_static(guider_ui.screen_lab_week, strfweek_buf);
- // lvgl_port_unlock();
- } else {
- ESP_LOGI(TAG, "Waiting for time synchronization...");
- }
- vTaskDelay(pdMS_TO_TICKS(1000));
- }
- vTaskDelete(NULL); // 在任务内部删除自身
- }
- void time_sync_start(void)
- {
- xTaskCreate(timer_Task, "timer_Task", 1024 * 2,NULL, 5, NULL);
- }
|