一、SNTP简介

简单网络时间协议(Simple Network Time Protocol),由 NTP 改编而来,主要用来同步因特网中的计算机时钟。

SNTP 协议是用来同步本地的时间到 unix 时间戳。通常嵌入式设备上电,连接 AP(access point),获取 IP 地址后,就需要使用 SNTP 协议获取全球时间。以便于下一步的应用交互和使用。
SNTP 工作原理比较简单, 通俗来说,就是设备向 SNTP server 发送一包 SNTP 请求,服务器收到请求后回复一包 SNTP reply。其中 SNTP reply 中就含有 unix 时间戳。

ESP-IDF 编程指南——SNTP 时间同步

二、API说明

以下 SNTP 接口位于 lwip/include/apps/esp_sntp.h

2.1 sntp_setoperatingmode

2.2 sntp_setservername

2.3 sntp_set_time_sync_notification_cb

2.4 sntp_init

2.5 sntp_get_sync_status

三、示例代码

根据 examples\protocols\sntp 中的例程修改

在 menuconfig 中配置 SSID 和密码

核心部分:

//设置单播模式
sntp_setoperatingmode(SNTP_OPMODE_POLL);
//设置访问服务器
sntp_setservername(0, "pool.ntp.org");
//初始化SNTP模块
sntp_init();

完整代码:

/* LwIP SNTP exampleThis example code is in the Public Domain (or CC0 licensed, at your option.)Unless required by applicable law or agreed to in writing, thissoftware is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "nvs_flash.h"
#include "protocol_examples_common.h"
#include "esp_sntp.h"static const char *TAG = "example";static void obtain_time(void);
static void initialize_sntp(void);void time_sync_notification_cb(struct timeval *tv)
{ESP_LOGI(TAG, "Notification of a time synchronization event");
}void app_main(void)
{time_t now;struct tm timeinfo;time(&now);localtime_r(&now, &timeinfo);// Is time set? If not, tm_year will be (1970 - 1900).if (timeinfo.tm_year < (2021 - 1900)) {ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");obtain_time();// update 'now' variable with current timetime(&now);}char strftime_buf[64];while (1){// update 'now' variable with current timetime(&now);// Set timezone to China Standard Timesetenv("TZ", "CST-8", 1);tzset();localtime_r(&now, &timeinfo);strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);vTaskDelay(10000 / portTICK_PERIOD_MS);}
}static void obtain_time(void)
{ESP_ERROR_CHECK( nvs_flash_init() );ESP_ERROR_CHECK(esp_netif_init());ESP_ERROR_CHECK( esp_event_loop_create_default() );/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.* Read "Establishing Wi-Fi or Ethernet Connection" section in* examples/protocols/README.md for more information about this function.*/ESP_ERROR_CHECK(example_connect());initialize_sntp();// wait for time to be settime_t now = 0;struct tm timeinfo = { 0 };int retry = 0;const int retry_count = 10;while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);vTaskDelay(2000 / portTICK_PERIOD_MS);}time(&now);localtime_r(&now, &timeinfo);ESP_ERROR_CHECK( example_disconnect() );
}static void initialize_sntp(void)
{ESP_LOGI(TAG, "Initializing SNTP");sntp_setoperatingmode(SNTP_OPMODE_POLL);sntp_setservername(0, "pool.ntp.org");sntp_set_time_sync_notification_cb(time_sync_notification_cb);sntp_init();
}

查看打印:

四、注意事项

  1. sntp_setservername 除了可以设置域名, 也可以设置 IP 地址, 例如 sntp_setservername(0, "120.25.115.20");
  2. 如果有必要, 请多设置几个 SNTP server,防止某个 SNTP server 暂时关闭服务而导致产品部分功能无法使用, 例如:
sntp_setservername(0, "ntp1.aliyun.com");
sntp_setservername(1, "210.72.145.44");       // 国家授时中心服务器 IP 地址
sntp_setservername(2, "1.cn.pool.ntp.org");

说明:
默认情况下, ESP8266/ESP32 只允许开启一个 SNTP server(节省资源考虑), 如果用户需开启多个 SNTP server, 请配置:

  • ESP8266 请在 make menuconfig -> Component config -> LWIP -> DHCP -> Maximum bumber of NTP servers 修改为 3
  • ESP32 请在 make menuconfig -> Component config -> LWIP -> SNTP -> Maximum bumber of NTP servers 修改为 3

配置多个 SNTP server 时, 不是同时发送多个 SNTP 请求报文, 而是轮循方式. 第一个处理超时后, 进行和第二个 SNTP server 交互, 这样依次进行到最后一个, 最后一个处理超时后, 会再和第一个 SNTP server 交互

  1. 更新时间请求间隔SNTP_UPDATE_DELAY,到下一次发起更新时间请求的间隔时间,单位是ms,最小不能小于15s,也是通过make menuconfig修改CONFIG_LWIP_SNTP_UPDATE_DELAY
    在 make menuconfig -> Component config -> LWIP -> SNTP -> Request interval to update time (ms).

  2. 最好不在任何 callback 或中断处理函数中调用 obtain_time(), callback/中断中, 调用任何阻塞的 API, 理论上都有死锁的可能.

  3. 任何有校验服务器证书的 TLS 过程 (本地有 CA 证书), 请务必开启 SNTP 功能, 否则会因为校验服务器证书有效期失败而导致 TLS 握手失败

  4. NTP.ORG.cn中国NTP授时快速域名服务提供商

新加坡 sgp.ntp.org.cn 韩国 kr.ntp.org.cn
中国 cn.ntp.org.cn 中国教育网 edu.ntp.org.cn
中国香港 hk.ntp.org.cn 中国台湾 tw.ntp.org.cn
美国 us.ntp.org.cn 韩国 kr.ntp.org.cn
日本 jp.ntp.org.cn 德国 de.ntp.org.cn
印度尼西亚 ina.ntp.org.cn
  1. 时区:
  • CST-8:这时区的表示有点混
    CST却同时可以代表如下 4 个不同的时区:
    Central Standard Time (USA) UT-6:00
    Central Standard Time (Australia) UT+9:30
    China Standard Time UT+8:00
    Cuba Standard Time UT-4:00
setenv("TZ", "CST-8", 1);
  • GMT:(Greenwich Mean Time)是格林尼治平时
    GMT+8正好是中国的标准时区
setenv("TZ", "GMT+8", 1);
  1. 在成功获取了网络时间后,必须调用 sntp_stop(); 停止NTP请求,不然设备重启后会造成获取网络时间失败的现象,大概是服务器时根据心跳时间来删除客户端的,如果不是stop结束的客户端,下次连接服务器时就会出错

• 由 Leung 写于 2021 年 7 月 30 日

• 参考:ESP8266/ESP32 基础篇: 时间同步 SNTP 介绍和使用
    ESP32 SNTP配置
    ESP32的SDK开发之获取SNTP网络时间

ESP32学习笔记(41)——SNTP接口使用相关推荐

  1. ESP32学习笔记(20)——SPI(从机)接口使用

    一.SPI简介 SPI(Serial Peripheral Interface) 协议是由摩托罗拉公司提出的通讯协议,即串行外围设备接口,是一种高速全双工的通信总线.它被广泛地使用在 ADC.LCD ...

  2. ESP32学习笔记(19)——SPI(主机)接口使用

    一.SPI简介 SPI(Serial Peripheral Interface) 协议是由摩托罗拉公司提出的通讯协议,即串行外围设备接口,是一种高速全双工的通信总线.它被广泛地使用在 ADC.LCD ...

  3. ESP32学习笔记(7)——SmartConfig接口使用(ESP-Touch和AirKiss)

    一.概述 SmartConfig是TI开发的一种配置技术,用于将新的Wi-Fi设备连接到Wi-Fi网络.它使用移动应用程序将网络凭据从智能手机或平板电脑广播到未配置的Wi-Fi设备. 该技术的优点是设 ...

  4. ESP32学习笔记(27)——BLE GAP主机端扫描

    一.背景 1.1 低功耗蓝牙(BLE)协议栈 链路层(LL) 控制设备的射频状态,有五个设备状态:待机.广播.扫描.初始化和连接. 广播 为广播数据包,而 扫描 则是监听广播. GAP通信中角色,中心 ...

  5. ESP32学习笔记(49)——RFID RC522使用

    一.简介 MF RC522 是应用于 13.56MHz 非接触式通信中高集成度读写卡系列芯片中的一员.是 NXP 公司针对"三表"应用推出的一款低电压.低成本.体积小的非接触式读写 ...

  6. ESP32学习笔记(一) 芯片型号介绍

    ESP32学习笔记(一) 芯片型号介绍 目录: ESP32学习笔记(一) 芯片型号介绍 ESP32学习笔记(二) 开发环境搭建 VSCode+platformio ESP32学习笔记(三) 硬件资源介 ...

  7. ESP32学习笔记(30)——BLE GATT服务端自定义服务和特征

    一.简介 1.1 低功耗蓝牙(BLE)协议栈 链路层(LL) 控制设备的射频状态,有五个设备状态:待机.广播.扫描.初始化和连接. 广播 为广播数据包,而 扫描 则是监听广播. GAP通信中角色,中心 ...

  8. [ESP32]学习笔记03

    今天我们使用ESP32自带的LEDC外设制作一个LED呼吸灯 目录 前言 一.呼吸灯是什么 二.首先我们在Blink实例的基础上建立工程 1.引入库添加宏定义 2.修改主函数 最后我们看一下呼吸灯的效 ...

  9. ESP32学习笔记(14)——HTTP服务器

    一.HTTP简介 HTTP(Hyper Text Transfer Protocol) 超文本传输协议,是一种建立在 TCP 上的无状态连接,整个基本的工作流程是客户端发送一个 HTTP 请求,说明客 ...

  10. 关于esp32蓝牙模块的使用——esp32学习笔记

    关于esp32蓝牙模块的使用--esp32学习笔记 关于esp32蓝牙模块的使用--esp32学习笔记 关于esp32蓝牙模块的使用--esp32学习笔记 零.前言 一.经典蓝牙BT 二.低功耗蓝牙B ...

最新文章

  1. SpringMVC源码解析
  2. 灾难恢复演练成功的8大步骤
  3. 【HDU 2507】【ACM-ICPC算法基础训练教程 题1-6】迷瘴(贪心)
  4. 前端学习(3120):react-hello-react的setstate的一个说明
  5. 基础01类与对象、封装、构造方法
  6. vs各个版本的编译器号
  7. 2020 IJCAI 接受论文 list 分类排列(一)
  8. u盘无法格式化不在计算机中,在电脑中,为什么U盘不能格式化?
  9. Java获取IP归属地
  10. 疫情中计算机方面的直播课,线上课程,前沿讲座,主要是人工智能方面,计算机视觉,爬虫等
  11. 苹果前置摄像头拍出来是反的怎么调_苹果前置摄像头拍照是反的怎么办
  12. Android11 亮度自动调节
  13. 研究生可以不用学英语?只要考研英语或六级分数高!
  14. iOS中百度地图API的总结
  15. iOS常用的第三方库
  16. 沈博研:企业家迷恋黄金投资的七大原因
  17. python3函数参数(必选参数、默认参数、关键字参数、可变参数)
  18. adb: error: failed to copy ‘xx‘ to ‘xx‘: remote couldn‘t create file: Permission denied
  19. 实战|智能家居行业移动应用性能分析
  20. 怎么手工解决DRA中的failure?

热门文章

  1. 软件测试工程师的前景!
  2. 「镁客·请讲」图鸭科技武俊敏:打造从压缩、通信到分析的完整视频解决方案...
  3. html优化字体包,web性能优化之字体优化
  4. python浮点型和整数型转换_Python字符串、整数、和浮点型数相互转换实例
  5. 机器人学习的坚持与收获-2023
  6. 小程序flex:1_Flex 2:瞬间丰富的Internet应用程序!
  7. iPad上的城市瞭望台
  8. 制作自己的数据库接口
  9. 星志远电商:2022拼多多如何获得流量?
  10. 经得起考验的CocoaPods安装教程