This article describes how to call the API operations of Link SDK for C to to obtain the UTC time from IoT Platform. In this example, the ./demos/ntp_posix_demo.c sample code file is used.
Background information
Step 1: Initialize a client
Step 2: Configure required features
Call the aiot_ntp_setopt operation to configure the following items:
- Associate with an MQTT connection handle.
- Set a time zone.
- Configure a message callback.
- Configure a callback to monitor status.
Step 3: Send a request
Call the aiot_ntp_send_request operation to send the current time of the device to the server by using the /ext/ntp/${YourProductKey}/${YourDeviceName}/request
topic. For more information about the parameters, see the previous step.
Link SDK can automatically submit the current time of the device by calling the API operation.
res = aiot_ntp_send_request(ntp_handle);
if (res < STATE_SUCCESS) {
aiot_ntp_deinit(&ntp_handle);
demo_mqtt_stop(&mqtt_handle);
return -1;
}
Step 4: Receive a response
After the device receives the NTP service message, the demo_ntp_recv_handler
callback is called to perform the required operations.
-
IoT Platform sends the server time to the device by using the
/ext/ntp/${YourProductKey}/${YourDeviceName}/response
topic. - aiot_ntp_recv_t indicates the data format. For more information, see the sample code.
-
In this example, after the response message is parsed, the packet pointer is used to print the parsed message.
void demo_ntp_recv_handler(void *handle, const aiot_ntp_recv_t *packet, void *userdata)
{
switch (packet->type) {
/* TODO: Parse and store the time information in the current time zone. The time information includes the year, month, day, hour, minute, and second. */
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: {
}
}
}
Step 5: Exit the program
Call the aiot_ntp_deinit operation to destroy the NTP client instance and release resources.
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;
}
What to do next
-
After you configure the sample code file, compile the file to generate an executable file In this example, the ./demos/ntp-posix-demo executable file is generated.
For more information, see Compilation and running.
-
For more information about running results, see View logs.