iot_sntp.c 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /*
  2. * Copyright (c) 2021 Huawei Device Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #include "iot_sntp.h"
  16. #include <stdint.h>
  17. #include <stddef.h>
  18. #include <string.h>
  19. #include <stdlib.h>
  20. #include <time.h>
  21. #include <stdio.h>
  22. #include <unistd.h>
  23. #include "ohos_init.h"
  24. #include "ohos_types.h"
  25. #include "cmsis_os2.h"
  26. #include "lwip/sockets.h"
  27. #include "kv_store.h"
  28. // this is the default SNTP server and port defines, you could define your own by add it in the config.gni
  29. #ifndef NTP_SERVER_IP
  30. #define NTP_SERVER_IP "120.24.166.46"
  31. #endif
  32. #ifndef NTP_SERVER_PORT
  33. #define NTP_SERVER_PORT 123
  34. #endif
  35. /**
  36. * The ntp server returns the time from 1900-1-1-0-0-0, and the unix
  37. * timestamp compute from 1970-1-1-0-0-0, so we define the seconds between
  38. * 1900-1-1-0-0-0 and 1970-1-1-0-0-0; when we get timestamp from NTP server,
  39. * we must sub this time
  40. */
  41. #define SECONDS_FROM_1900_TO_1970 (2208988800L)
  42. /**
  43. * @brief NTP procto packet message
  44. * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
  45. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  46. * | LI| VN |Mode | Stratum | Poll | Precision |
  47. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  48. * | Root delay (32Bits) |
  49. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  50. * | Root dispersion (32Bits) |
  51. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  52. * | Reference identifier (32Bits) |
  53. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  54. * | |
  55. * | Reference timestamp (64Bits) |
  56. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  57. * | |
  58. * | Originate timestamp (64Bits) |
  59. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  60. * | |
  61. * | Receive timestamp (64Bits) |
  62. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  63. * | |
  64. * | Transmit timestamp (64Bits) |
  65. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  66. * | |
  67. * | Authenticator(optional 96Bits) |
  68. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
  69. *
  70. * 主要字段的解释如下:
  71. * LI:当前时间闰秒标志。字段长度为2位整数,只在服务器端有效。取值定义为:
  72. * LI=0:无警告;
  73. * LI=1:最后一分钟是61秒;
  74. * LI=2:最后一分钟是59秒;
  75. * LI=3:警告(时钟没有同步)
  76. * 服务器在开始时,LI设置为3,一旦与主钟取得同步后就设置成其它值。
  77. * VN(Version Number):长度为3比特,表示NTP的版本号,可以是3或者是4
  78. * Mode:指示协议模式。字段长度为3位,取值定义为:
  79. * Mode=0:保留
  80. * Mode=1:对称主动;
  81. * Mode=2:对称被动;
  82. * Mode=3:客户;
  83. * Mode=4:服务器;
  84. * Mode=5:广播;
  85. * Mode=6:保留为NTP控制信息;
  86. * Mode=7:保留为用户定义;
  87. * 在单播和多播模式,客户在请求时把这个字段设置为3,服务器在响应时把这个字段设置为4。在广播模式下,服务器把这个字段设置为5。
  88. * Poll Interval:指示数据包的最大时间间隔,以秒为单位,作为2的指数方的指数部分,该字段只在服务器端有效。字段长度为8位整数,取值范围从4-17,即16秒到131,072秒。
  89. * Precision:指示系统时钟的精确性,以秒为单位,作为2的指数方的指数部分,该字段只在服务器端有效。字段长度为8位符号整数,取值范围从-6到-20。
  90. * Root Delay:指示与主时钟参考源的总共往返延迟,以秒为单位,该字段只在服务器端有效。字段长度为32位浮点数,小数部分在16位以后,取值范围从负几毫秒到正几百毫秒。
  91. * Root Dispersion:指示与主时钟参考源的误差,以秒为单位,该字段只在服务器端有效。字段长度为32位浮点数,小数部分在16位以后,取值范围从零毫秒到正几百毫秒。
  92. * Reference Identifier:指示时钟参考源的标记,该字段只在服务器端有效。对于一级服务器,字段长度为4字节ASCII字符串,左对齐不足添零。对于二级服务器,在IPV4环境下,取值为一级服务器的IP地址,在IPV6环境下,是一级服务器的NSAP地址。
  93. * Reference Timestamp:指示系统时钟最后一次校准的时间,该字段只在服务器端有效,以前面所述64位时间戳格式表示。
  94. * Originate Timestamp:指示客户向服务器发起请求的时间,以前面所述64位时间戳格式表示。
  95. * Receive Timestamp:指服务器收到客户请求的时间 ,以前面所述64位时间戳格式表示。
  96. * Transmit Timestamp:指示服务器向客户发时间戳的时间,以前面所述64位时间戳格式表示。
  97. * Authenticator(可选):当需要进行SNTP认证时,该字段包含密钥和信息加密码
  98. *
  99. */
  100. /**
  101. * @brief defines the NTP packet corresponding to the procto
  102. *
  103. */
  104. #pragma pack(1)
  105. typedef struct {
  106. uint32_t low;
  107. uint32_t high;
  108. }TimeStamp; // for the 64Bits timestamp use
  109. typedef struct {
  110. uint8_t liVnMode;
  111. uint8_t stratum;
  112. uint8_t poll;
  113. uint8_t precision;
  114. uint32_t rootDelay;
  115. uint32_t rootDispersion;
  116. uint8_t referenceID[4];
  117. TimeStamp refecenceTimestamp;
  118. TimeStamp originateTimestamp;
  119. TimeStamp receiveTimestamp;
  120. TimeStamp transmitTimestamp;
  121. }SntpPacket;
  122. #pragma pack()
  123. #define CN_TIMEZONE_MAXIMUM (11)
  124. #define CN_TIMEZONE_MINIMUM (-11)
  125. #define CN_SNTP_RETRYTIMES 10
  126. int SntpGetRtcTime(int localTimeZone, struct tm *rtcTime)
  127. {
  128. int ret = -1;
  129. int sockfd = -1;
  130. struct sockaddr_in server;
  131. socklen_t addrLen;
  132. fd_set set;
  133. struct timeval timeout;
  134. struct timeval tv;
  135. int nRet;
  136. SntpPacket sntpPacket;
  137. struct tm *time = NULL;
  138. int tryTimes = CN_SNTP_RETRYTIMES;
  139. // check the params passed to this API
  140. if ((localTimeZone > CN_TIMEZONE_MAXIMUM) || (localTimeZone < CN_TIMEZONE_MINIMUM) ||\
  141. rtcTime == NULL) {
  142. return ret;
  143. }
  144. // prepare the server address
  145. bzero(&server, sizeof(server));
  146. server.sin_family = AF_INET;
  147. server.sin_port = htons(NTP_SERVER_PORT);
  148. addrLen = sizeof(server);
  149. if (inet_aton(NTP_SERVER_IP, &server.sin_addr) <= 0) {
  150. printf("inet_pton error\n");
  151. return ret;
  152. }
  153. if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  154. return ret;
  155. }
  156. // we do the loop here to get the time
  157. do{
  158. tryTimes--;
  159. // prepare the send packet
  160. bzero((char * )&sntpPacket, sizeof(sntpPacket)); // clean it
  161. sntpPacket.liVnMode = 0x1b; // set the mode to client
  162. if (sendto(sockfd, (char *) &sntpPacket, sizeof(sntpPacket), 0,
  163. (struct sockaddr*) &server, addrLen) < 0) {
  164. printf("sendto error!\n");
  165. continue;
  166. }
  167. // use select to get the data
  168. FD_ZERO(&set);
  169. FD_SET(sockfd, &set);
  170. timeout.tv_sec = 0;
  171. timeout.tv_usec = 500000;
  172. nRet = select(sockfd + 1, &set, NULL, NULL, &timeout);
  173. if (nRet < 0) {
  174. printf("select error!\n");
  175. continue;
  176. } else if (nRet == 0) {
  177. printf("time out!\n");
  178. continue;
  179. } else {
  180. if (FD_ISSET(sockfd, &set)) {
  181. if (recvfrom(sockfd, (char *) &sntpPacket, sizeof(sntpPacket),
  182. 0, (struct sockaddr*) &server, &addrLen) < 0) {
  183. printf("recv error!\n");
  184. continue;
  185. } else {
  186. tv.tv_usec = 0;
  187. tv.tv_sec = ntohl(sntpPacket.transmitTimestamp.low);
  188. tv.tv_sec -= SECONDS_FROM_1900_TO_1970;
  189. tv.tv_sec += (localTimeZone * 3600);
  190. if((time = gmtime_r((const long int *) &tv.tv_sec, rtcTime)) != NULL) {
  191. ret = 0;
  192. break;
  193. }
  194. }
  195. }
  196. }
  197. } while (tryTimes > 0);
  198. closesocket(sockfd);
  199. return ret;
  200. }