本文以C Link SDK中的Demo文件./demos/ntp_posix_demo.c为例,介绍如何调用Link SDK的API,使设备从物联网平台获取UTC时间。
背景信息
步骤一:初始化
步骤二:配置功能
调用aiot_ntp_setopt,配置以下功能。
步骤三:发送请求
调用aiot_ntp_send_request,根据上一步配置的参数,通过Topic /ext/ntp/${YourProductKey}/${YourDeviceName}/request
,向服务器发送一条包含设备当前时间的请求消息。
Link SDK通过系统接口,自动上报设备当前时间。
res = aiot_ntp_send_request(ntp_handle);
if (res < STATE_SUCCESS) {
aiot_ntp_deinit(&ntp_handle);
demo_mqtt_stop(&mqtt_handle);
return -1;
}
步骤四:接收应答
设备接收NTP服务消息后,触发回调函数demo_ntp_recv_handler
,根据回调函数的设置,执行对应处理。
-
物联网平台通过Topic
/ext/ntp/${YourProductKey}/${YourDeviceName}/response
向设备发回一条包含时间内容的消息。 - 时间消息的数据结构类型为aiot_ntp_recv_t,可参考示例代码获取时间。
-
本文示例代码对返回的消息解析处理后,通过packet传递,打印该时间消息。
void demo_ntp_recv_handler(void *handle, const aiot_ntp_recv_t *packet, void *userdata)
{
switch (packet->type) {
/* TODO: 含当前时区下, 年月日时分秒的数值, 可在这里把它们解析储存起来 */
case AIOT_NTPRECV_LOCAL_TIME: {
printf("local time: %llu, %02d/%02d/%02d-%02d:%02d:%02d:%d\n",
(long long unsigned int)packet->data.local_time.timestamp,
packet->data.local_time.year,
packet->data.local_time.mon, packet->data.local_time.day, packet->data.local_time.hour, packet->data.local_time.min,
packet->data.local_time.sec, packet->data.local_time.msec);
}
break;
default: {
}
}
}
步骤五:退出程序
调用aiot_ntp_deinit,销毁NTP客户端实例,释放资源。
res = aiot_ntp_deinit(&ntp_handle);
if (res < STATE_SUCCESS) {
demo_mqtt_stop(&mqtt_handle);
printf("aiot_ntp_deinit failed: -0x%04X\n", -res);
return -1;
}