TCPEchoClient_SingleTasks.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * FreeRTOS V202112.00
  3. * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. * this software and associated documentation files (the "Software"), to deal in
  7. * the Software without restriction, including without limitation the rights to
  8. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. * the Software, and to permit persons to whom the Software is furnished to do so,
  10. * subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  18. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. *
  22. * https://www.FreeRTOS.org
  23. * https://github.com/FreeRTOS
  24. *
  25. */
  26. /*
  27. * A set of tasks are created that send TCP echo requests to the standard echo
  28. * port (port 7) on the IP address set by the configECHO_SERVER_ADDR0 to
  29. * configECHO_SERVER_ADDR3 constants, then wait for and verify the reply
  30. * (another demo is available that demonstrates the reception being performed in
  31. * a task other than that from with the request was made).
  32. *
  33. * See the following web page for essential demo usage and configuration
  34. * details:
  35. * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/examples_FreeRTOS_simulator.html
  36. */
  37. /* Standard includes. */
  38. #include <stdint.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. /* FreeRTOS includes. */
  42. #include "FreeRTOS.h"
  43. #include "task.h"
  44. #include "queue.h"
  45. /* FreeRTOS+TCP includes. */
  46. #include "FreeRTOS_IP.h"
  47. #include "FreeRTOS_Sockets.h"
  48. /* Exclude the whole file if FreeRTOSIPConfig.h is configured to use UDP only. */
  49. #if ( ipconfigUSE_TCP == 1 )
  50. /* The echo tasks create a socket, send out a number of echo requests, listen
  51. for the echo reply, then close the socket again before starting over. This
  52. delay is used between each iteration to ensure the network does not get too
  53. congested. */
  54. #define echoLOOP_DELAY ( ( TickType_t ) 150 / portTICK_PERIOD_MS )
  55. /* The echo server is assumed to be on port 7, which is the standard echo
  56. protocol port. */
  57. #define echoECHO_PORT ( 7 )
  58. /* The size of the buffers is a multiple of the MSS - the length of the data
  59. sent is a pseudo random size between 20 and echoBUFFER_SIZES. */
  60. #define echoBUFFER_SIZE_MULTIPLIER ( 3 )
  61. #define echoBUFFER_SIZES ( ipconfigTCP_MSS * echoBUFFER_SIZE_MULTIPLIER )
  62. /* The number of instances of the echo client task to create. */
  63. #define echoNUM_ECHO_CLIENTS ( 1 )
  64. /*-----------------------------------------------------------*/
  65. /*
  66. * Uses a socket to send data to, then receive data from, the standard echo
  67. * port number 7.
  68. */
  69. static void prvEchoClientTask( void *pvParameters );
  70. /*
  71. * Creates a pseudo random sized buffer of data to send to the echo server.
  72. */
  73. static BaseType_t prvCreateTxData( char *ucBuffer,
  74. uint32_t ulBufferLength );
  75. /*-----------------------------------------------------------*/
  76. /* Rx and Tx time outs are used to ensure the sockets do not wait too long for
  77. missing data. */
  78. static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 4000 );
  79. static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 2000 );
  80. /* Counters for each created task - for inspection only. */
  81. static uint32_t ulTxRxCycles[ echoNUM_ECHO_CLIENTS ] = { 0 },
  82. ulTxRxFailures[ echoNUM_ECHO_CLIENTS ] = { 0 },
  83. ulConnections[ echoNUM_ECHO_CLIENTS ] = { 0 };
  84. /* Rx and Tx buffers for each created task. */
  85. static char cTxBuffers[ echoNUM_ECHO_CLIENTS ][ echoBUFFER_SIZES ],
  86. cRxBuffers[ echoNUM_ECHO_CLIENTS ][ echoBUFFER_SIZES ];
  87. /*-----------------------------------------------------------*/
  88. void vStartTCPEchoClientTasks_SingleTasks( uint16_t usTaskStackSize,
  89. UBaseType_t uxTaskPriority )
  90. {
  91. BaseType_t x;
  92. /* Create the echo client tasks. */
  93. for( x = 0; x < echoNUM_ECHO_CLIENTS; x++ )
  94. {
  95. xTaskCreate( prvEchoClientTask, /* The function that implements the task. */
  96. "Echo0", /* Just a text name for the task to aid debugging. */
  97. usTaskStackSize, /* The stack size is defined in FreeRTOSIPConfig.h. */
  98. ( void * ) x, /* The task parameter, not used in this case. */
  99. uxTaskPriority, /* The priority assigned to the task is defined in FreeRTOSConfig.h. */
  100. NULL ); /* The task handle is not used. */
  101. }
  102. }
  103. /*-----------------------------------------------------------*/
  104. static void prvEchoClientTask( void *pvParameters )
  105. {
  106. Socket_t xSocket;
  107. struct freertos_sockaddr xEchoServerAddress;
  108. int32_t lLoopCount = 0UL;
  109. const int32_t lMaxLoopCount = 1;
  110. volatile uint32_t ulTxCount = 0UL;
  111. BaseType_t xReceivedBytes, xReturned, xInstance;
  112. BaseType_t lTransmitted, lStringLength;
  113. char *pcTransmittedString, *pcReceivedString;
  114. WinProperties_t xWinProps;
  115. TickType_t xTimeOnEntering;
  116. BaseType_t ret;
  117. /* Fill in the buffer and window sizes that will be used by the socket. */
  118. xWinProps.lTxBufSize = 6 * ipconfigTCP_MSS;
  119. xWinProps.lTxWinSize = 3;
  120. xWinProps.lRxBufSize = 6 * ipconfigTCP_MSS;
  121. xWinProps.lRxWinSize = 3;
  122. /* This task can be created a number of times. Each instance is numbered
  123. to enable each instance to use a different Rx and Tx buffer. The number is
  124. passed in as the task's parameter. */
  125. xInstance = ( BaseType_t ) pvParameters;
  126. /* Point to the buffers to be used by this instance of this task. */
  127. pcTransmittedString = &( cTxBuffers[ xInstance ][ 0 ] );
  128. pcReceivedString = &( cRxBuffers[ xInstance ][ 0 ] );
  129. /* Echo requests are sent to the echo server. The address of the echo
  130. server is configured by the constants configECHO_SERVER_ADDR0 to
  131. configECHO_SERVER_ADDR3 in FreeRTOSConfig.h. */
  132. xEchoServerAddress.sin_port = FreeRTOS_htons( echoECHO_PORT );
  133. xEchoServerAddress.sin_addr = FreeRTOS_inet_addr_quick( configECHO_SERVER_ADDR0,
  134. configECHO_SERVER_ADDR1,
  135. configECHO_SERVER_ADDR2,
  136. configECHO_SERVER_ADDR3 );
  137. for( ; ; )
  138. {
  139. /* Create a TCP socket. */
  140. xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
  141. configASSERT( xSocket != FREERTOS_INVALID_SOCKET );
  142. /* Set a time out so a missing reply does not cause the task to block
  143. indefinitely. */
  144. FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
  145. FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );
  146. /* Set the window and buffer sizes. */
  147. FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) );
  148. /* Connect to the echo server. */
  149. printf( "connecting to echo server....\n" );
  150. ret = FreeRTOS_connect( xSocket, &xEchoServerAddress, sizeof( xEchoServerAddress ) );
  151. if( ret == 0 )
  152. {
  153. printf( "Connected to server.. \n" );
  154. ulConnections[ xInstance ]++;
  155. /* Send a number of echo requests. */
  156. for( lLoopCount = 0; lLoopCount < lMaxLoopCount; lLoopCount++ )
  157. {
  158. /* Create the string that is sent to the echo server. */
  159. lStringLength = prvCreateTxData( pcTransmittedString, echoBUFFER_SIZES );
  160. /* Add in some unique text at the front of the string. */
  161. sprintf( pcTransmittedString, "TxRx message number %u", ulTxCount );
  162. ulTxCount++;
  163. printf( "sending data to the echo server \n" );
  164. /* Send the string to the socket. */
  165. lTransmitted = FreeRTOS_send( xSocket, /* The socket being sent to. */
  166. ( void * ) pcTransmittedString, /* The data being sent. */
  167. lStringLength, /* The length of the data being sent. */
  168. 0 ); /* No flags. */
  169. if( lTransmitted < 0 )
  170. {
  171. /* Error? */
  172. break;
  173. }
  174. /* Clear the buffer into which the echoed string will be
  175. placed. */
  176. memset( ( void * ) pcReceivedString, 0x00, echoBUFFER_SIZES );
  177. xReceivedBytes = 0;
  178. /* Receive data echoed back to the socket. */
  179. while( xReceivedBytes < lTransmitted )
  180. {
  181. xReturned = FreeRTOS_recv( xSocket, /* The socket being received from. */
  182. &( pcReceivedString[ xReceivedBytes ] ), /* The buffer into which the received data will be written. */
  183. lStringLength - xReceivedBytes, /* The size of the buffer provided to receive the data. */
  184. 0 ); /* No flags. */
  185. if( xReturned < 0 )
  186. {
  187. /* Error occurred. Latch it so it can be detected
  188. below. */
  189. xReceivedBytes = xReturned;
  190. break;
  191. }
  192. else if( xReturned == 0 )
  193. {
  194. /* Timed out. */
  195. break;
  196. }
  197. else
  198. {
  199. /* Keep a count of the bytes received so far. */
  200. xReceivedBytes += xReturned;
  201. }
  202. }
  203. /* If an error occurred it will be latched in xReceivedBytes,
  204. otherwise xReceived bytes will be just that - the number of
  205. bytes received from the echo server. */
  206. if( xReceivedBytes > 0 )
  207. {
  208. /* Compare the transmitted string to the received string. */
  209. configASSERT( strncmp( pcReceivedString, pcTransmittedString, lTransmitted ) == 0 );
  210. if( strncmp( pcReceivedString, pcTransmittedString, lTransmitted ) == 0 )
  211. {
  212. /* The echo reply was received without error. */
  213. ulTxRxCycles[ xInstance ]++;
  214. }
  215. else
  216. {
  217. /* The received string did not match the transmitted
  218. string. */
  219. ulTxRxFailures[ xInstance ]++;
  220. break;
  221. }
  222. }
  223. else if( xReceivedBytes < 0 )
  224. {
  225. /* FreeRTOS_recv() returned an error. */
  226. break;
  227. }
  228. else
  229. {
  230. /* Timed out without receiving anything? */
  231. break;
  232. }
  233. }
  234. /* Finished using the connected socket, initiate a graceful close:
  235. FIN, FIN+ACK, ACK. */
  236. FreeRTOS_shutdown( xSocket, FREERTOS_SHUT_RDWR );
  237. /* Expect FreeRTOS_recv() to return an error once the shutdown is
  238. complete. */
  239. xTimeOnEntering = xTaskGetTickCount();
  240. do
  241. {
  242. xReturned = FreeRTOS_recv( xSocket, /* The socket being received from. */
  243. &( pcReceivedString[ 0 ] ), /* The buffer into which the received data will be written. */
  244. echoBUFFER_SIZES, /* The size of the buffer provided to receive the data. */
  245. 0 );
  246. if( xReturned < 0 )
  247. {
  248. break;
  249. }
  250. } while( ( xTaskGetTickCount() - xTimeOnEntering ) < xReceiveTimeOut );
  251. }
  252. else
  253. {
  254. printf( "Could not connect to server %ld\n", ret );
  255. }
  256. /* Close this socket before looping back to create another. */
  257. FreeRTOS_closesocket( xSocket );
  258. /* Pause for a short while to ensure the network is not too
  259. congested. */
  260. vTaskDelay( echoLOOP_DELAY );
  261. }
  262. }
  263. /*-----------------------------------------------------------*/
  264. static BaseType_t prvCreateTxData( char *cBuffer,
  265. uint32_t ulBufferLength )
  266. {
  267. BaseType_t lCharactersToAdd, lCharacter;
  268. char cChar = '0';
  269. const BaseType_t lMinimumLength = 60;
  270. /* Randomise the number of characters that will be sent in the echo
  271. request. */
  272. do
  273. {
  274. lCharactersToAdd = ipconfigRAND32() % ( ulBufferLength - 20UL );
  275. } while( ( lCharactersToAdd == 0 ) || ( lCharactersToAdd < lMinimumLength ) ); /* Must be at least enough to add the unique text to the start of the string later. */
  276. /* Fill the buffer. */
  277. for( lCharacter = 0; lCharacter < lCharactersToAdd; lCharacter++ )
  278. {
  279. cBuffer[ lCharacter ] = cChar;
  280. cChar++;
  281. if( cChar > '~' )
  282. {
  283. cChar = '0';
  284. }
  285. }
  286. return lCharactersToAdd;
  287. }
  288. /*-----------------------------------------------------------*/
  289. BaseType_t xAreSingleTaskTCPEchoClientsStillRunning( void )
  290. {
  291. static uint32_t ulLastEchoSocketCount[ echoNUM_ECHO_CLIENTS ] = { 0 }, ulLastConnections[ echoNUM_ECHO_CLIENTS ] = { 0 };
  292. BaseType_t xReturn = pdPASS, x;
  293. /* Return fail is the number of cycles does not increment between
  294. consecutive calls. */
  295. for( x = 0; x < echoNUM_ECHO_CLIENTS; x++ )
  296. {
  297. if( ulTxRxCycles[ x ] == ulLastEchoSocketCount[ x ] )
  298. {
  299. xReturn = pdFAIL;
  300. }
  301. else
  302. {
  303. ulLastEchoSocketCount[ x ] = ulTxRxCycles[ x ];
  304. }
  305. if( ulConnections[ x ] == ulLastConnections[ x ] )
  306. {
  307. xReturn = pdFAIL;
  308. }
  309. else
  310. {
  311. ulConnections[ x ] = ulLastConnections[ x ];
  312. }
  313. }
  314. return xReturn;
  315. }
  316. #endif /* ipconfigUSE_TCP */