]> git.sur5r.net Git - freertos/blob - FreeRTOS-Labs/Demo/Common/FreeRTOS_Plus_TCP_Demos/SimpleTCPEchoServer.c
Add the Labs projects provided in the V10.2.1_191129 zip file.
[freertos] / FreeRTOS-Labs / Demo / Common / FreeRTOS_Plus_TCP_Demos / SimpleTCPEchoServer.c
1 /*\r
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.\r
3     All rights reserved\r
4 \r
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     This file is part of the FreeRTOS distribution.\r
8 \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
12 \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
19 \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
24 \r
25     ***************************************************************************\r
26      *                                                                       *\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
31      *                                                                       *\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
36      *                                                                       *\r
37     ***************************************************************************\r
38 \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
42 \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
46 \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
51 \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
55 \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
58 \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
62 \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
66 \r
67     1 tab == 4 spaces!\r
68 */\r
69 \r
70 /*\r
71  * FreeRTOS tasks are used with FreeRTOS+TCP to create a TCP echo server on the\r
72  * standard echo port number (7).\r
73  *\r
74  * See the following web page for essential demo usage and configuration\r
75  * details:\r
76  * http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_Echo_Server.html\r
77  */\r
78 \r
79 /* Standard includes. */\r
80 #include <stdint.h>\r
81 #include <stdio.h>\r
82 \r
83 /* FreeRTOS includes. */\r
84 #include "FreeRTOS.h"\r
85 #include "task.h"\r
86 #include "semphr.h"\r
87 \r
88 /* FreeRTOS+TCP includes. */\r
89 #include "FreeRTOS_IP.h"\r
90 #include "FreeRTOS_Sockets.h"\r
91 \r
92 /* Remove the whole file if FreeRTOSIPConfig.h is set to exclude TCP. */\r
93 #if( ipconfigUSE_TCP == 1 )\r
94 \r
95 /* The maximum time to wait for a closing socket to close. */\r
96 #define tcpechoSHUTDOWN_DELAY   ( pdMS_TO_TICKS( 5000 ) )\r
97 \r
98 /* The standard echo port number. */\r
99 #define tcpechoPORT_NUMBER              7\r
100 \r
101 /* If ipconfigUSE_TCP_WIN is 1 then the Tx sockets will use a buffer size set by\r
102 ipconfigTCP_TX_BUFFER_LENGTH, and the Tx window size will be\r
103 configECHO_SERVER_TX_WINDOW_SIZE times the buffer size.  Note\r
104 ipconfigTCP_TX_BUFFER_LENGTH is set in FreeRTOSIPConfig.h as it is a standard TCP/IP\r
105 stack constant, whereas configECHO_SERVER_TX_WINDOW_SIZE is set in\r
106 FreeRTOSConfig.h as it is a demo application constant. */\r
107 #ifndef configECHO_SERVER_TX_WINDOW_SIZE\r
108         #define configECHO_SERVER_TX_WINDOW_SIZE        2\r
109 #endif\r
110 \r
111 /* If ipconfigUSE_TCP_WIN is 1 then the Rx sockets will use a buffer size set by\r
112 ipconfigTCP_RX_BUFFER_LENGTH, and the Rx window size will be\r
113 configECHO_SERVER_RX_WINDOW_SIZE times the buffer size.  Note\r
114 ipconfigTCP_RX_BUFFER_LENGTH is set in FreeRTOSIPConfig.h as it is a standard TCP/IP\r
115 stack constant, whereas configECHO_SERVER_RX_WINDOW_SIZE is set in\r
116 FreeRTOSConfig.h as it is a demo application constant. */\r
117 #ifndef configECHO_SERVER_RX_WINDOW_SIZE\r
118         #define configECHO_SERVER_RX_WINDOW_SIZE        2\r
119 #endif\r
120 \r
121 /*-----------------------------------------------------------*/\r
122 \r
123 /*\r
124  * Uses FreeRTOS+TCP to listen for incoming echo connections, creating a task\r
125  * to handle each connection.\r
126  */\r
127 static void prvConnectionListeningTask( void *pvParameters );\r
128 \r
129 /*\r
130  * Created by the connection listening task to handle a single connection.\r
131  */\r
132 static void prvServerConnectionInstance( void *pvParameters );\r
133 \r
134 /*-----------------------------------------------------------*/\r
135 \r
136 /* Stores the stack size passed into vStartSimpleTCPServerTasks() so it can be\r
137 reused when the server listening task creates tasks to handle connections. */\r
138 static uint16_t usUsedStackSize = 0;\r
139 \r
140 /*-----------------------------------------------------------*/\r
141 \r
142 void vStartSimpleTCPServerTasks( uint16_t usStackSize, UBaseType_t uxPriority )\r
143 {\r
144         /* Create the TCP echo server. */\r
145         xTaskCreate( prvConnectionListeningTask, "ServerListener", usStackSize, NULL, uxPriority + 1, NULL );\r
146 \r
147         /* Remember the requested stack size so it can be re-used by the server\r
148         listening task when it creates tasks to handle connections. */\r
149         usUsedStackSize = usStackSize;\r
150 }\r
151 /*-----------------------------------------------------------*/\r
152 \r
153 static void prvConnectionListeningTask( void *pvParameters )\r
154 {\r
155 struct freertos_sockaddr xClient, xBindAddress;\r
156 Socket_t xListeningSocket, xConnectedSocket;\r
157 socklen_t xSize = sizeof( xClient );\r
158 static const TickType_t xReceiveTimeOut = portMAX_DELAY;\r
159 const BaseType_t xBacklog = 20;\r
160 \r
161 #if( ipconfigUSE_TCP_WIN == 1 )\r
162         WinProperties_t xWinProps;\r
163 \r
164         /* Fill in the buffer and window sizes that will be used by the socket. */\r
165         xWinProps.lTxBufSize = ipconfigTCP_TX_BUFFER_LENGTH;\r
166         xWinProps.lTxWinSize = configECHO_SERVER_TX_WINDOW_SIZE;\r
167         xWinProps.lRxBufSize = ipconfigTCP_RX_BUFFER_LENGTH;\r
168         xWinProps.lRxWinSize = configECHO_SERVER_RX_WINDOW_SIZE;\r
169 #endif /* ipconfigUSE_TCP_WIN */\r
170 \r
171         /* Just to prevent compiler warnings. */\r
172         ( void ) pvParameters;\r
173 \r
174         /* Attempt to open the socket. */\r
175         xListeningSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );\r
176         configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET );\r
177 \r
178         /* Set a time out so accept() will just wait for a connection. */\r
179         FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );\r
180 \r
181         /* Set the window and buffer sizes. */\r
182         #if( ipconfigUSE_TCP_WIN == 1 )\r
183         {\r
184                 FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) );\r
185         }\r
186         #endif /* ipconfigUSE_TCP_WIN */\r
187 \r
188         /* Bind the socket to the port that the client task will send to, then\r
189         listen for incoming connections. */\r
190         xBindAddress.sin_port = tcpechoPORT_NUMBER;\r
191         xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port );\r
192         FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) );\r
193         FreeRTOS_listen( xListeningSocket, xBacklog );\r
194 \r
195         for( ;; )\r
196         {\r
197                 /* Wait for a client to connect. */\r
198                 xConnectedSocket = FreeRTOS_accept( xListeningSocket, &xClient, &xSize );\r
199                 configASSERT( xConnectedSocket != FREERTOS_INVALID_SOCKET );\r
200 \r
201                 /* Spawn a task to handle the connection. */\r
202                 xTaskCreate( prvServerConnectionInstance, "EchoServer", usUsedStackSize, ( void * ) xConnectedSocket, tskIDLE_PRIORITY, NULL );\r
203         }\r
204 }\r
205 /*-----------------------------------------------------------*/\r
206 \r
207 static void prvServerConnectionInstance( void *pvParameters )\r
208 {\r
209 int32_t lBytes, lSent, lTotalSent;\r
210 Socket_t xConnectedSocket;\r
211 static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );\r
212 static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 5000 );\r
213 TickType_t xTimeOnShutdown;\r
214 uint8_t *pucRxBuffer;\r
215 \r
216         xConnectedSocket = ( Socket_t ) pvParameters;\r
217 \r
218         /* Attempt to create the buffer used to receive the string to be echoed\r
219         back.  This could be avoided using a zero copy interface that just returned\r
220         the same buffer. */\r
221         pucRxBuffer = ( uint8_t * ) pvPortMalloc( ipconfigTCP_MSS );\r
222 \r
223         if( pucRxBuffer != NULL )\r
224         {\r
225                 FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );\r
226                 FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xReceiveTimeOut ) );\r
227 \r
228                 for( ;; )\r
229                 {\r
230                         /* Zero out the receive array so there is NULL at the end of the string\r
231                         when it is printed out. */\r
232                         memset( pucRxBuffer, 0x00, ipconfigTCP_MSS );\r
233 \r
234                         /* Receive data on the socket. */\r
235                         lBytes = FreeRTOS_recv( xConnectedSocket, pucRxBuffer, ipconfigTCP_MSS, 0 );\r
236 \r
237                         /* If data was received, echo it back. */\r
238                         if( lBytes >= 0 )\r
239                         {\r
240                                 lSent = 0;\r
241                                 lTotalSent = 0;\r
242 \r
243                                 /* Call send() until all the data has been sent. */\r
244                                 while( ( lSent >= 0 ) && ( lTotalSent < lBytes ) )\r
245                                 {\r
246                                         lSent = FreeRTOS_send( xConnectedSocket, pucRxBuffer, lBytes - lTotalSent, 0 );\r
247                                         lTotalSent += lSent;\r
248                                 }\r
249 \r
250                                 if( lSent < 0 )\r
251                                 {\r
252                                         /* Socket closed? */\r
253                                         break;\r
254                                 }\r
255                         }\r
256                         else\r
257                         {\r
258                                 /* Socket closed? */\r
259                                 break;\r
260                         }\r
261                 }\r
262         }\r
263 \r
264         /* Initiate a shutdown in case it has not already been initiated. */\r
265         FreeRTOS_shutdown( xConnectedSocket, FREERTOS_SHUT_RDWR );\r
266 \r
267         /* Wait for the shutdown to take effect, indicated by FreeRTOS_recv()\r
268         returning an error. */\r
269         xTimeOnShutdown = xTaskGetTickCount();\r
270         do\r
271         {\r
272                 if( FreeRTOS_recv( xConnectedSocket, pucRxBuffer, ipconfigTCP_MSS, 0 ) < 0 )\r
273                 {\r
274                         break;\r
275                 }\r
276         } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < tcpechoSHUTDOWN_DELAY );\r
277 \r
278         /* Finished with the socket, buffer, the task. */\r
279         vPortFree( pucRxBuffer );\r
280         FreeRTOS_closesocket( xConnectedSocket );\r
281 \r
282         vTaskDelete( NULL );\r
283 }\r
284 /*-----------------------------------------------------------*/\r
285 \r
286 /* The whole file is excluded if TCP is not compiled in. */\r
287 #endif /* ipconfigUSE_TCP */\r
288 \r