sntp.c 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #include "sntp.h"
  2. #include "rtc.h"
  3. #include "settings_api.h"
  4. #include "tcpip.h"
  5. #include "udp.h"
  6. #include <string.h>
  7. #include <time.h>
  8. #include "FreeRTOS.h"
  9. #include "task.h"
  10. #ifdef PRINTF_STDLIB
  11. #include <stdio.h>
  12. #endif
  13. #ifdef PRINTF_CUSTOM
  14. #include "tinystdio.h"
  15. #endif
  16. #define SENDFAIL_TIMEOUT 5000 /* 5 seconds */
  17. #define SENT_TIMEOUT 60000 /* 1 minute */
  18. #define BADREPLY_TIMEOUT 60000 /* 1 minute */
  19. #define VALID_TIMEOUT (8 * 3600000) /* 8 hours */
  20. /* number of seconds between 1900 and 1970 */
  21. #define DIFF_SEC_1900_1970 (2208988800UL)
  22. struct sntp_packet
  23. {
  24. uint8_t status;
  25. uint8_t stratum;
  26. uint8_t ppoll;
  27. uint8_t precision;
  28. uint32_t distance;
  29. uint32_t dispersion;
  30. uint32_t refid;
  31. uint64_t reftime;
  32. uint64_t org;
  33. uint64_t rec;
  34. uint64_t xmt;
  35. };
  36. static unsigned int timeout;
  37. static struct udp_pcb* upcb;
  38. static struct ip4_addr server;
  39. static int port = 123;
  40. /**
  41. * @brief Общая структура настроек
  42. */
  43. extern SETTINGS_t sSettings;
  44. /**
  45. * @brief Разовая синхронизация времени при старте контроллера
  46. */
  47. extern TaskHandle_t xHandleSntpOnceSinhro;
  48. /**
  49. * @brief Синхронизация времени единоразово при включении контроллера
  50. * @retval
  51. */
  52. void vTaskOnceSynchro(void *arg)
  53. {
  54. for (;;)
  55. {
  56. if (sSettings.sSNTP.sntpEnable)
  57. {
  58. vTaskDelay(7000);
  59. SNTP_Poll();
  60. //printf("Once time sinhro\n\r");
  61. vTaskDelete(xHandleSntpOnceSinhro);
  62. }
  63. else
  64. {
  65. vTaskDelay(7000);
  66. }
  67. vTaskDelete(xHandleSntpOnceSinhro);
  68. }
  69. }
  70. /**
  71. * @brief Периодическая синхронизация времени.
  72. * Выполняется раз в сутки с 0 часов.
  73. * @retval
  74. */
  75. void vTaskPeriodicSynchro(void *arg)
  76. {
  77. TM_RTC_t data;
  78. static uint8_t fSinhro = 0;
  79. for (;;)
  80. {
  81. vTaskDelay(10000);
  82. if (sSettings.sSNTP.sntpEnable)
  83. {
  84. TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
  85. /* Если пришло время синхронизации */
  86. if ((data.hours == 0) && (fSinhro == 0))
  87. {
  88. SNTP_Poll();
  89. fSinhro = 1;
  90. //printf("Periodic time sinhro\n\r");
  91. }
  92. if (data.hours > 1)
  93. fSinhro = 0;
  94. }
  95. }
  96. }
  97. /**
  98. * @brief Отладочный таск. Выводим время в консоль.
  99. * @retval
  100. */
  101. void vTaskSntp(void *arg)
  102. {
  103. TM_RTC_t data;
  104. for (;;)
  105. {
  106. vTaskDelay(1000);
  107. TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
  108. printf("%d.%d.%d %d:%d:%d \n\r", data.date,data.month,data.year,data.hours,data.minutes,data.seconds);
  109. }
  110. }
  111. /**
  112. * @brief Инициализация SNTP.
  113. * @retval
  114. */
  115. void SNTP_Init(void)
  116. {
  117. SNTP_SetServerAddr(sSettings.sSNTP.ip);
  118. SNTP_Enable(sSettings.sSNTP.sntpEnable);
  119. }
  120. static void recv(void *arg, struct udp_pcb *upcb, struct pbuf *p,
  121. const ip_addr_t *addr, u16_t port)
  122. {
  123. time_t t;
  124. int utcSec = 0;
  125. TM_RTC_t data;
  126. if (p->len == sizeof(struct sntp_packet))
  127. {
  128. int i;
  129. struct sntp_packet aligned;
  130. //myassert(p->len == p->tot_len); /* don't accept chained pbuf */
  131. memcpy(&aligned, p->payload, sizeof(aligned));
  132. i = (aligned.status >> 3) & 7;
  133. if ((i < 1) || (i > 4)) /* SNTP version 1..4 */
  134. goto out;
  135. i = aligned.status & 7;
  136. if ((i != 4) && (i != 5)) /* mode 4 or 5: server or broadcast */
  137. goto out;
  138. if (aligned.xmt == 0)
  139. goto out;
  140. utcSec = (int)(3600.0*sSettings.sSNTP.timeZone);
  141. t = (ntohl(aligned.xmt) - 2208988800 + utcSec );
  142. TM_RTC_SetDataTimeUnix((uint32_t)t);
  143. /* Сохраним время последней синхронизации */
  144. TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
  145. memset(sSettings.sSNTP.data, 0, sizeof(sSettings.sSNTP.data));
  146. sprintf(sSettings.sSNTP.data, "%02d.%02d.%02d %02d:%02d:%02d",
  147. data.date, data.month, data.year,
  148. data.hours, data.minutes, data.seconds);
  149. timeout = VALID_TIMEOUT;
  150. }
  151. out:
  152. pbuf_free(p);
  153. }
  154. void SNTP_Enable(bool enable)
  155. {
  156. if (enable)
  157. {
  158. if (upcb == 0)
  159. {
  160. err_t ret;
  161. upcb = udp_new();
  162. if (upcb != 0)
  163. {
  164. ret = udp_bind(upcb, IP_ADDR_ANY, port);
  165. if (ret != ERR_OK)
  166. {
  167. udp_remove(upcb);
  168. upcb = 0;
  169. }
  170. else
  171. {
  172. udp_recv(upcb, recv, 0);
  173. }
  174. timeout = 0;
  175. }
  176. }
  177. }
  178. else if (upcb != 0)
  179. {
  180. udp_remove(upcb);
  181. upcb = 0;
  182. }
  183. }
  184. bool SNTP_IsEnabled(void)
  185. {
  186. return upcb != 0;
  187. }
  188. void SNTP_SetServerAddr(char *addr)
  189. {
  190. server.addr = ipaddr_addr(addr);
  191. }
  192. int sntp_getserverport(void)
  193. {
  194. return port;
  195. }
  196. static void send_request(void)
  197. {
  198. struct sntp_packet packet;
  199. struct pbuf* psend;
  200. memset(&packet, 0, sizeof(packet));
  201. packet.status = (3 << 3) /* SNTP vesion 3 */ | (3 << 0); /* Mode: client */
  202. psend = pbuf_alloc(PBUF_RAW, sizeof(packet), PBUF_REF);
  203. if (psend != 0)
  204. {
  205. psend->payload = &packet;
  206. timeout = (udp_sendto(upcb, psend, &server, port) == ERR_OK) ? SENT_TIMEOUT : SENDFAIL_TIMEOUT;
  207. pbuf_free(psend);
  208. }
  209. }
  210. void SNTP_Poll(void)
  211. {
  212. if (upcb)
  213. send_request();
  214. }