time_sync.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @Author: 李建
  3. * @Date: 2025/3/24 10:09
  4. * Description: 时钟同步任务
  5. * Copyright: Copyright (©) 2025 永续绿建. All rights reserved.
  6. */
  7. #include <freertos/FreeRTOS.h>
  8. #include <esp_log.h>
  9. #include <esp_netif_sntp.h>
  10. #include <time.h>
  11. #include <freertos/task.h>
  12. #include "time_sync.h"
  13. #include "lvgl_port.h"
  14. #include "main.h"
  15. static const char *TAG = "time_sync";
  16. // SNTP同步时间函数
  17. void initialize_sntp(void)
  18. {
  19. ESP_LOGI(TAG, "Initializing SNTP");
  20. esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
  21. config.servers[1] = "ntp1.aliyun.com";
  22. config.servers[2] = "ntp.ntsc.ac.cn";
  23. esp_netif_sntp_init(&config);
  24. // 将时区设置为中国标准时间
  25. setenv("TZ", "CST-8", 1);
  26. tzset();
  27. if (esp_netif_sntp_sync_wait(pdMS_TO_TICKS(60000)) != ESP_OK) {
  28. printf("Failed to update system time within 60s timeout");
  29. }
  30. }
  31. static void timer_Task(void *pvParameter)
  32. {
  33. time_t now;
  34. struct tm timeinfo;
  35. char strftime_buf[32];
  36. char strfdata_buf[32];
  37. char strfweek_buf[12];
  38. char weekday[][4] = {"日", "一", "二", "三", "四", "五", "六"};
  39. initialize_sntp();
  40. while(1)
  41. {
  42. time(&now);
  43. localtime_r(&now, &timeinfo);
  44. // strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
  45. // 如果时间已同步(年份大于 2020)
  46. if (timeinfo.tm_year > (2020 - 1900)) {
  47. // snprintf(strfdata_buf, sizeof(strfdata_buf), "%d/%02d/%02d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday);
  48. // sniprintf(strftime_buf, sizeof(strftime_buf), "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
  49. // sniprintf(strfweek_buf, sizeof(strfweek_buf), "星期%s", weekday[timeinfo.tm_wday]);
  50. // lvgl_port_lock(-1);
  51. // lv_label_set_text_static(guider_ui.screen_lab_time, strftime_buf);
  52. // lv_label_set_text_static(guider_ui.screen_lab_date, strfdata_buf);
  53. // lv_label_set_text_static(guider_ui.screen_lab_week, strfweek_buf);
  54. // lvgl_port_unlock();
  55. } else {
  56. ESP_LOGI(TAG, "Waiting for time synchronization...");
  57. }
  58. vTaskDelay(pdMS_TO_TICKS(1000));
  59. }
  60. vTaskDelete(NULL); // 在任务内部删除自身
  61. }
  62. void time_sync_start(void)
  63. {
  64. xTaskCreate(timer_Task, "timer_Task", 1024 * 2,NULL, 5, NULL);
  65. }