2 * FreeRTOS+TCP V2.0.3
\r
3 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
\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
12 * The above copyright notice and this permission notice shall be included in all
\r
13 * copies or substantial portions of the Software.
\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
22 * http://aws.amazon.com/freertos
\r
23 * http://www.FreeRTOS.org
\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
34 /* Standard includes. */
\r
40 /* FreeRTOS includes. */
\r
41 #include "FreeRTOS.h"
\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
51 /* Use the date & time functions from +FAT. */
\r
52 #include "ff_time.h"
\r
54 #include "NTPDemo.h"
\r
55 #include "ntpClient.h"
\r
57 #include "date_and_time.h"
\r
66 static struct SNtpPacket xNTPPacket;
\r
68 #if( ipconfigUSE_CALLBACKS == 0 )
\r
69 static char cRecvBuffer[ sizeof( struct SNtpPacket ) + 64 ];
\r
72 static enum EStatus xStatus = EStatusLookup;
\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
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
89 static void prvNTPTask( void *pvParameters );
\r
91 static void vSignalTask( void )
\r
93 #if( ipconfigUSE_CALLBACKS == 0 )
\r
94 if( xUDPSocket != NULL )
\r
96 /* Send a signal to the socket so that the
\r
97 FreeRTOS_recvfrom will get interrupted. */
\r
98 FreeRTOS_SignalSocket( xUDPSocket );
\r
102 if( xNTPWakeupSem != NULL )
\r
104 xSemaphoreGive( xNTPWakeupSem );
\r
108 void vStartNTPTask( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority )
\r
110 /* The only public function in this module: start a task to contact
\r
111 some NTP server. */
\r
113 if( xNTPTaskhandle != NULL )
\r
118 xStatus = EStatusAsking;
\r
121 case EStatusLookup:
\r
122 FreeRTOS_printf( ( "NTP looking up server\n" ) );
\r
124 case EStatusAsking:
\r
125 FreeRTOS_printf( ( "NTP still asking\n" ) );
\r
127 case EStatusFailed:
\r
128 FreeRTOS_printf( ( "NTP failed somehow\n" ) );
\r
129 ulIPAddressFound = 0ul;
\r
130 xStatus = EStatusLookup;
\r
137 xUDPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
\r
138 if( xUDPSocket != FREERTOS_INVALID_SOCKET )
\r
140 struct freertos_sockaddr xAddress;
\r
141 #if( ipconfigUSE_CALLBACKS != 0 )
\r
142 BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 0 );
\r
144 BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );
\r
147 xAddress.sin_addr = 0ul;
\r
148 xAddress.sin_port = FreeRTOS_htons( NTP_PORT );
\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
161 FreeRTOS_printf( ( "Creating socket failed\n" ) );
\r
165 /*-----------------------------------------------------------*/
\r
167 static void vDNS_callback( const char *pcName, void *pvSearchID, uint32_t ulIPAddress )
\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
176 ulIPAddressFound = ulIPAddress;
\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
182 ulIPAddressFound = FreeRTOS_inet_addr_quick( 184, 105, 182, 7 );
\r
183 /* ulIPAddressFound = FreeRTOS_inet_addr_quick( 103, 242, 70, 4 ); */
\r
185 xStatus = EStatusAsking;
\r
189 /*-----------------------------------------------------------*/
\r
191 static void prvSwapFields( struct SNtpPacket *pxPacket)
\r
193 /* NTP messages are big-endian */
\r
194 pxPacket->rootDelay = FreeRTOS_htonl( pxPacket->rootDelay );
\r
195 pxPacket->rootDispersion = FreeRTOS_htonl( pxPacket->rootDispersion );
\r
197 pxPacket->referenceTimestamp.seconds = FreeRTOS_htonl( pxPacket->referenceTimestamp.seconds );
\r
198 pxPacket->referenceTimestamp.fraction = FreeRTOS_htonl( pxPacket->referenceTimestamp.fraction );
\r
200 pxPacket->originateTimestamp.seconds = FreeRTOS_htonl( pxPacket->originateTimestamp.seconds );
\r
201 pxPacket->originateTimestamp.fraction = FreeRTOS_htonl( pxPacket->originateTimestamp.fraction );
\r
203 pxPacket->receiveTimestamp.seconds = FreeRTOS_htonl( pxPacket->receiveTimestamp.seconds );
\r
204 pxPacket->receiveTimestamp.fraction = FreeRTOS_htonl( pxPacket->receiveTimestamp.fraction );
\r
206 pxPacket->transmitTimestamp.seconds = FreeRTOS_htonl( pxPacket->transmitTimestamp.seconds );
\r
207 pxPacket->transmitTimestamp.fraction = FreeRTOS_htonl( pxPacket->transmitTimestamp.fraction );
\r
209 /*-----------------------------------------------------------*/
\r
211 static void prvNTPPacketInit( )
\r
213 memset (&xNTPPacket, '\0', sizeof( xNTPPacket ) );
\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
221 /* use the recorded NTP time */
\r
222 time_t uxSecs = FreeRTOS_time( NULL );/* apTime may be NULL, returns seconds */
\r
224 xNTPPacket.referenceTimestamp.seconds = uxSecs; /* Current time */
\r
225 xNTPPacket.transmitTimestamp.seconds = uxSecs + 3;
\r
227 /* Transform the contents of the fields from native to big endian. */
\r
228 prvSwapFields( &xNTPPacket );
\r
230 /*-----------------------------------------------------------*/
\r
232 static void prvReadTime( struct SNtpPacket * pxPacket )
\r
234 FF_TimeStruct_t xTimeStruct;
\r
235 time_t uxPreviousSeconds;
\r
236 time_t uxPreviousMS;
\r
238 time_t uxCurrentSeconds;
\r
239 time_t uxCurrentMS;
\r
241 const char *pcTimeUnit;
\r
243 TickType_t uxTravelTime;
\r
245 uxTravelTime = xTaskGetTickCount() - uxSendTime;
\r
247 /* Transform the contents of the fields from big to native endian. */
\r
248 prvSwapFields( pxPacket );
\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
255 // Get the last time recorded
\r
256 uxPreviousSeconds = FreeRTOS_get_secs_msec( &uxPreviousMS );
\r
258 // Set the new time with precision in msec. */
\r
259 FreeRTOS_set_secs_msec( &uxCurrentSeconds, &uxCurrentMS );
\r
261 if( uxCurrentSeconds >= uxPreviousSeconds )
\r
263 ilDiff = ( int32_t ) ( uxCurrentSeconds - uxPreviousSeconds );
\r
267 ilDiff = 0 - ( int32_t ) ( uxPreviousSeconds - uxCurrentSeconds );
\r
270 if( ( ilDiff < -5 ) || ( ilDiff > 5 ) )
\r
272 /* More than 5 seconds difference. */
\r
273 pcTimeUnit = "sec";
\r
277 /* Less than or equal to 5 second difference. */
\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
284 uxCurrentSeconds -= iTimeZone;
\r
286 FreeRTOS_gmtime_r( &uxCurrentSeconds, &xTimeStruct );
\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
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
305 /* Remove compiler warnings in case FreeRTOS_printf() is not used. */
\r
306 ( void ) pcTimeUnit;
\r
307 ( void ) uxTravelTime;
\r
309 /*-----------------------------------------------------------*/
\r
311 #if( ipconfigUSE_CALLBACKS != 0 )
\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
316 if( xLength >= sizeof( xNTPPacket ) )
\r
318 prvReadTime( ( struct SNtpPacket *)pvData );
\r
319 if( xStatus != EStatusPause )
\r
321 xStatus = EStatusPause;
\r
325 /* Tell the driver not to store the RX data */
\r
328 /*-----------------------------------------------------------*/
\r
330 #endif /* ipconfigUSE_CALLBACKS != 0 */
\r
332 static void prvNTPTask( void *pvParameters )
\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
340 xStatus = EStatusLookup;
\r
341 #if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 ) || ( ipconfigUSE_CALLBACKS != 0 )
\r
343 xNTPWakeupSem = xSemaphoreCreateBinary();
\r
347 #if( ipconfigUSE_CALLBACKS != 0 )
\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
354 #if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 )
\r
356 FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_SET_SEMAPHORE, ( void * ) &xNTPWakeupSem, sizeof( xNTPWakeupSem ) );
\r
363 case EStatusLookup:
\r
364 if( ( ulIPAddressFound == 0ul ) || ( ulIPAddressFound == ~0ul ) )
\r
366 if( ++xServerIndex == sizeof( pcTimeServers ) / sizeof( pcTimeServers[ 0 ] ) )
\r
370 FreeRTOS_printf( ( "Looking up server '%s'\n", pcTimeServers[ xServerIndex ] ) );
\r
371 FreeRTOS_gethostbyname_a( pcTimeServers[ xServerIndex ], vDNS_callback, (void *)NULL, 1200 );
\r
375 xStatus = EStatusAsking;
\r
379 case EStatusAsking:
\r
383 prvNTPPacketInit( );
\r
384 xAddress.sin_addr = ulIPAddressFound;
\r
385 xAddress.sin_port = FreeRTOS_htons( NTP_PORT );
\r
387 FreeRTOS_inet_ntoa( xAddress.sin_addr, pcBuf );
\r
388 FreeRTOS_printf( ( "Sending UDP message to %s:%u\n",
\r
390 FreeRTOS_ntohs( xAddress.sin_port ) ) );
\r
392 uxSendTime = xTaskGetTickCount( );
\r
393 FreeRTOS_sendto( xUDPSocket, ( void * )&xNTPPacket, sizeof( xNTPPacket ), 0, &xAddress, sizeof( xAddress ) );
\r
400 case EStatusFailed:
\r
404 #if( ipconfigUSE_CALLBACKS != 0 )
\r
406 xSemaphoreTake( xNTPWakeupSem, 5000 );
\r
410 uint32_t xAddressSize;
\r
411 BaseType_t xReturned;
\r
413 xAddressSize = sizeof( xAddress );
\r
414 xReturned = FreeRTOS_recvfrom( xUDPSocket, ( void * ) cRecvBuffer, sizeof( cRecvBuffer ), 0, &xAddress, &xAddressSize );
\r
415 switch( xReturned )
\r
418 case -pdFREERTOS_ERRNO_EAGAIN:
\r
419 case -pdFREERTOS_ERRNO_EINTR:
\r
422 if( xReturned < sizeof( xNTPPacket ) )
\r
424 FreeRTOS_printf( ( "FreeRTOS_recvfrom: returns %ld\n", xReturned ) );
\r
428 prvReadTime( ( struct SNtpPacket *)cRecvBuffer );
\r
429 if( xStatus != EStatusPause )
\r
431 xStatus = EStatusPause;
\r
440 /*-----------------------------------------------------------*/
\r