8.6. NTP

8.6.1. 概述

ntp网络时间协议用法


8.6.2. 配置说明

  • 用户可以在文件 include_lib/net/lwip_2_1_3/lwip/app/ntp/ntp.h 添加自己的ntp服务器:

//此处添加ntp服务器,请自行测试ntp服务器是否正常
 static const char *ntp_host[] = {
       "s2a.time.edu.cn",
       "s2b.time.edu.cn",
       "s2c.time.edu.cn",
       // "s2d.time.edu.cn",
       // "s2e.time.edu.cn",
       // "s2f.time.edu.cn",
       // "s2g.time.edu.cn",
       // "s2h.time.edu.cn",
       // "s2j.time.edu.cn",
       // "s2k.time.edu.cn",
       // "s2m.time.edu.cn",
};
  • 打印控制,用户可以打开关闭DEBUG,ERR打印信息

#define NTP_DBUG_INFO_ON 0               /*!< NTP client debug information on/off */
#define NTP_ERR_INFO_ON  1               /*!< NTP client error information on/off */
  • 用户可以在文件 apps/common/net/wifi_conf.c 中配置是否开机调用ntp

const u8 ntp_get_time_init = 1;  //连上网后调用ntp向ntp_host列表所有服务器获取时间, 0为关闭, 1为开启

8.6.3. API Reference

This file provides the api of ntp client.

Copyright(c) 2017, ZhuHai JieLi Technology Co.Ltd. All rights reserved.

Author

Version

Attention

Defines

NTP_HOST_NUM
NTP_DBUG_INFO_ON

NTP client debug information on/off

NTP_ERR_INFO_ON

NTP client error information on/off

Functions

int ntp_client_get_time_once(const char *host, struct tm *s_tm, int recv_to)

Get time from ntp server

Parameters
  • host – NTP server host name

  • s_tm – Save time information

  • recv_to – The value of socket receive timeout(ms)

Returns

0: sucess

Returns

-1: fail

int ntp_client_get_time_all(struct tm *s_tm, int recv_to)

Get time from all ntp_host list server

Parameters
  • s_tm – Save time information

  • recv_to – The value of socket receive timeout(ms)

Returns

0: sucess

Returns

-1: fail

u8 ntp_client_get_time_status(void)

Get the status of the time from ntp server

Note

Returns

1: sucess

Returns

0: fail or still getting

void ntp_client_get_time(const char *host)

Get time from ntp server,and save to the rtc,if it has.

Note

This api is a loop, is will exit when getting time successful or calling ntp_client_get_time_exit function.

Note

When it succeed, it will post the net_event NET_NTP_GET_TIME_SUCC and set the ntp_client_time_status to 1.

Parameters

host – NTP server host name, if NULL, it will visit all the ntp_host list.

void ntp_client_get_time_exit(void)

Exit the ntp_client_get_time function.

void ntp_client_get_time_clear(void)

clear the status of the time from ntp server

Variables

static const char *ntp_host[] = {"s2a.time.edu.cn", "s2b.time.edu.cn", "s2c.time.edu.cn",}

8.6.4. 示例实例

示例代码见 apps/common/example/network_protocols/ntp/main.c, 测试时需要在 apps/demo/demo_DevKitBoard/include/demo_config.h ,开启宏 USE_NTP_TEST

操作说明

  • 编译工程,烧录镜像,复位启动

  • 系统启动并成功联网后,开始向ntp服务器发起请求。

示例流程如下:

  • c_main() 入口
    1. 创建任务 ntp_test

  • ntp_test 函数流程
    1. 通过 wifi_get_sta_connect_state 函数检测是否通过dhcp成功获取到ip

    2. 成功通过dhcp获取到ip后,线程调用 ntp_test2 创建获取所有NTP服务器函数

    3. 模仿弱网情况, 主动退出NTP请求

    4. 获取一次请求状态

    5. 清除请求状态

    6. 请求获取指定NTP服务器

    7. 再次获取状态