sntp_api.c 5.4 KB

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