]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Demo/Common/FreeRTOS_Plus_UDP_Demos/EchoClients/TwoEchoClients.c
692c2ebc39378447c5dc62b570ad25f6162d9364
[freertos] / FreeRTOS-Plus / Demo / Common / FreeRTOS_Plus_UDP_Demos / EchoClients / TwoEchoClients.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 /******************************************************************************\r
98  *\r
99  * See the following web page for essential TwoEchoClient.c usage and\r
100  * configuration details:\r
101  * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/Embedded_Ethernet_Examples/Common_Echo_Clients.shtml\r
102  *\r
103  ******************************************************************************/\r
104 \r
105 \r
106 /* Standard includes. */\r
107 #include <stdint.h>\r
108 #include <stdio.h>\r
109 #include <stdlib.h>\r
110 \r
111 /* FreeRTOS includes. */\r
112 #include "FreeRTOS.h"\r
113 #include "task.h"\r
114 \r
115 /* FreeRTOS+UDP includes. */\r
116 #include "FreeRTOS_UDP_IP.h"\r
117 #include "FreeRTOS_Sockets.h"\r
118 \r
119 /* Small delay used between attempts to obtain a zero copy buffer. */\r
120 #define echoTINY_DELAY  ( ( TickType_t ) 2 )\r
121 \r
122 /* The echo tasks create a socket, send out a number of echo requests\r
123 (listening for each echo reply), then close the socket again before\r
124 starting over.  This delay is used between each iteration to ensure the\r
125 network does not get too congested. */\r
126 #define echoLOOP_DELAY  ( ( TickType_t ) 250 / portTICK_RATE_MS )\r
127 \r
128 #if ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1\r
129         /* When the trace recorder code is included user events are generated to\r
130         mark the sending and receiving of the echoed data (only in the zero copy\r
131         task. */\r
132         #define echoMARK_SEND_IN_TRACE_BUFFER( x ) vTraceUserEvent( x )\r
133         traceLabel xZeroCopySendEvent, xZeroCopyReceiveEvent;\r
134 \r
135 #else\r
136         /* When the trace recorder code is not included just #define away the call\r
137         to post the user event. */\r
138         #define echoMARK_SEND_IN_TRACE_BUFFER( x )\r
139         #define xZeroCopySendEvent 0\r
140         #define xZeroCopyReceiveEvent 0\r
141 #endif\r
142 \r
143 /* The echo server is assumed to be on port 7, which is the standard echo\r
144 protocol port. */\r
145 #define echoECHO_PORT   ( 7 )\r
146 \r
147 /*\r
148  * Uses a socket to send data to, then receive data from, the standard echo\r
149  * port number 7.  prvEchoClientTask() uses the standard interface.\r
150  * prvZeroCopyEchoClientTask() uses the zero copy interface.\r
151  */\r
152 static void prvEchoClientTask( void *pvParameters );\r
153 static void prvZeroCopyEchoClientTask( void *pvParameters );\r
154 \r
155 /* The receive timeout is set shorter when the windows simulator is used\r
156 because simulated time is slower than real time. */\r
157 #ifdef _WINDOWS_\r
158         const TickType_t xReceiveTimeOut = 50 / portTICK_RATE_MS;\r
159 #else\r
160         const TickType_t xReceiveTimeOut = 500 / portTICK_RATE_MS;\r
161 #endif\r
162 \r
163 /*-----------------------------------------------------------*/\r
164 \r
165 void vStartEchoClientTasks( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority )\r
166 {\r
167         /* Create the echo client task that does not use the zero copy interface. */\r
168         xTaskCreate(    prvEchoClientTask,      /* The function that implements the task. */\r
169                                         "Echo0",                        /* Just a text name for the task to aid debugging. */\r
170                                         usTaskStackSize,        /* The stack size is defined in FreeRTOSIPConfig.h. */\r
171                                         NULL,                           /* The task parameter, not used in this case. */\r
172                                         uxTaskPriority,         /* The priority assigned to the task is defined in FreeRTOSConfig.h. */\r
173                                         NULL );                         /* The task handle is not used. */\r
174 \r
175         /* Create the echo client task that does use the zero copy interface. */\r
176         xTaskCreate(    prvZeroCopyEchoClientTask,      /* The function that implements the task. */\r
177                                         "Echo1",                                        /* Just a text name for the task to aid debugging. */\r
178                                         usTaskStackSize,                        /* The stack size is defined in FreeRTOSIPConfig.h. */\r
179                                         NULL,                                           /* The task parameter, not used in this case. */\r
180                                         uxTaskPriority,                         /* The priority assigned to the task is defined in FreeRTOSConfig.h. */\r
181                                         NULL );                                         /* The task handle is not used. */\r
182 }\r
183 /*-----------------------------------------------------------*/\r
184 \r
185 static void prvEchoClientTask( void *pvParameters )\r
186 {\r
187 xSocket_t xSocket;\r
188 struct freertos_sockaddr xEchoServerAddress;\r
189 char cTxString[ 25 ], cRxString[ 25 ]; /* Make sure the stack is large enough to hold these.  Turn on stack overflow checking during debug to be sure. */\r
190 int32_t lLoopCount = 0UL;\r
191 const int32_t lMaxLoopCount = 50;\r
192 volatile uint32_t ulRxCount = 0UL, ulTxCount = 0UL;\r
193 uint32_t xAddressLength = sizeof( xEchoServerAddress );\r
194 \r
195         /* Remove compiler warning about unused parameters. */\r
196         ( void ) pvParameters;\r
197 \r
198         /* Echo requests are sent to the echo server.  The address of the echo\r
199         server is configured by the constants configECHO_SERVER_ADDR0 to\r
200         configECHO_SERVER_ADDR3 in FreeRTOSConfig.h. */\r
201         xEchoServerAddress.sin_port = FreeRTOS_htons( echoECHO_PORT );\r
202         xEchoServerAddress.sin_addr = FreeRTOS_inet_addr_quick( configECHO_SERVER_ADDR0,\r
203                                                                                                                         configECHO_SERVER_ADDR1,\r
204                                                                                                                         configECHO_SERVER_ADDR2,\r
205                                                                                                                         configECHO_SERVER_ADDR3 );\r
206 \r
207         for( ;; )\r
208         {\r
209                 /* Create a socket. */\r
210                 xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
211                 configASSERT( xSocket != FREERTOS_INVALID_SOCKET );\r
212 \r
213                 /* Set a time out so a missing reply does not cause the task to block\r
214                 indefinitely. */\r
215                 FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );\r
216 \r
217                 /* Send a number of echo requests. */\r
218                 for( lLoopCount = 0; lLoopCount < lMaxLoopCount; lLoopCount++ )\r
219                 {\r
220                         /* Create the string that is sent to the echo server. */\r
221                         sprintf( cTxString, "Message number %u\r\n", ( unsigned int ) ulTxCount );\r
222 \r
223                         /* Send the string to the socket.  ulFlags is set to 0, so the zero\r
224                         copy interface is not used.  That means the data from cTxString is\r
225                         copied into a network buffer inside FreeRTOS_sendto(), and cTxString\r
226                         can be reused as soon as FreeRTOS_sendto() has returned.  1 is added\r
227                         to ensure the NULL string terminator is sent as part of the message. */\r
228                         FreeRTOS_sendto( xSocket,                               /* The socket being sent to. */\r
229                                                         ( void * ) cTxString,   /* The data being sent. */\r
230                                                         strlen( cTxString ) + 1,/* The length of the data being sent. */\r
231                                                         0,                                              /* ulFlags with the FREERTOS_ZERO_COPY bit clear. */\r
232                                                         &xEchoServerAddress,    /* The destination address. */\r
233                                                         sizeof( xEchoServerAddress ) );\r
234 \r
235                         /* Keep a count of how many echo requests have been transmitted so\r
236                         it can be compared to the number of echo replies received.  It would\r
237                         be expected to loose at least one to an ARP message the first time\r
238                         the     connection is created. */\r
239                         ulTxCount++;\r
240 \r
241                         /* Receive data echoed back to the socket.  ulFlags is zero, so the\r
242                         zero copy option is not being used and the received data will be\r
243                         copied into the buffer pointed to by cRxString.  xAddressLength is\r
244                         not actually used (at the time of writing this comment, anyway) by\r
245                         FreeRTOS_recvfrom(), but is set appropriately in case future\r
246                         versions do use it. */\r
247                         memset( ( void * ) cRxString, 0x00, sizeof( cRxString ) );\r
248                         FreeRTOS_recvfrom(      xSocket,                                /* The socket being received from. */\r
249                                                                 cRxString,                              /* The buffer into which the received data will be written. */\r
250                                                                 sizeof( cRxString ),    /* The size of the buffer provided to receive the data. */\r
251                                                                 0,                                              /* ulFlags with the FREERTOS_ZERO_COPY bit clear. */\r
252                                                                 &xEchoServerAddress,    /* The address from where the data was sent (the source address). */\r
253                                                                 &xAddressLength );\r
254 \r
255                         /* Compare the transmitted string to the received string. */\r
256                         if( strcmp( cRxString, cTxString ) == 0 )\r
257                         {\r
258                                 /* The echo reply was received without error. */\r
259                                 ulRxCount++;\r
260                         }\r
261                 };\r
262 \r
263                 /* Pause for a short while to ensure the network is not too\r
264                 congested. */\r
265                 vTaskDelay( echoLOOP_DELAY );\r
266 \r
267                 /* Close this socket before looping back to create another. */\r
268                 FreeRTOS_closesocket( xSocket );\r
269         }\r
270 }\r
271 /*-----------------------------------------------------------*/\r
272 \r
273 static void prvZeroCopyEchoClientTask( void *pvParameters )\r
274 {\r
275 xSocket_t xSocket;\r
276 struct freertos_sockaddr xEchoServerAddress;\r
277 static char cTxString[ 40 ];\r
278 int32_t lLoopCount = 0UL;\r
279 volatile uint32_t ulRxCount = 0UL, ulTxCount = 0UL;\r
280 uint32_t xAddressLength = sizeof( xEchoServerAddress );\r
281 int32_t lReturned;\r
282 uint8_t *pucUDPPayloadBuffer;\r
283 \r
284 const int32_t lMaxLoopCount = 50;\r
285 const char * const pcStringToSend = "Zero copy message number";\r
286 /* The buffer is large enough to hold the string, a number, and the string terminator. */\r
287 const size_t xBufferLength = strlen( pcStringToSend ) + 15;\r
288 \r
289         #if ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1\r
290         {\r
291                 /* When the trace recorder code is included user events are generated to\r
292                 mark the sending and receiving of the echoed data (only in the zero copy\r
293                 task). */\r
294                 xZeroCopySendEvent = xTraceOpenLabel( "ZeroCopyTx" );\r
295                 xZeroCopyReceiveEvent = xTraceOpenLabel( "ZeroCopyRx" );\r
296         }\r
297         #endif /* ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS */\r
298 \r
299         /* Remove compiler warning about unused parameters. */\r
300         ( void ) pvParameters;\r
301 \r
302         /* Delay for a little while to ensure the task is out of synch with the\r
303         other echo task implemented above. */\r
304         vTaskDelay( echoLOOP_DELAY >> 1 );\r
305 \r
306         /* Echo requests are sent to the echo server.  The address of the echo\r
307         server is configured by the constants configECHO_SERVER_ADDR0 to\r
308         configECHO_SERVER_ADDR3 in FreeRTOSConfig.h. */\r
309         xEchoServerAddress.sin_port = FreeRTOS_htons( echoECHO_PORT );\r
310         xEchoServerAddress.sin_addr = FreeRTOS_inet_addr_quick( configECHO_SERVER_ADDR0,\r
311                                                                                                                         configECHO_SERVER_ADDR1,\r
312                                                                                                                         configECHO_SERVER_ADDR2,\r
313                                                                                                                         configECHO_SERVER_ADDR3 );\r
314 \r
315         for( ;; )\r
316         {\r
317                 /* Create a socket. */\r
318                 xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );\r
319                 configASSERT( xSocket != FREERTOS_INVALID_SOCKET );\r
320 \r
321                 /* Set a time out so a missing reply does not cause the task to block\r
322                 indefinitely. */\r
323                 FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );\r
324 \r
325                 /* Send a number of echo requests. */\r
326                 for( lLoopCount = 0; lLoopCount < lMaxLoopCount; lLoopCount++ )\r
327                 {\r
328                         /* This task is going to send using the zero copy interface.  The\r
329                         data being sent is therefore written directly into a buffer that is\r
330                         passed by reference into the FreeRTOS_sendto() function.  First\r
331                         obtain a buffer of adequate size from the IP stack.  Although a max\r
332                         delay is used, the actual delay will be capped to\r
333                         ipconfigMAX_SEND_BLOCK_TIME_TICKS, hence the test to ensure a buffer\r
334                         was actually obtained. */\r
335                         pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( xBufferLength, portMAX_DELAY );\r
336 \r
337                         if( pucUDPPayloadBuffer != NULL )\r
338                         {\r
339                                 /* A buffer was successfully obtained.  Create the string that is\r
340                                 sent to the echo server.  Note the string is written directly\r
341                                 into the buffer obtained from the IP stack. */\r
342                                 sprintf( ( char * ) pucUDPPayloadBuffer, "%s %u\r\n", "Zero copy message number", ( unsigned int ) ulTxCount );\r
343 \r
344                                 /* Also copy the string into a local buffer so it can be compared\r
345                                 with the string that is later received back from the echo server. */\r
346                                 strcpy( cTxString, ( char * ) pucUDPPayloadBuffer );\r
347 \r
348                                 /* Pass the buffer into the send function.  ulFlags has the\r
349                                 FREERTOS_ZERO_COPY bit set so the IP stack will take control of\r
350                                 the     buffer, rather than copy data out of the buffer. */\r
351                                 echoMARK_SEND_IN_TRACE_BUFFER( xZeroCopySendEvent );\r
352                                 lReturned = FreeRTOS_sendto(    xSocket,                                        /* The socket being sent to. */\r
353                                                                                                 ( void * ) pucUDPPayloadBuffer, /* The buffer being passed into the IP stack. */\r
354                                                                                                 strlen( cTxString ) + 1,        /* The length of the data being sent.  Plus 1 to ensure the null terminator is part of the data. */\r
355                                                                                                 FREERTOS_ZERO_COPY,                     /* ulFlags with the zero copy bit is set. */\r
356                                                                                                 &xEchoServerAddress,            /* Where the data is being sent. */\r
357                                                                                                 sizeof( xEchoServerAddress ) );\r
358 \r
359                                 if( lReturned == 0 )\r
360                                 {\r
361                                         /* The send operation failed, so this task is still\r
362                                         responsible     for the buffer obtained from the IP stack.  To\r
363                                         ensure the buffer is not lost it must either be used again,\r
364                                         or, as in this case, returned to the IP stack using\r
365                                         FreeRTOS_ReleaseUDPPayloadBuffer().  pucUDPPayloadBuffer can\r
366                                         be safely re-used to receive from the socket below once the\r
367                                         buffer has been returned to the stack. */\r
368                                         FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );\r
369                                 }\r
370                                 else\r
371                                 {\r
372                                         /* The send was successful so the IP stack is now managing\r
373                                         the     buffer pointed to by pucUDPPayloadBuffer, and the IP\r
374                                         stack will return the buffer once it has been sent.\r
375                                         pucUDPPayloadBuffer can be safely re-used to receive from\r
376                                         the socket below. */\r
377                                 }\r
378 \r
379                                 /* Keep a count of how many echo requests have been transmitted\r
380                                 so it can be compared to the number of echo replies received.\r
381                                 It would be expected to loose at least one to an ARP message the\r
382                                 first time the connection is created. */\r
383                                 ulTxCount++;\r
384 \r
385                                 /* Receive data on the socket.  ulFlags has the zero copy bit set\r
386                                 (FREERTOS_ZERO_COPY) indicating to the stack that a reference to\r
387                                 the     received data should be passed out to this task using the\r
388                                 second parameter to the FreeRTOS_recvfrom() call.  When this is\r
389                                 done the IP stack is no longer responsible for releasing the\r
390                                 buffer, and     the task *must* return the buffer to the stack when\r
391                                 it is no longer needed.  By default the receive block time is\r
392                                 portMAX_DELAY. */\r
393                                 echoMARK_SEND_IN_TRACE_BUFFER( xZeroCopyReceiveEvent );\r
394                                 lReturned = FreeRTOS_recvfrom(  xSocket,                                        /* The socket to receive from. */\r
395                                                                                                 ( void * ) &pucUDPPayloadBuffer,  /* pucUDPPayloadBuffer will be set to point to the buffer that already contains the received data. */\r
396                                                                                                 0,                                                      /* Ignored because the zero copy interface is being used. */\r
397                                                                                                 FREERTOS_ZERO_COPY,                     /* ulFlags with the FREERTOS_ZERO_COPY bit set. */\r
398                                                                                                 &xEchoServerAddress,            /* The address from which the data was sent. */\r
399                                                                                                 &xAddressLength );\r
400 \r
401                                 if( lReturned > 0 )\r
402                                 {\r
403                                         /* Compare the string sent to the echo server with the string\r
404                                         received back from the echo server. */\r
405                                         if( strcmp( ( char * ) pucUDPPayloadBuffer, cTxString ) == 0 )\r
406                                         {\r
407                                                 /* The strings matched. */\r
408                                                 ulRxCount++;\r
409                                         }\r
410 \r
411                                         /* The buffer that contains the data passed out of the stack\r
412                                         *must* be returned to the stack. */\r
413                                         FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer );\r
414                                 }\r
415                         }\r
416                 }\r
417 \r
418                 /* Pause for a short while to ensure the network is not too\r
419                 congested. */\r
420                 vTaskDelay( echoLOOP_DELAY );\r
421 \r
422                 /* Close this socket before looping back to create another. */\r
423                 FreeRTOS_closesocket( xSocket );\r
424         }\r
425 }\r
426 /*-----------------------------------------------------------*/\r
427 \r