alios things ntp获取时间

alios things 中还有另一种获取时间的方法,使用ntp服务获取时间,物联网平台借鉴NTP协议原理,将云端作为NTP服务器。设备端发送一个特定Topic给云端,payload中带上发送时间。云端回复时在payload中加上云端的接收时间和发送时间。设备端收到回复后,再结合自己本地当前时间,得出一共4个时间。一起计算出设备端与云端的时间差,从而得出端上当前的精确时间。

注意:只有设备端与云端成功建立连接之后,才能通过NTP服务进行校准

步骤:

  1. 设备端订阅/ext/ntp/${YourProductKey}/${YourDeviceName}/responseTopic。
    //回调函数,当发送请求topic后,用此函数接收时间
    static void request_topic_handle_func(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
    {
        
        iotx_mqtt_topic_info_t     *topic_info = (iotx_mqtt_topic_info_pt) msg->msg;
            switch (msg->event_type) {
                case IOTX_MQTT_EVENT_PUBLISH_RECEIVED:
                    /* print topic name and topic message */
                    EXAMPLE_TRACE("Payload: %.*s", topic_info->payload_len, topic_info->payload);
                    break;
                default:
                    break;
            }
    }
    #define RESPONSE_TOPIC         "/ext/ntp/a11YWzN48cV/fourswitch/response"
    IOT_MQTT_Subscribe(NULL,RESPONSE_TOPIC,IOTX_MQTT_QOS0,request_topic_handle_func,NULL);

     

  2. 设备端向/ext/ntp/${YourProductKey}/${YourDeviceName}/requestTopic发送一条QoS=0的消息,payload中带上设备当前的时间戳,单位为毫秒。示例如下:
    #define REQUEST_TOPIC         "/ext/ntp/a11YWzN48cV/fourswitch/request"
    char           *payload = "{\"deviceSendTime\":\"100\"}";
    IOT_MQTT_Publish_Simple(0,REQUEST_TOPIC,IOTX_MQTT_QOS0,payload,strlen(payload));

     

  3. 设备端收到服务端回复的消息,payload中包含以下信息:
    {
        "deviceSendTime":"100",//发送时设备端时间戳
        "serverRecvTime":"1010",//服务端接收时时间戳
        "serverSendTime":"1015",//服务端发送时时间戳
    }

     

  4. 设备端计算出当前精确的unix时间。

    设备端收到服务端的时间记为${deviceRecvTime},则设备上的精确时间为:(${serverRecvTime} + ${serverSendTime} + ${deviceRecvTime} - ${deviceSendTime}) / 2alios things ntp获取时间_第1张图片

你可能感兴趣的:(alios,things)