NTP service

更新时间:
复制 MD 格式

IoT Platform provides a Network Time Protocol (NTP) service. This service helps resource-constrained embedded devices obtain the real-time clock. You can configure the C Link SDK to allow a device to obtain the UTC time.

Prerequisites

Background information

Alibaba Cloud IoT Platform provides the Network Time Protocol (NTP) service. For more information, see NTP service.

Usage flow

The following sequence diagram shows the NTP service flow. The demos/ntp_basic_demo.c application is used as an example.

image..png

Step 1: Device initialization

  1. Create a device handle and establish a connection for the device.

    static void* demo_device_init(char *product_key, char *device_name, char *device_secret, char *host, uint16_t port)
    {
        int32_t res = STATE_SUCCESS;
        /* Create a device. */
        void *device = aiot_device_create(product_key, device_name);
    	....
        ....
            
        res = aiot_device_connect(device);
        
    	....
        ....
        return device;
    }
  2. Configure the NTP module.

    • Set the time synchronization callback function.

          /* Set the time synchronization callback function. */
          aiot_device_ntp_set_callback(device, demo_ntp_callback, NULL);

      Parameter description

      Parameter

      Description

      device

      The device handle.

      demo_ntp_callback

      A custom callback function.

      NULL

      The context parameter of the callback function. The example uses NULL.

    • Set the time zone.

          /* This demo uses UTC+8, the time zone for China. Therefore, the sample code prints the time in UTC+8 during runtime. */
          aiot_device_ntp_set_zone(device, 8);

      Parameter description

      Parameter

      Description

      device

      The device handle.

      8

      The time zone. Examples:

      • For UTC+8, set the value to 8.

      • For UTC-3, set the value to -3.

Step 2: Send a time synchronization request

  1. Send a time synchronization request.

    /* Send a time synchronization request. */
    aiot_device_ntp_request(device);
  2. Time synchronization callback function.

    /* The time synchronization callback function. */
    static void demo_ntp_callback(void *device, const aiot_ntp_time_t *recv_time, void *userdata)
    {
        printf("ntp recv time %d-%d-%d %d:%d:%d %d\r\n", 
            recv_time->year, recv_time->mon, recv_time->day, 
            recv_time->hour, recv_time->min, recv_time->sec, recv_time->msec);
    }

    Parameter description

    Parameter

    Description

    device

    The device handle.

    recv_time

    The returned time, which you can use directly.

    userdata

    The context of the callback. The example uses NULL.

Step 3: Device deinitialization

 /* Disconnect the device and release its resources. */
 demo_device_deinit(device);