]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Demo/Common/Demo_IP_Protocols/NTP/NTPDemo.c
Minor bug fix in NTPDemo.c -> use of FREERTOS_INVALID_SOCKET in place of NULL.
[freertos] / FreeRTOS-Plus / Demo / Common / Demo_IP_Protocols / NTP / NTPDemo.c
1 /*\r
2  * FreeRTOS+TCP V2.0.3\r
3  * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
4  *\r
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
6  * this software and associated documentation files (the "Software"), to deal in\r
7  * the Software without restriction, including without limitation the rights to\r
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
9  * the Software, and to permit persons to whom the Software is furnished to do so,\r
10  * subject to the following conditions:\r
11  *\r
12  * The above copyright notice and this permission notice shall be included in all\r
13  * copies or substantial portions of the Software.\r
14  *\r
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
17  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
18  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
19  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
20  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
21  *\r
22  * http://aws.amazon.com/freertos\r
23  * http://www.FreeRTOS.org\r
24  */\r
25 \r
26 /*\r
27  * NTPDemo.c\r
28  *\r
29  * An example of how to lookup a domain using DNS\r
30  * And also how to send and receive UDP messages to get the NTP time\r
31  *\r
32  */\r
33 \r
34 /* Standard includes. */\r
35 #include <stdint.h>\r
36 #include <stdio.h>\r
37 #include <stdlib.h>\r
38 #include <time.h>\r
39 \r
40 /* FreeRTOS includes. */\r
41 #include "FreeRTOS.h"\r
42 #include "task.h"\r
43 #include "semphr.h"\r
44 \r
45 /* FreeRTOS+TCP includes. */\r
46 #include "FreeRTOS_IP.h"\r
47 #include "FreeRTOS_Sockets.h"\r
48 #include "FreeRTOS_DNS.h"\r
49 #include "FreeRTOS_Stream_Buffer.h"\r
50 \r
51 /* Use the date & time functions from +FAT. */\r
52 #include "ff_time.h"\r
53 \r
54 #include "NTPDemo.h"\r
55 #include "ntpClient.h"\r
56 \r
57 #include "date_and_time.h"\r
58 \r
59 enum EStatus {\r
60         EStatusLookup,\r
61         EStatusAsking,\r
62         EStatusPause,\r
63         EStatusFailed,\r
64 };\r
65 \r
66 static struct SNtpPacket xNTPPacket;\r
67 \r
68 #if( ipconfigUSE_CALLBACKS == 0 )\r
69         static char cRecvBuffer[ sizeof( struct SNtpPacket ) + 64 ];\r
70 #endif\r
71 \r
72 static enum EStatus xStatus = EStatusLookup;\r
73 \r
74 static const char *pcTimeServers[] = {\r
75         "0.asia.pool.ntp.org",\r
76         "0.europe.pool.ntp.org",\r
77         "0.id.pool.ntp.org",\r
78         "0.south-america.pool.ntp.org",\r
79         "0.oceania.pool.ntp.org",\r
80         "0.north-america.pool.ntp.org"\r
81 };\r
82 \r
83 static SemaphoreHandle_t xNTPWakeupSem = NULL;\r
84 static uint32_t ulIPAddressFound;\r
85 static Socket_t xUDPSocket = NULL;\r
86 static TaskHandle_t xNTPTaskhandle = NULL;\r
87 static TickType_t uxSendTime;\r
88 \r
89 static void prvNTPTask( void *pvParameters );\r
90 \r
91 static void vSignalTask( void )\r
92 {\r
93         #if( ipconfigUSE_CALLBACKS == 0 )\r
94         if( xUDPSocket != NULL )\r
95         {\r
96                 /* Send a signal to the socket so that the\r
97                 FreeRTOS_recvfrom will get interrupted. */\r
98                 FreeRTOS_SignalSocket( xUDPSocket );\r
99         }\r
100         else\r
101         #endif\r
102         if( xNTPWakeupSem != NULL )\r
103         {\r
104                 xSemaphoreGive( xNTPWakeupSem );\r
105         }\r
106 }\r
107 \r
108 void vStartNTPTask( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority )\r
109 {\r
110         /* The only public function in this module: start a task to contact\r
111         some NTP server. */\r
112 \r
113         if( xNTPTaskhandle != NULL )\r
114         {\r
115                 switch( xStatus )\r
116                 {\r
117                 case EStatusPause:\r
118                         xStatus = EStatusAsking;\r
119                         vSignalTask();\r
120                         break;\r
121                 case EStatusLookup:\r
122                         FreeRTOS_printf( ( "NTP looking up server\n" ) );\r
123                         break;\r
124                 case EStatusAsking:\r
125                         FreeRTOS_printf( ( "NTP still asking\n" ) );\r
126                         break;\r
127                 case EStatusFailed:\r
128                         FreeRTOS_printf( ( "NTP failed somehow\n" ) );\r
129                         ulIPAddressFound = 0ul;\r
130                         xStatus = EStatusLookup;\r
131                         vSignalTask();\r
132                         break;\r
133                 }\r
134         }\r
135         else\r
136         {\r
137                 xUDPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
138                 if( xUDPSocket != FREERTOS_INVALID_SOCKET )\r
139                 {\r
140                 struct freertos_sockaddr xAddress;\r
141                 #if( ipconfigUSE_CALLBACKS != 0 )\r
142                         BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 0 );\r
143                 #else\r
144                         BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );\r
145                 #endif\r
146 \r
147                         xAddress.sin_addr = 0ul;\r
148                         xAddress.sin_port = FreeRTOS_htons( NTP_PORT );\r
149 \r
150                         FreeRTOS_bind( xUDPSocket, &xAddress, sizeof( xAddress ) );\r
151                         FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );\r
152                         xTaskCreate(    prvNTPTask,                                             /* The function that implements the task. */\r
153                                                         ( const char * ) "NTP client",  /* Just a text name for the task to aid debugging. */\r
154                                                         usTaskStackSize,                                /* The stack size is defined in FreeRTOSIPConfig.h. */\r
155                                                         NULL,                                                   /* The task parameter, not used in this case. */\r
156                                                         uxTaskPriority,                                 /* The priority assigned to the task is defined in FreeRTOSConfig.h. */\r
157                                                         &xNTPTaskhandle );                              /* The task handle. */\r
158                 }\r
159                 else\r
160                 {\r
161                         FreeRTOS_printf( ( "Creating socket failed\n" ) );\r
162                 }\r
163         }\r
164 }\r
165 /*-----------------------------------------------------------*/\r
166 \r
167 static void vDNS_callback( const char *pcName, void *pvSearchID, uint32_t ulIPAddress )\r
168 {\r
169 char pcBuf[16];\r
170 \r
171         /* The DNS lookup has a result, or it has reached the time-out. */\r
172         FreeRTOS_inet_ntoa( ulIPAddress, pcBuf );\r
173         FreeRTOS_printf( ( "IP address of %s found: %s\n", pcName, pcBuf ) );\r
174         if( ulIPAddressFound == 0ul )\r
175         {\r
176                 ulIPAddressFound = ulIPAddress;\r
177         }\r
178         /* For testing: in case DNS doen't respond, still try some NTP server\r
179         with a known IP-address. */\r
180         if( ulIPAddressFound == 0ul )\r
181         {\r
182                 ulIPAddressFound = FreeRTOS_inet_addr_quick( 184, 105, 182, 7 );\r
183 /*              ulIPAddressFound = FreeRTOS_inet_addr_quick( 103, 242,  70, 4 );        */\r
184         }\r
185         xStatus = EStatusAsking;\r
186 \r
187         vSignalTask();\r
188 }\r
189 /*-----------------------------------------------------------*/\r
190 \r
191 static void prvSwapFields( struct SNtpPacket *pxPacket)\r
192 {\r
193         /* NTP messages are big-endian */\r
194         pxPacket->rootDelay = FreeRTOS_htonl( pxPacket->rootDelay );\r
195         pxPacket->rootDispersion = FreeRTOS_htonl( pxPacket->rootDispersion );\r
196 \r
197         pxPacket->referenceTimestamp.seconds = FreeRTOS_htonl( pxPacket->referenceTimestamp.seconds );\r
198         pxPacket->referenceTimestamp.fraction = FreeRTOS_htonl( pxPacket->referenceTimestamp.fraction );\r
199 \r
200         pxPacket->originateTimestamp.seconds = FreeRTOS_htonl( pxPacket->originateTimestamp.seconds );\r
201         pxPacket->originateTimestamp.fraction = FreeRTOS_htonl( pxPacket->originateTimestamp.fraction );\r
202 \r
203         pxPacket->receiveTimestamp.seconds = FreeRTOS_htonl( pxPacket->receiveTimestamp.seconds );\r
204         pxPacket->receiveTimestamp.fraction = FreeRTOS_htonl( pxPacket->receiveTimestamp.fraction );\r
205 \r
206         pxPacket->transmitTimestamp.seconds = FreeRTOS_htonl( pxPacket->transmitTimestamp.seconds );\r
207         pxPacket->transmitTimestamp.fraction = FreeRTOS_htonl( pxPacket->transmitTimestamp.fraction );\r
208 }\r
209 /*-----------------------------------------------------------*/\r
210 \r
211 static void prvNTPPacketInit( )\r
212 {\r
213         memset (&xNTPPacket, '\0', sizeof( xNTPPacket ) );\r
214 \r
215         xNTPPacket.flags = 0xDB;                                /* value 0xDB : mode 3 (client), version 3, leap indicator unknown 3 */\r
216         xNTPPacket.poll = 10;                                   /* 10 means 1 << 10 = 1024 seconds */\r
217         xNTPPacket.precision = 0xFA;                    /* = 250 = 0.015625 seconds */\r
218         xNTPPacket.rootDelay = 0x5D2E;                  /* 0x5D2E = 23854 or (23854/65535)= 0.3640 sec */\r
219         xNTPPacket.rootDispersion = 0x0008CAC8; /* 0x0008CAC8 = 8.7912  seconds */\r
220 \r
221         /* use the recorded NTP time */\r
222         time_t uxSecs = FreeRTOS_time( NULL );/* apTime may be NULL, returns seconds */\r
223 \r
224         xNTPPacket.referenceTimestamp.seconds = uxSecs; /* Current time */\r
225         xNTPPacket.transmitTimestamp.seconds = uxSecs + 3;\r
226 \r
227         /* Transform the contents of the fields from native to big endian. */\r
228         prvSwapFields( &xNTPPacket );\r
229 }\r
230 /*-----------------------------------------------------------*/\r
231 \r
232 static void prvReadTime( struct SNtpPacket * pxPacket )\r
233 {\r
234         FF_TimeStruct_t xTimeStruct;\r
235         time_t uxPreviousSeconds;\r
236         time_t uxPreviousMS;\r
237 \r
238         time_t uxCurrentSeconds;\r
239         time_t uxCurrentMS;\r
240 \r
241         const char *pcTimeUnit;\r
242         int32_t ilDiff;\r
243         TickType_t uxTravelTime;\r
244 \r
245         uxTravelTime = xTaskGetTickCount() - uxSendTime;\r
246 \r
247         /* Transform the contents of the fields from big to native endian. */\r
248         prvSwapFields( pxPacket );\r
249 \r
250         uxCurrentSeconds = pxPacket->receiveTimestamp.seconds - TIME1970;\r
251         uxCurrentMS = pxPacket->receiveTimestamp.fraction / 4294967;\r
252         uxCurrentSeconds += uxCurrentMS / 1000;\r
253         uxCurrentMS = uxCurrentMS % 1000;\r
254 \r
255         // Get the last time recorded\r
256         uxPreviousSeconds = FreeRTOS_get_secs_msec( &uxPreviousMS );\r
257 \r
258         // Set the new time with precision in msec. */\r
259         FreeRTOS_set_secs_msec( &uxCurrentSeconds, &uxCurrentMS );\r
260 \r
261         if( uxCurrentSeconds >= uxPreviousSeconds )\r
262         {\r
263                 ilDiff = ( int32_t ) ( uxCurrentSeconds - uxPreviousSeconds );\r
264         }\r
265         else\r
266         {\r
267                 ilDiff = 0 - ( int32_t ) ( uxPreviousSeconds - uxCurrentSeconds );\r
268         }\r
269 \r
270         if( ( ilDiff < -5 ) || ( ilDiff > 5 ) )\r
271         {\r
272                 /* More than 5 seconds difference. */\r
273                 pcTimeUnit = "sec";\r
274         }\r
275         else\r
276         {\r
277                 /* Less than or equal to 5 second difference. */\r
278                 pcTimeUnit = "ms";\r
279                 uint32_t ulLowest = ( uxCurrentSeconds <= uxPreviousSeconds ) ? uxCurrentSeconds : uxPreviousSeconds;\r
280                 int32_t iCurMS = 1000 * ( uxCurrentSeconds - ulLowest ) + uxCurrentMS;\r
281                 int32_t iPrevMS = 1000 * ( uxPreviousSeconds - ulLowest ) + uxPreviousMS;\r
282                 ilDiff = iCurMS - iPrevMS;\r
283         }\r
284         uxCurrentSeconds -= iTimeZone;\r
285 \r
286         FreeRTOS_gmtime_r( &uxCurrentSeconds, &xTimeStruct );\r
287 \r
288         /*\r
289                 378.067 [NTP client] NTP time: 9/11/2015 16:11:19.559 Diff -20 ms (289 ms)\r
290                 379.441 [NTP client] NTP time: 9/11/2015 16:11:20.933 Diff 0 ms (263 ms)\r
291         */\r
292 \r
293         FreeRTOS_printf( ("NTP time: %d/%d/%02d %2d:%02d:%02d.%03u Diff %d %s (%lu ms)\n",\r
294                 xTimeStruct.tm_mday,\r
295                 xTimeStruct.tm_mon + 1,\r
296                 xTimeStruct.tm_year + 1900,\r
297                 xTimeStruct.tm_hour,\r
298                 xTimeStruct.tm_min,\r
299                 xTimeStruct.tm_sec,\r
300                 ( unsigned )uxCurrentMS,\r
301                 ( unsigned )ilDiff,\r
302                 pcTimeUnit,\r
303                 uxTravelTime ) );\r
304 \r
305         /* Remove compiler warnings in case FreeRTOS_printf() is not used. */\r
306         ( void ) pcTimeUnit;\r
307         ( void ) uxTravelTime;\r
308 }\r
309 /*-----------------------------------------------------------*/\r
310 \r
311 #if( ipconfigUSE_CALLBACKS != 0 )\r
312 \r
313         static BaseType_t xOnUDPReceive( Socket_t xSocket, void * pvData, size_t xLength,\r
314                 const struct freertos_sockaddr *pxFrom, const struct freertos_sockaddr *pxDest )\r
315         {\r
316                 if( xLength >= sizeof( xNTPPacket ) )\r
317                 {\r
318                         prvReadTime( ( struct SNtpPacket *)pvData );\r
319                         if( xStatus != EStatusPause )\r
320                         {\r
321                                 xStatus = EStatusPause;\r
322                         }\r
323                 }\r
324                 vSignalTask();\r
325                 /* Tell the driver not to store the RX data */\r
326                 return 1;\r
327         }\r
328         /*-----------------------------------------------------------*/\r
329 \r
330 #endif  /* ipconfigUSE_CALLBACKS != 0 */\r
331 \r
332 static void prvNTPTask( void *pvParameters )\r
333 {\r
334 BaseType_t xServerIndex = 3;\r
335 struct freertos_sockaddr xAddress;\r
336 #if( ipconfigUSE_CALLBACKS != 0 )\r
337         F_TCP_UDP_Handler_t xHandler;\r
338 #endif /* ipconfigUSE_CALLBACKS != 0 */\r
339 \r
340         xStatus = EStatusLookup;\r
341         #if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 ) || ( ipconfigUSE_CALLBACKS != 0 )\r
342         {\r
343                 xNTPWakeupSem = xSemaphoreCreateBinary();\r
344         }\r
345         #endif\r
346 \r
347         #if( ipconfigUSE_CALLBACKS != 0 )\r
348         {\r
349                 memset( &xHandler, '\0', sizeof( xHandler ) );\r
350                 xHandler.pxOnUDPReceive = xOnUDPReceive;\r
351                 FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_UDP_RECV_HANDLER, ( void * ) &xHandler, sizeof( xHandler ) );\r
352         }\r
353         #endif\r
354         #if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 )\r
355         {\r
356                 FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_SET_SEMAPHORE, ( void * ) &xNTPWakeupSem, sizeof( xNTPWakeupSem ) );\r
357         }\r
358         #endif\r
359         for( ; ; )\r
360         {\r
361                 switch( xStatus )\r
362                 {\r
363                 case EStatusLookup:\r
364                         if( ( ulIPAddressFound == 0ul ) || ( ulIPAddressFound == ~0ul ) )\r
365                         {\r
366                                 if( ++xServerIndex == sizeof( pcTimeServers ) / sizeof( pcTimeServers[ 0 ] ) )\r
367                                 {\r
368                                         xServerIndex = 0;\r
369                                 }\r
370                                 FreeRTOS_printf( ( "Looking up server '%s'\n", pcTimeServers[ xServerIndex ] ) );\r
371                                 FreeRTOS_gethostbyname_a( pcTimeServers[ xServerIndex ], vDNS_callback, (void *)NULL, 1200 );\r
372                         }\r
373                         else\r
374                         {\r
375                                 xStatus = EStatusAsking;\r
376                         }\r
377                         break;\r
378 \r
379                 case EStatusAsking:\r
380                         {\r
381                         char pcBuf[16];\r
382 \r
383                                 prvNTPPacketInit( );\r
384                                 xAddress.sin_addr = ulIPAddressFound;\r
385                                 xAddress.sin_port = FreeRTOS_htons( NTP_PORT );\r
386 \r
387                                 FreeRTOS_inet_ntoa( xAddress.sin_addr, pcBuf );\r
388                                 FreeRTOS_printf( ( "Sending UDP message to %s:%u\n",\r
389                                         pcBuf,\r
390                                         FreeRTOS_ntohs( xAddress.sin_port ) ) );\r
391 \r
392                                 uxSendTime = xTaskGetTickCount( );\r
393                                 FreeRTOS_sendto( xUDPSocket, ( void * )&xNTPPacket, sizeof( xNTPPacket ), 0, &xAddress, sizeof( xAddress ) );\r
394                         }\r
395                         break;\r
396 \r
397                 case EStatusPause:\r
398                         break;\r
399 \r
400                 case EStatusFailed:\r
401                         break;\r
402                 }\r
403 \r
404                 #if( ipconfigUSE_CALLBACKS != 0 )\r
405                 {\r
406                         xSemaphoreTake( xNTPWakeupSem, 5000 );\r
407                 }\r
408                 #else\r
409                 {\r
410                 uint32_t xAddressSize;\r
411                 BaseType_t xReturned;\r
412 \r
413                         xAddressSize = sizeof( xAddress );\r
414                         xReturned = FreeRTOS_recvfrom( xUDPSocket, ( void * ) cRecvBuffer, sizeof( cRecvBuffer ), 0, &xAddress, &xAddressSize );\r
415                         switch( xReturned )\r
416                         {\r
417                         case 0:\r
418                         case -pdFREERTOS_ERRNO_EAGAIN:\r
419                         case -pdFREERTOS_ERRNO_EINTR:\r
420                                 break;\r
421                         default:\r
422                                 if( xReturned < sizeof( xNTPPacket ) )\r
423                                 {\r
424                                         FreeRTOS_printf( ( "FreeRTOS_recvfrom: returns %ld\n", xReturned ) );\r
425                                 }\r
426                                 else\r
427                                 {\r
428                                         prvReadTime( ( struct SNtpPacket *)cRecvBuffer );\r
429                                         if( xStatus != EStatusPause )\r
430                                         {\r
431                                                 xStatus = EStatusPause;\r
432                                         }\r
433                                 }\r
434                                 break;\r
435                         }\r
436                 }\r
437                 #endif\r
438         }\r
439 }\r
440 /*-----------------------------------------------------------*/\r