]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Demo/FreeRTOS_Plus_UDP_and_CLI_Windows_Simulator/DemoTasks/SimpleClientAndServer.c
fe31c468503d90491925436b3bc89be8d0928789
[freertos] / FreeRTOS-Plus / Demo / FreeRTOS_Plus_UDP_and_CLI_Windows_Simulator / DemoTasks / SimpleClientAndServer.c
1 /*\r
2     FreeRTOS V8.2.0rc1 - Copyright (C) 2014 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     >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
14     >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
15     >>!   obliged to provide the source code for proprietary components     !<<\r
16     >>!   outside of the FreeRTOS kernel.                                   !<<\r
17 \r
18     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
19     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
20     FOR A PARTICULAR PURPOSE.  Full license text is available on the following\r
21     link: http://www.freertos.org/a00114.html\r
22 \r
23     1 tab == 4 spaces!\r
24 \r
25     ***************************************************************************\r
26      *                                                                       *\r
27      *    Having a problem?  Start by reading the FAQ "My application does   *\r
28      *    not run, what could be wrong?".  Have you defined configASSERT()?  *\r
29      *                                                                       *\r
30      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
31      *                                                                       *\r
32     ***************************************************************************\r
33 \r
34     ***************************************************************************\r
35      *                                                                       *\r
36      *    FreeRTOS provides completely free yet professionally developed,    *\r
37      *    robust, strictly quality controlled, supported, and cross          *\r
38      *    platform software that is more than just the market leader, it     *\r
39      *    is the industry's de facto standard.                               *\r
40      *                                                                       *\r
41      *    Help yourself get started quickly while simultaneously helping     *\r
42      *    to support the FreeRTOS project by purchasing a FreeRTOS           *\r
43      *    tutorial book, reference manual, or both:                          *\r
44      *    http://www.FreeRTOS.org/Documentation                              *\r
45      *                                                                       *\r
46     ***************************************************************************\r
47 \r
48     ***************************************************************************\r
49      *                                                                       *\r
50      *   Investing in training allows your team to be as productive as       *\r
51      *   possible as early as possible, lowering your overall development    *\r
52      *   cost, and enabling you to bring a more robust product to market     *\r
53      *   earlier than would otherwise be possible.  Richard Barry is both    *\r
54      *   the architect and key author of FreeRTOS, and so also the world's   *\r
55      *   leading authority on what is the world's most popular real time     *\r
56      *   kernel for deeply embedded MCU designs.  Obtaining your training    *\r
57      *   from Richard ensures your team will gain directly from his in-depth *\r
58      *   product knowledge and years of usage experience.  Contact Real Time *\r
59      *   Engineers Ltd to enquire about the FreeRTOS Masterclass, presented  *\r
60      *   by Richard Barry:  http://www.FreeRTOS.org/contact\r
61      *                                                                       *\r
62     ***************************************************************************\r
63 \r
64     ***************************************************************************\r
65      *                                                                       *\r
66      *    You are receiving this top quality software for free.  Please play *\r
67      *    fair and reciprocate by reporting any suspected issues and         *\r
68      *    participating in the community forum:                              *\r
69      *    http://www.FreeRTOS.org/support                                    *\r
70      *                                                                       *\r
71      *    Thank you!                                                         *\r
72      *                                                                       *\r
73     ***************************************************************************\r
74 \r
75     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
76     license and Real Time Engineers Ltd. contact details.\r
77 \r
78     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
79     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
80     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
81 \r
82     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.\r
83     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.\r
84 \r
85     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
86     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
87     licenses offer ticketed support, indemnification and commercial middleware.\r
88 \r
89     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
90     engineered and independently SIL3 certified version for use in safety and\r
91     mission critical applications that require provable dependability.\r
92 \r
93     1 tab == 4 spaces!\r
94 */\r
95 \r
96 /*\r
97  * Creates two transmitting tasks and two receiving tasks.  The transmitting\r
98  * tasks send values that are received by the receiving tasks.  One set of tasks\r
99  * uses the standard API.  The other set of tasks uses the zero copy API.\r
100  */\r
101 \r
102 /* Standard includes. */\r
103 #include <stdint.h>\r
104 #include <stdio.h>\r
105 \r
106 /* FreeRTOS includes. */\r
107 #include "FreeRTOS.h"\r
108 #include "task.h"\r
109 \r
110 /* FreeRTOS+UDP includes. */\r
111 #include "FreeRTOS_UDP_IP.h"\r
112 #include "FreeRTOS_Sockets.h"\r
113 \r
114 #define simpTINY_DELAY  ( ( TickType_t ) 2 )\r
115 \r
116 /*\r
117  * Uses a socket to send data without using the zero copy option.\r
118  * prvSimpleServerTask() will receive the data.\r
119  */\r
120 static void prvSimpleClientTask( void *pvParameters );\r
121 \r
122 /*\r
123  * Uses a socket to receive the data sent by the prvSimpleClientTask() task.\r
124  * Does not use the zero copy option.\r
125  */\r
126 static void prvSimpleServerTask( void *pvParameters );\r
127 \r
128 /*\r
129  * Uses a socket to send data using the zero copy option.\r
130  * prvSimpleZeroCopyServerTask() will receive the data.\r
131  */\r
132 static void prvSimpleZeroCopyUDPClientTask( void *pvParameters );\r
133 \r
134 /*\r
135  * Uses a socket to receive the data sent by the prvSimpleZeroCopyUDPClientTask()\r
136  * task.  Uses the zero copy option.\r
137  */\r
138 static void prvSimpleZeroCopyServerTask( void *pvParameters );\r
139 \r
140 /*-----------------------------------------------------------*/\r
141 \r
142 void vStartSimpleUDPClientServerTasks( uint16_t usStackSize, uint32_t ulPort, UBaseType_t uxPriority )\r
143 {\r
144         /* Create the client and server tasks that do not use the zero copy\r
145         interface. */\r
146         xTaskCreate( prvSimpleClientTask, "SimpCpyClnt", usStackSize, ( void * ) ulPort, uxPriority, NULL );\r
147         xTaskCreate( prvSimpleServerTask, "SimpCpySrv", usStackSize, ( void * ) ulPort, uxPriority + 1, NULL );\r
148 \r
149         /* Create the client and server tasks that do use the zero copy interface. */\r
150         xTaskCreate( prvSimpleZeroCopyUDPClientTask, "SimpZCpyClnt", usStackSize, ( void * ) ( ulPort + 1 ), uxPriority, NULL );\r
151         xTaskCreate( prvSimpleZeroCopyServerTask, "SimpZCpySrv", usStackSize, ( void * ) ( ulPort + 1 ), uxPriority + 1, NULL );\r
152 }\r
153 /*-----------------------------------------------------------*/\r
154 \r
155 static void prvSimpleClientTask( void *pvParameters )\r
156 {\r
157 xSocket_t xClientSocket;\r
158 struct freertos_sockaddr xDestinationAddress;\r
159 char cString[ 50 ];\r
160 BaseType_t lReturned;\r
161 uint32_t ulCount = 0UL, ulIPAddress;\r
162 const uint32_t ulLoopsPerSocket = 10UL;\r
163 const TickType_t x150ms = 150UL / portTICK_RATE_MS;\r
164 \r
165         /* Remove compiler warning about unused parameters. */\r
166         ( void ) pvParameters;\r
167 \r
168         /* It is assumed that this task is not created until the network is up,\r
169         so the IP address can be obtained immediately.  store the IP address being\r
170         used in ulIPAddress.  This is done so the socket can send to a different\r
171         port on the same IP address. */\r
172         FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL );\r
173 \r
174         /* This test sends to itself, so data sent from here is received by a server\r
175         socket on the same IP address.  Setup the freertos_sockaddr structure with\r
176         this nodes IP address, and the port number being sent to.  The strange\r
177         casting is to try and remove compiler warnings on 32 bit machines. */\r
178         xDestinationAddress.sin_addr = ulIPAddress;\r
179         xDestinationAddress.sin_port = ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL;\r
180         xDestinationAddress.sin_port = FreeRTOS_htons( xDestinationAddress.sin_port );\r
181 \r
182         for( ;; )\r
183         {\r
184                 /* Create the socket. */\r
185                 xClientSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
186                 configASSERT( xClientSocket != FREERTOS_INVALID_SOCKET );\r
187 \r
188                 /* The count is used to differentiate between different messages sent to\r
189                 the server, and to break out of the do while loop below. */\r
190                 ulCount = 0UL;\r
191 \r
192                 do\r
193                 {\r
194                         /* Create the string that is sent to the server. */\r
195                         sprintf( cString, "Server received (not zero copy): Message number %lu\r\n", ulCount );\r
196 \r
197                         /* Send the string to the socket.  ulFlags is set to 0, so the zero\r
198                         copy option is not selected.  That means the data from cString[] is\r
199                         copied into a network buffer inside FreeRTOS_sendto(), and cString[]\r
200                         can be reused as soon as FreeRTOS_sendto() has returned. */\r
201                         lReturned = FreeRTOS_sendto( xClientSocket, ( void * ) cString, strlen( cString ), 0, &xDestinationAddress, sizeof( xDestinationAddress ) );\r
202 \r
203                         ulCount++;\r
204 \r
205                 } while( ( lReturned != FREERTOS_SOCKET_ERROR ) && ( ulCount < ulLoopsPerSocket ) );\r
206 \r
207                 FreeRTOS_closesocket( xClientSocket );\r
208 \r
209                 /* A short delay to prevent the messages printed by the server task\r
210                 scrolling off the screen too quickly, and to prevent reduce the network\r
211                 loading. */\r
212                 vTaskDelay( x150ms );\r
213         }\r
214 }\r
215 /*-----------------------------------------------------------*/\r
216 \r
217 static void prvSimpleServerTask( void *pvParameters )\r
218 {\r
219 long lBytes;\r
220 char cReceivedString[ 60 ];\r
221 struct freertos_sockaddr xClient, xBindAddress;\r
222 uint32_t xClientLength = sizeof( xClient );\r
223 xSocket_t xListeningSocket;\r
224 \r
225         /* Just to prevent compiler warnings. */\r
226         ( void ) pvParameters;\r
227 \r
228         /* Attempt to open the socket. */\r
229         xListeningSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
230         configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET );\r
231 \r
232         /* This test receives data sent from a different port on the same IP\r
233         address.  Configure the freertos_sockaddr structure with the address being\r
234         bound to.  The strange casting is to try and remove     compiler warnings on 32\r
235         bit machines.  Note that this task is only created after the network is up,\r
236         so the IP address is valid here. */\r
237         xBindAddress.sin_port = ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL;\r
238         xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port );\r
239 \r
240         /* Bind the socket to the port that the client task will send to. */\r
241         FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) );\r
242 \r
243         for( ;; )\r
244         {\r
245                 /* Zero out the receive array so there is NULL at the end of the string\r
246                 when it is printed out. */\r
247                 memset( cReceivedString, 0x00, sizeof( cReceivedString ) );\r
248 \r
249                 /* Receive data on the socket.  ulFlags is zero, so the zero copy option\r
250                 is not set and the received data is copied into the buffer pointed to by\r
251                 cReceivedString.  By default the block time is portMAX_DELAY.\r
252                 xClientLength is not actually used by FreeRTOS_recvfrom(), but is set\r
253                 appropriately in case future versions do use it. */\r
254                 lBytes = FreeRTOS_recvfrom( xListeningSocket, cReceivedString, sizeof( cReceivedString ), 0, &xClient, &xClientLength );\r
255 \r
256                 /* Print the received characters. */\r
257                 if( lBytes > 0 )\r
258                 {\r
259                         vOutputString( cReceivedString );\r
260                 }\r
261 \r
262                 /* Error check. */\r
263                 configASSERT( lBytes == ( BaseType_t ) strlen( cReceivedString ) );\r
264         }\r
265 }\r
266 /*-----------------------------------------------------------*/\r
267 \r
268 static void prvSimpleZeroCopyUDPClientTask( void *pvParameters )\r
269 {\r
270 xSocket_t xClientSocket;\r
271 uint8_t *pucUDPPayloadBuffer;\r
272 struct freertos_sockaddr xDestinationAddress;\r
273 BaseType_t lReturned;\r
274 uint32_t ulCount = 0UL, ulIPAddress;\r
275 const uint32_t ulLoopsPerSocket = 10UL;\r
276 const char *pcStringToSend = "Server received (using zero copy): Message number ";\r
277 const TickType_t x150ms = 150UL / portTICK_RATE_MS;\r
278 /* 15 is added to ensure the number, \r\n and terminating zero fit. */\r
279 const size_t xStringLength = strlen( pcStringToSend ) + 15;\r
280 \r
281         /* Remove compiler warning about unused parameters. */\r
282         ( void ) pvParameters;\r
283 \r
284         /* It is assumed that this task is not created until the network is up,\r
285         so the IP address can be obtained immediately.  store the IP address being\r
286         used in ulIPAddress.  This is done so the socket can send to a different\r
287         port on the same IP address. */\r
288         FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL );\r
289 \r
290         /* This test sends to itself, so data sent from here is received by a server\r
291         socket on the same IP address.  Setup the freertos_sockaddr structure with\r
292         this nodes IP address, and the port number being sent to.  The strange\r
293         casting is to try and remove compiler warnings on 32 bit machines. */\r
294         xDestinationAddress.sin_addr = ulIPAddress;\r
295         xDestinationAddress.sin_port = ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL;\r
296         xDestinationAddress.sin_port = FreeRTOS_htons( xDestinationAddress.sin_port );\r
297 \r
298         for( ;; )\r
299         {\r
300                 /* Create the socket. */\r
301                 xClientSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
302                 configASSERT( xClientSocket != FREERTOS_INVALID_SOCKET );\r
303 \r
304                 /* The count is used to differentiate between different messages sent to\r
305                 the server, and to break out of the do while loop below. */\r
306                 ulCount = 0UL;\r
307 \r
308                 do\r
309                 {\r
310                         /* This task is going to send using the zero copy interface.  The\r
311                         data being sent is therefore written directly into a buffer that is\r
312                         passed into, rather than copied into, the FreeRTOS_sendto()\r
313                         function.\r
314 \r
315                         First obtain a buffer of adequate length from the IP stack into which\r
316                         the string will be written.  Although a max delay is used, the actual\r
317                         delay will be capped to ipconfigMAX_SEND_BLOCK_TIME_TICKS, hence\r
318                         the do while loop is used to ensure a buffer is obtained. */\r
319                         do\r
320                         {\r
321                         } while( ( pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( xStringLength, portMAX_DELAY ) ) == NULL );\r
322 \r
323                         /* A buffer was successfully obtained.  Create the string that is\r
324                         sent to the server.  First the string is filled with zeros as this will\r
325                         effectively be the null terminator when the string is received at the other\r
326                         end.  Note that the string is being written directly into the buffer\r
327                         obtained from the IP stack above. */\r
328                         memset( ( void * ) pucUDPPayloadBuffer, 0x00, xStringLength );\r
329                         sprintf( ( char * ) pucUDPPayloadBuffer, "%s%lu\r\n", pcStringToSend, ulCount );\r
330 \r
331                         /* Pass the buffer into the send function.  ulFlags has the\r
332                         FREERTOS_ZERO_COPY bit set so the IP stack will take control of the\r
333                         buffer rather than copy data out of the buffer. */\r
334                         lReturned = FreeRTOS_sendto( xClientSocket,                             /* The socket being sent to. */\r
335                                                                                 ( void * ) pucUDPPayloadBuffer, /* A pointer to the the data being sent. */\r
336                                                                                 strlen( ( const char * ) pucUDPPayloadBuffer ) + 1, /* The length of the data being sent - including the string's null terminator. */\r
337                                                                                 FREERTOS_ZERO_COPY,                     /* ulFlags with the FREERTOS_ZERO_COPY bit set. */\r
338                                                                                 &xDestinationAddress,                   /* Where the data is being sent. */\r
339                                                                                 sizeof( xDestinationAddress ) );\r
340 \r
341                         if( lReturned == 0 )\r
342                         {\r
343                                 /* The send operation failed, so this task is still responsible\r
344                                 for the buffer obtained from the IP stack.  To ensure the buffer\r
345                                 is not lost it must either be used again, or, as in this case,\r
346                                 returned to the IP stack using FreeRTOS_ReleaseUDPPayloadBuffer().\r
347                                 pucUDPPayloadBuffer can be safely re-used after this call. */\r
348                                 FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );\r
349                         }\r
350                         else\r
351                         {\r
352                                 /* The send was successful so the IP stack is now managing the\r
353                                 buffer pointed to by pucUDPPayloadBuffer, and the IP stack will\r
354                                 return the buffer once it has been sent.  pucUDPPayloadBuffer can\r
355                                 be safely re-used. */\r
356                         }\r
357 \r
358                         ulCount++;\r
359 \r
360                 } while( ( lReturned != FREERTOS_SOCKET_ERROR ) && ( ulCount < ulLoopsPerSocket ) );\r
361 \r
362                 FreeRTOS_closesocket( xClientSocket );\r
363 \r
364                 /* A short delay to prevent the messages scrolling off the screen too\r
365                 quickly. */\r
366                 vTaskDelay( x150ms );\r
367         }\r
368 }\r
369 /*-----------------------------------------------------------*/\r
370 \r
371 static void prvSimpleZeroCopyServerTask( void *pvParameters )\r
372 {\r
373 int32_t lBytes;\r
374 uint8_t *pucUDPPayloadBuffer;\r
375 struct freertos_sockaddr xClient, xBindAddress;\r
376 uint32_t xClientLength = sizeof( xClient ), ulIPAddress;\r
377 xSocket_t xListeningSocket;\r
378 \r
379         /* Just to prevent compiler warnings. */\r
380         ( void ) pvParameters;\r
381 \r
382         /* Attempt to open the socket. */\r
383         xListeningSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
384         configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET );\r
385 \r
386         /* This test receives data sent from a different port on the same IP address.\r
387         Obtain the nodes IP address.  Configure the freertos_sockaddr structure with\r
388         the address being bound to.  The strange casting is to try and remove\r
389         compiler warnings on 32 bit machines.  Note that this task is only created\r
390         after the network is up, so the IP address is valid here. */\r
391         FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL );\r
392         xBindAddress.sin_addr = ulIPAddress;\r
393         xBindAddress.sin_port = ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL;\r
394         xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port );\r
395 \r
396         /* Bind the socket to the port that the client task will send to. */\r
397         FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) );\r
398 \r
399         for( ;; )\r
400         {\r
401                 /* Receive data on the socket.  ulFlags has the zero copy bit set\r
402                 (FREERTOS_ZERO_COPY) indicating to the stack that a reference to the\r
403                 received data should be passed out to this task using the second\r
404                 parameter to the FreeRTOS_recvfrom() call.  When this is done the\r
405                 IP stack is no longer responsible for releasing the buffer, and\r
406                 the task *must* return the buffer to the stack when it is no longer\r
407                 needed.  By default the block time is portMAX_DELAY. */\r
408                 lBytes = FreeRTOS_recvfrom( xListeningSocket, ( void * ) &pucUDPPayloadBuffer, 0, FREERTOS_ZERO_COPY, &xClient, &xClientLength );\r
409 \r
410                 /* It is expected to receive one more byte than the string length as\r
411                 the NULL terminator is also transmitted. */\r
412                 configASSERT( lBytes == ( ( BaseType_t ) strlen( ( const char * ) pucUDPPayloadBuffer ) + 1 ) );\r
413 \r
414                 /* Print the received characters. */\r
415                 if( lBytes > 0 )\r
416                 {\r
417                         vOutputString( ( char * ) pucUDPPayloadBuffer );\r
418                 }\r
419 \r
420                 if( lBytes >= 0 )\r
421                 {\r
422                         /* The buffer *must* be freed once it is no longer needed. */\r
423                         FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer );\r
424                 }\r
425         }\r
426 }\r
427 \r