【ESP-IDF】使用SNTP进行时间同步

/**
 * @description: sntp初始化
 * @return {*}
 * @note: 参考官方博客
 */
static void esp_initialize_sntp(void)
{
    
    
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "ntp1.aliyun.com");
    sntp_setservername(1, "210.72.145.44");		// 国家授时中心服务器 IP 地址
    sntp_setservername(2, "1.cn.pool.ntp.org");        

    sntp_init();
}

/**
 * @description: 获取时间函数,应用层直接调用即可
 * @return {*}
 * @note: 参考官方博客
 */
static void esp_wait_sntp_sync(void)
{
    
    
    char strftime_buf[64];
    esp_initialize_sntp();

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = {
    
     0 };
    int retry = 0;

    while (timeinfo.tm_year < (2019 - 1900))
    {
    
    
        ESP_LOGD(TAG, "Waiting for system time to be set... (%d)", ++retry);
        vTaskDelay(100 / portTICK_PERIOD_MS);   // 延迟100ms
        time(&now);                             // 获得unix时间戳
        localtime_r(&now, &timeinfo);           // 将unix时间戳转换成struct tm格式
    }

    // set timezone to China Standard Time 设置东八区
    setenv("TZ", "CST-8", 1);
    tzset();

    strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);   // 修改时间格式
    ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
}

/**
 * @description: 获得实时时间
 * @return {*}
 * @note: 
 */
static void display_time(void)
{
    
    
    char strftime_buf[64];
    struct tm timeinfo;
    time_t now = 0;

    // Set timezone to China Standard Time
    setenv("TZ", "CST-8", 1);
    tzset();

    while (1)
    {
    
    
        time(&now);

        localtime_r(&now, &timeinfo);
        strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
        ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
        
        vTaskDelay(300 / portTICK_RATE_MS);
    }
}

官方文档_System Time
官方博客_SNTP时间同步
SNTP官方例程

猜你喜欢

转载自blog.csdn.net/ManiacLook/article/details/131505188
今日推荐