2 FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
\r
5 VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
\r
7 This file is part of the FreeRTOS distribution.
\r
9 FreeRTOS is free software; you can redistribute it and/or modify it under
\r
10 the terms of the GNU General Public License (version 2) as published by the
\r
11 Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
\r
13 ***************************************************************************
\r
14 >>! NOTE: The modification to the GPL is included to allow you to !<<
\r
15 >>! distribute a combined work that includes FreeRTOS without being !<<
\r
16 >>! obliged to provide the source code for proprietary components !<<
\r
17 >>! outside of the FreeRTOS kernel. !<<
\r
18 ***************************************************************************
\r
20 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
\r
21 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
\r
22 FOR A PARTICULAR PURPOSE. Full license text is available on the following
\r
23 link: http://www.freertos.org/a00114.html
\r
25 ***************************************************************************
\r
27 * FreeRTOS provides completely free yet professionally developed, *
\r
28 * robust, strictly quality controlled, supported, and cross *
\r
29 * platform software that is more than just the market leader, it *
\r
30 * is the industry's de facto standard. *
\r
32 * Help yourself get started quickly while simultaneously helping *
\r
33 * to support the FreeRTOS project by purchasing a FreeRTOS *
\r
34 * tutorial book, reference manual, or both: *
\r
35 * http://www.FreeRTOS.org/Documentation *
\r
37 ***************************************************************************
\r
39 http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
\r
40 the FAQ page "My application does not run, what could be wrong?". Have you
\r
41 defined configASSERT()?
\r
43 http://www.FreeRTOS.org/support - In return for receiving this top quality
\r
44 embedded software for free we request you assist our global community by
\r
45 participating in the support forum.
\r
47 http://www.FreeRTOS.org/training - Investing in training allows your team to
\r
48 be as productive as possible as early as possible. Now you can receive
\r
49 FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
\r
50 Ltd, and the world's leading authority on the world's leading RTOS.
\r
52 http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
\r
53 including FreeRTOS+Trace - an indispensable productivity tool, a DOS
\r
54 compatible FAT file system, and our tiny thread aware UDP/IP stack.
\r
56 http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
\r
57 Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
\r
59 http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
\r
60 Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
\r
61 licenses offer ticketed support, indemnification and commercial middleware.
\r
63 http://www.SafeRTOS.com - High Integrity Systems also provide a safety
\r
64 engineered and independently SIL3 certified version for use in safety and
\r
65 mission critical applications that require provable dependability.
\r
71 * FreeRTOS tasks are used with FreeRTOS+TCP to create a TCP echo server. Echo
\r
72 * clients are also created, but the echo clients use Windows threads (as
\r
73 * opposed to FreeRTOS tasks) and use the Windows TCP library (Winsocks). This
\r
74 * creates a communication between the FreeRTOS+TCP TCP/IP stack and the Windows
\r
77 * See the following web page for essential demo usage and configuration
\r
79 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/examples_FreeRTOS_simulator.html
\r
82 /* Standard includes. */
\r
85 #include <WinSock2.h>
\r
86 #include <Mswsock.h>
\r
88 /* FreeRTOS includes. */
\r
89 #include "FreeRTOS.h"
\r
93 /* FreeRTOS+TCP includes. */
\r
94 #include "FreeRTOS_IP.h"
\r
95 #include "FreeRTOS_Sockets.h"
\r
97 /* Remove the whole file if FreeRTOSIPConfig.h is set to exclude TCP. */
\r
98 #if( ipconfigUSE_TCP == 1 )
\r
100 /* This example uses Winsocks clients to talk to a FreeRTOS+TCP server. */
\r
101 #pragma comment( lib, "ws2_32.lib" )
\r
103 /* The number of Winsock clients that communicate with the FreeRTOS+TCP
\r
105 #define tcpechoNUMBER_OF_CLIENTS 1
\r
107 /* Specifies the size of the data sent to the server in MSS units. */
\r
108 #define tcpechoBUFFER_SIZE_MULTIPLIER 3
\r
110 /* Delay between cycles so as not to flood the network. */
\r
111 #define tcpechoLOOP_DELAY ( ( TickType_t ) 750 / portTICK_PERIOD_MS )
\r
113 /* The maximum time to wait for a closing socket to close. */
\r
114 #define tcpechoSHUTDOWN_DELAY ( pdMS_TO_TICKS( 5000 ) )
\r
116 /* The time to wait between reads of a Winsock socket when shutting the socket
\r
118 #define tcpechoWINSOCK_SHUTDOWN_DELAY ( 5 )
\r
120 /* The standard echo port number. */
\r
121 #define tcpechoPORT_NUMBER 7
\r
123 /* The size of the Rx and Tx buffers. */
\r
124 #define tcpechoBUFFER_SIZE ( ipconfigTCP_MSS * tcpechoBUFFER_SIZE_MULTIPLIER )
\r
126 /*-----------------------------------------------------------*/
\r
129 * Uses Winsocks from Windows threads to send data from the real IP and MAC
\r
130 * addresses to the IP and MAC addresses spoofed by FreeRTOS+TCP. Multiple
\r
131 * instances of this task are created.
\r
133 DWORD WINAPI prvSimpleWinsockTCPClientTask( void *pvParameters );
\r
136 * Uses FreeRTOS+TCP to listen for incoming echo connections, creating a task
\r
137 * to handle each connection.
\r
139 static void prvConnectionListeningTask( void *pvParameters );
\r
142 * Created by the connection listening task to handle a single connection.
\r
144 static void prvServerConnectionInstance( void *pvParameters );
\r
147 * Create a string to transmit of pseudo random length.
\r
149 static BaseType_t prvCreateTxData( char *cBuffer, uint32_t ulBufferLength );
\r
152 * Create the Windows threads that use the Windows TCP/IP stack to talk to the
\r
153 * FreeRTOS task that is using the FreeRTOS+TCP TCP/IP stack.
\r
155 static void prvCreateWindowsThreadClients( void );
\r
157 /*-----------------------------------------------------------*/
\r
159 /* Stores the stack size passed into vStartSimpleTCPServerTasks() so it can be
\r
160 reused when the server listening task creates tasks to handle connections. */
\r
161 static uint16_t usUsedStackSize = 0;
\r
163 /* Used for error reporting. */
\r
164 static uint32_t ulConnectionCount = 0, ulClientCycles = 0, ulClientTransmitErrors = 0, ulIncorrectDataReceived;
\r
165 static uint32_t ulClientSocketsClosedDuringReceive = 0, ulClientReceiveErrors = 0;
\r
167 /* The buffers used to hold the string to Tx and the received string. */
\r
168 static char cTxBuffers[ tcpechoNUMBER_OF_CLIENTS ][ tcpechoBUFFER_SIZE ], cRxBuffers[ tcpechoNUMBER_OF_CLIENTS ][ tcpechoBUFFER_SIZE ];
\r
170 /*-----------------------------------------------------------*/
\r
172 void vStartSimpleTCPServerTasks( uint16_t usStackSize, UBaseType_t uxPriority )
\r
174 WORD wVersionRequested;
\r
177 /* The clients use Winsock sockets and must therefore run at the idle
\r
179 configASSERT( uxPriority == tskIDLE_PRIORITY );
\r
181 /* Create the TCP echo server. The echo server uses FreeRTOS+TCP through
\r
182 the spoofed IP and MAC address. The WinSock client tasks are created from
\r
183 inside the listening task. */
\r
184 xTaskCreate( prvConnectionListeningTask, "ServerListener", usStackSize, NULL, uxPriority + 1, NULL );
\r
186 /* Prepare to use WinSock library. */
\r
187 wVersionRequested = MAKEWORD( 2, 2 );
\r
188 configASSERT( WSAStartup( wVersionRequested, &xWSAData ) == ( WORD ) 0 );
\r
190 /* Remember the requested stack size so it can be re-used by the server
\r
191 listening task when it creates tasks to handle connections. */
\r
192 usUsedStackSize = usStackSize;
\r
194 /*-----------------------------------------------------------*/
\r
196 static void prvCreateWindowsThreadClients( void )
\r
198 BaseType_t xClientTask;
\r
201 /* Create a set of (Windows thread) clients, all of which talk to the same
\r
202 (FreeRTOS task) server. The clients use Winsocks through the real IP and
\r
204 for( xClientTask = 0; xClientTask < tcpechoNUMBER_OF_CLIENTS; xClientTask++ )
\r
206 xWinHandle = CreateThread(
\r
207 NULL, /* Pointer to thread security attributes. */
\r
208 0, /* Initial thread stack size, in bytes. */
\r
209 prvSimpleWinsockTCPClientTask, /* Pointer to thread function. */
\r
210 ( void * ) xClientTask, /* Argument for new thread. */
\r
211 0, /* Creation flags. */
\r
214 /* Set the priority and the cores used of the Windows threads such that
\r
215 they do no interfere with the FreeRTOS simulator. */
\r
216 SetThreadPriority( xWinHandle, THREAD_PRIORITY_IDLE );
\r
217 SetThreadPriorityBoost( xWinHandle, TRUE );
\r
218 SetThreadAffinityMask( xWinHandle, ~0x01u );
\r
221 /*-----------------------------------------------------------*/
\r
223 static void prvConnectionListeningTask( void *pvParameters )
\r
225 struct freertos_sockaddr xClient, xBindAddress;
\r
226 Socket_t xListeningSocket, xConnectedSocket;
\r
227 socklen_t xSize = sizeof( xClient );
\r
228 static const TickType_t xReceiveTimeOut = portMAX_DELAY;
\r
229 const BaseType_t xBacklog = 20;
\r
230 WinProperties_t xWinProps;
\r
232 /* Just to prevent compiler warnings. */
\r
233 ( void ) pvParameters;
\r
235 /* Attempt to open the socket. */
\r
236 xListeningSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
\r
237 configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET );
\r
239 /* Set a time out so accept() will just wait for a connection. */
\r
240 FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
\r
242 /* Fill in the buffer and window sizes that will be used by the socket. */
\r
243 xWinProps.lTxBufSize = 6 * ipconfigTCP_MSS;
\r
244 xWinProps.lTxWinSize = 3;
\r
245 xWinProps.lRxBufSize = 6 * ipconfigTCP_MSS;
\r
246 xWinProps.lRxWinSize = 3;
\r
248 /* Set the window and buffer sizes. */
\r
249 FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) );
\r
251 /* Bind the socket to the port that the client task will send to, then
\r
252 listen for incoming connections. */
\r
253 xBindAddress.sin_port = tcpechoPORT_NUMBER;
\r
254 xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port );
\r
255 FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) );
\r
256 FreeRTOS_listen( xListeningSocket, xBacklog );
\r
258 /* Create the clients that will connect to the listening socket. */
\r
259 prvCreateWindowsThreadClients();
\r
263 /* Wait for a client to connect. */
\r
264 xConnectedSocket = FreeRTOS_accept( xListeningSocket, &xClient, &xSize );
\r
265 configASSERT( xConnectedSocket != FREERTOS_INVALID_SOCKET );
\r
267 /* Spawn a task to handle the connection. */
\r
268 xTaskCreate( prvServerConnectionInstance, "EchoServer", usUsedStackSize, ( void * ) xConnectedSocket, tskIDLE_PRIORITY, NULL );
\r
271 /*-----------------------------------------------------------*/
\r
273 static void prvServerConnectionInstance( void *pvParameters )
\r
275 int32_t lBytes, lSent, lTotalSent;
\r
276 uint8_t cReceivedString[ ipconfigTCP_MSS ];
\r
277 Socket_t xConnectedSocket;
\r
278 static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );
\r
279 static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 5000 );
\r
280 TickType_t xTimeOnShutdown;
\r
282 ulConnectionCount++;
\r
283 xConnectedSocket = ( Socket_t ) pvParameters;
\r
284 FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
\r
285 FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xReceiveTimeOut ) );
\r
289 /* Zero out the receive array so there is NULL at the end of the string
\r
290 when it is printed out. */
\r
291 memset( cReceivedString, 0x00, sizeof( cReceivedString ) );
\r
293 /* Receive data on the socket. */
\r
294 lBytes = FreeRTOS_recv( xConnectedSocket, cReceivedString, sizeof( cReceivedString ), 0 );
\r
296 /* If data was received, echo it back. */
\r
302 /* Call send() until all the data has been sent. */
\r
303 while( ( lSent >= 0 ) && ( lTotalSent < lBytes ) )
\r
305 lSent = FreeRTOS_send( xConnectedSocket, cReceivedString, lBytes - lTotalSent, 0 );
\r
306 lTotalSent += lSent;
\r
311 /* Socket closed? */
\r
317 /* Socket closed? */
\r
322 /* Initiate a shutdown in case it has not already been initiated. */
\r
323 FreeRTOS_shutdown( xConnectedSocket, FREERTOS_SHUT_RDWR );
\r
325 /* Wait for the shutdown to take effect, indicated by FreeRTOS_recv()
\r
326 returning an error. */
\r
327 xTimeOnShutdown = xTaskGetTickCount();
\r
330 if( FreeRTOS_recv( xConnectedSocket, cReceivedString, ipconfigTCP_MSS, 0 ) < 0 )
\r
334 } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < tcpechoSHUTDOWN_DELAY );
\r
336 /* Finished with the socket and the task. */
\r
337 FreeRTOS_closesocket( xConnectedSocket );
\r
338 vTaskDelete( NULL );
\r
340 /*-----------------------------------------------------------*/
\r
342 static BaseType_t prvCreateTxData( char *cBuffer, uint32_t ulBufferLength )
\r
344 BaseType_t lCharactersToAdd, lCharacter;
\r
347 /* Randomise the number of characters that will be sent. */
\r
350 lCharactersToAdd = ipconfigRAND32() % ( ulBufferLength - 20UL );
\r
351 } while ( lCharactersToAdd == 0 );
\r
353 /* Fill the buffer. */
\r
354 for( lCharacter = 0; lCharacter < lCharactersToAdd; lCharacter++ )
\r
356 cBuffer[ lCharacter ] = cChar;
\r
365 return lCharactersToAdd;
\r
367 /*-----------------------------------------------------------*/
\r
369 BaseType_t xAreTCPEchoServersStillRunning( void )
\r
371 static uint32_t ulLastConnectionCount = 0, ulLastClientCycles = 0;
\r
372 BaseType_t xReturn = pdPASS;
\r
374 if( ulConnectionCount == ulLastConnectionCount )
\r
380 ulLastConnectionCount = ulConnectionCount;
\r
383 if( ulClientCycles == ulLastClientCycles )
\r
389 ulLastClientCycles = ulClientCycles;
\r
394 /*-----------------------------------------------------------*/
\r
396 DWORD WINAPI prvSimpleWinsockTCPClientTask( void *pvParameters )
\r
398 char *pcTransmittedString, *pcReceivedString;
\r
399 BaseType_t lReceived, lTransmitted = 0, lStringLength, lReturned = 0, lInstance;
\r
400 uint32_t ulCount = 0UL, ulMaxCount, ulIPAddress;
\r
401 const uint32_t ulMaxLoopsPerSocket = 100UL;
\r
402 struct sockaddr_in xConnection;
\r
403 SOCKET xClientSocket;
\r
405 TickType_t xTimeOnShutdown;
\r
407 /* Multiple instances of this task are created. The instance is passed in
\r
408 as the parameter. */
\r
409 lInstance = ( BaseType_t ) pvParameters;
\r
411 /* Locate the buffers for this instance of this task. */
\r
412 pcTransmittedString = &( cTxBuffers[ lInstance ][ 0 ] );
\r
413 pcReceivedString = &( cRxBuffers[ lInstance ][ 0 ] );
\r
415 /* It is assumed that this task is not created until the network is up,
\r
416 so the IP address of the server (which is the FreeRTOS+TCP side of the
\r
417 connection) can be obtained immediately. Store the IP address being
\r
418 used in ulIPAddress. */
\r
419 FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL );
\r
421 /* Set family and port for client socket. */
\r
422 memset( ( void * ) &xConnection, 0x00, sizeof( struct sockaddr_in ) );
\r
423 xConnection.sin_family = AF_INET;
\r
424 xConnection.sin_addr.s_addr = ulIPAddress;
\r
425 xConnection.sin_port = htons( tcpechoPORT_NUMBER );
\r
429 /* Create the socket then connect it to the FreeRTOS+TCP server. */
\r
430 xClientSocket = socket( AF_INET, SOCK_STREAM, 0 );
\r
431 configASSERT( xClientSocket != INVALID_SOCKET );
\r
435 iReturned = connect( xClientSocket, (const struct sockaddr*) &xConnection, sizeof( xConnection ) );
\r
436 } while( iReturned != 0 );
\r
438 ulMaxCount = ipconfigRAND32() % ulMaxLoopsPerSocket;
\r
440 for( ulCount = 0; ulCount < ulMaxCount; ulCount++ )
\r
442 /* Create a string then send it to the server. */
\r
443 lStringLength = prvCreateTxData( pcTransmittedString, tcpechoBUFFER_SIZE );
\r
444 lTransmitted = send( xClientSocket, pcTransmittedString, lStringLength, 0 );
\r
446 configASSERT( lTransmitted != SOCKET_ERROR );
\r
447 configASSERT( lTransmitted == lStringLength );
\r
449 if( lTransmitted == lStringLength )
\r
451 memset( ( void * ) pcReceivedString, 0x00, tcpechoBUFFER_SIZE );
\r
454 /* Wait for the echoed string. */
\r
455 while( lReceived < lTransmitted )
\r
457 lReturned = recv( xClientSocket, ( char * ) &( pcReceivedString[ lReceived ] ), lTransmitted - lReceived, 0 );
\r
459 if( lReturned >= 0 )
\r
461 /* Data was received. */
\r
462 lReceived += lReturned;
\r
466 /* Error was returned. */
\r
467 ulClientReceiveErrors++;
\r
472 /* If the socket was not closed, check the number of bytes
\r
474 if( lReceived == lTransmitted )
\r
476 /* Were the expected characters received? */
\r
477 configASSERT( memcmp( pcTransmittedString, pcReceivedString, lTransmitted ) == 0x00 );
\r
478 if( memcmp( pcTransmittedString, pcReceivedString, lReceived ) != 0x00 )
\r
480 ulIncorrectDataReceived++;
\r
485 /* Received expected string, increment the count of
\r
486 successful cycles. */
\r
492 /* Socket is being closed or an error occurred. Don't try
\r
493 using the same socket again. */
\r
499 ulClientTransmitErrors++;
\r
504 shutdown( xClientSocket, SD_BOTH );
\r
505 xTimeOnShutdown = xTaskGetTickCount();
\r
509 Sleep( tcpechoWINSOCK_SHUTDOWN_DELAY );
\r
510 lReturned = recv( xClientSocket, pcReceivedString, lTransmitted, 0 );
\r
512 if( lReturned < 0 )
\r
516 } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < tcpechoSHUTDOWN_DELAY );
\r
518 configASSERT( closesocket( xClientSocket ) == 0 );
\r
520 Sleep( tcpechoLOOP_DELAY );
\r
523 /*-----------------------------------------------------------*/
\r
525 /* The whole file is excluded if TCP is not compiled in. */
\r
526 #endif /* ipconfigUSE_TCP */
\r