]> begriffs open source - cmsis-freertos/blob - Demo/Common/Full/comtest.c
Merge branch 'develop'
[cmsis-freertos] / Demo / Common / Full / comtest.c
1 /*
2  * FreeRTOS V202111.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 /**
28  * Creates two tasks that operate on an interrupt driven serial port.  A loopback
29  * connector should be used so that everything that is transmitted is also received.
30  * The serial port does not use any flow control.  On a standard 9way 'D' connector
31  * pins two and three should be connected together.
32  *
33  * The first task repeatedly sends a string to a queue, character at a time.  The
34  * serial port interrupt will empty the queue and transmit the characters.  The
35  * task blocks for a pseudo random period before resending the string.
36  *
37  * The second task blocks on a queue waiting for a character to be received.
38  * Characters received by the serial port interrupt routine are posted onto the
39  * queue - unblocking the task making it ready to execute.  If this is then the
40  * highest priority task ready to run it will run immediately - with a context
41  * switch occurring at the end of the interrupt service routine.  The task
42  * receiving characters is spawned with a higher priority than the task
43  * transmitting the characters.
44  *
45  * With the loop back connector in place, one task will transmit a string and the
46  * other will immediately receive it.  The receiving task knows the string it
47  * expects to receive so can detect an error.
48  *
49  * This also creates a third task.  This is used to test semaphore usage from an
50  * ISR and does nothing interesting.
51  *
52  * \page ComTestC comtest.c
53  * \ingroup DemoFiles
54  * <HR>
55  */
56
57 /*
58  * Changes from V1.00:
59  *
60  + The priority of the Rx task has been lowered.  Received characters are
61  +    now processed (read from the queue) at the idle priority, allowing low
62  +    priority tasks to run evenly at times of a high communications overhead.
63  +
64  + Changes from V1.01:
65  +
66  + The Tx task now waits a pseudo random time between transmissions.
67  +    Previously a fixed period was used but this was not such a good test as
68  +    interrupts fired at regular intervals.
69  +
70  + Changes From V1.2.0:
71  +
72  + Use vSerialPutString() instead of single character puts.
73  + Only stop the check variable incrementing after two consecutive errors.
74  +
75  + Changed from V1.2.5
76  +
77  + Made the Rx task 2 priorities higher than the Tx task.  Previously it was
78  +    only 1.  This is done to tie in better with the other demo application
79  +    tasks.
80  +
81  + Changes from V2.0.0
82  +
83  + Delay periods are now specified using variables and constants of
84  +    TickType_t rather than unsigned long.
85  + Slight modification to task priorities.
86  +
87  */
88
89
90 /* Scheduler include files. */
91 #include <stdlib.h>
92 #include <string.h>
93 #include "FreeRTOS.h"
94 #include "task.h"
95
96 /* Demo program include files. */
97 #include "serial.h"
98 #include "comtest.h"
99 #include "print.h"
100
101 /* The Tx task will transmit the sequence of characters at a pseudo random
102  * interval.  This is the maximum and minimum block time between sends. */
103 #define comTX_MAX_BLOCK_TIME         ( ( TickType_t ) 0x15e )
104 #define comTX_MIN_BLOCK_TIME         ( ( TickType_t ) 0xc8 )
105
106 #define comMAX_CONSECUTIVE_ERRORS    ( 2 )
107
108 #define comSTACK_SIZE                ( ( unsigned short ) 256 )
109
110 #define comRX_RELATIVE_PRIORITY      ( 1 )
111
112 /* Handle to the com port used by both tasks. */
113 static xComPortHandle xPort;
114
115 /* The transmit function as described at the top of the file. */
116 static void vComTxTask( void * pvParameters );
117
118 /* The receive function as described at the top of the file. */
119 static void vComRxTask( void * pvParameters );
120
121 /* The semaphore test function as described at the top of the file. */
122 static void vSemTestTask( void * pvParameters );
123
124 /* The string that is repeatedly transmitted. */
125 const char * const pcMessageToExchange = "Send this message over and over again to check communications interrupts. "
126                                          "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n";
127
128 /* Variables that are incremented on each cycle of each task.  These are used to
129  * check that both tasks are still executing. */
130 volatile short sTxCount = 0, sRxCount = 0, sSemCount = 0;
131
132 /* The handle to the semaphore test task. */
133 static TaskHandle_t xSemTestTaskHandle = NULL;
134
135 /*-----------------------------------------------------------*/
136
137 void vStartComTestTasks( unsigned portBASE_TYPE uxPriority,
138                          eCOMPort ePort,
139                          eBaud eBaudRate )
140 {
141     const unsigned portBASE_TYPE uxBufferLength = 255;
142
143     /* Initialise the com port then spawn both tasks. */
144     xPort = xSerialPortInit( ePort, eBaudRate, serNO_PARITY, serBITS_8, serSTOP_1, uxBufferLength );
145     xTaskCreate( vComTxTask, "COMTx", comSTACK_SIZE, NULL, uxPriority, NULL );
146     xTaskCreate( vComRxTask, "COMRx", comSTACK_SIZE, NULL, uxPriority + comRX_RELATIVE_PRIORITY, NULL );
147     xTaskCreate( vSemTestTask, "ISRSem", comSTACK_SIZE, NULL, tskIDLE_PRIORITY, &xSemTestTaskHandle );
148 }
149 /*-----------------------------------------------------------*/
150
151 static void vComTxTask( void * pvParameters )
152 {
153     const char * const pcTaskStartMsg = "COM Tx task started.\r\n";
154     TickType_t xTimeToWait;
155
156     /* Stop warnings. */
157     ( void ) pvParameters;
158
159     /* Queue a message for printing to say the task has started. */
160     vPrintDisplayMessage( &pcTaskStartMsg );
161
162     for( ; ; )
163     {
164         /* Send the string to the serial port. */
165         vSerialPutString( xPort, pcMessageToExchange, strlen( pcMessageToExchange ) );
166
167         /* We have posted all the characters in the string - increment the variable
168          * used to check that this task is still running, then wait before re-sending
169          * the string. */
170         sTxCount++;
171
172         xTimeToWait = xTaskGetTickCount();
173
174         /* Make sure we don't wait too long... */
175         xTimeToWait %= comTX_MAX_BLOCK_TIME;
176
177         /* ...but we do want to wait. */
178         if( xTimeToWait < comTX_MIN_BLOCK_TIME )
179         {
180             xTimeToWait = comTX_MIN_BLOCK_TIME;
181         }
182
183         vTaskDelay( xTimeToWait );
184     }
185 } /*lint !e715 !e818 pvParameters is required for a task function even if it is not referenced. */
186 /*-----------------------------------------------------------*/
187
188 static void vComRxTask( void * pvParameters )
189 {
190     const char * const pcTaskStartMsg = "COM Rx task started.\r\n";
191     const char * const pcTaskErrorMsg = "COM read error\r\n";
192     const char * const pcTaskRestartMsg = "COM resynced\r\n";
193     const char * const pcTaskTimeoutMsg = "COM Rx timed out\r\n";
194     const TickType_t xBlockTime = ( TickType_t ) 0xffff / portTICK_PERIOD_MS;
195     const char * pcExpectedChar;
196     portBASE_TYPE xGotChar;
197     char cRxedChar;
198     short sResyncRequired, sConsecutiveErrors, sLatchedError;
199
200     /* Stop warnings. */
201     ( void ) pvParameters;
202
203     /* Queue a message for printing to say the task has started. */
204     vPrintDisplayMessage( &pcTaskStartMsg );
205
206     /* The first expected character is the first character in the string. */
207     pcExpectedChar = pcMessageToExchange;
208     sResyncRequired = pdFALSE;
209     sConsecutiveErrors = 0;
210     sLatchedError = pdFALSE;
211
212     for( ; ; )
213     {
214         /* Receive a message from the com port interrupt routine.  If a message is
215          * not yet available the call will block the task. */
216         xGotChar = xSerialGetChar( xPort, &cRxedChar, xBlockTime );
217
218         if( xGotChar == pdTRUE )
219         {
220             if( sResyncRequired == pdTRUE )
221             {
222                 /* We got out of sequence and are waiting for the start of the next
223                  * transmission of the string. */
224                 if( cRxedChar == '\n' )
225                 {
226                     /* This is the end of the message so we can start again - with
227                      * the first character in the string being the next thing we expect
228                      * to receive. */
229                     pcExpectedChar = pcMessageToExchange;
230                     sResyncRequired = pdFALSE;
231
232                     /* Queue a message for printing to say that we are going to try
233                      * again. */
234                     vPrintDisplayMessage( &pcTaskRestartMsg );
235
236                     /* Stop incrementing the check variable, if consecutive errors occur. */
237                     sConsecutiveErrors++;
238
239                     if( sConsecutiveErrors >= comMAX_CONSECUTIVE_ERRORS )
240                     {
241                         sLatchedError = pdTRUE;
242                     }
243                 }
244             }
245             else
246             {
247                 /* We have received a character, but is it the expected character? */
248                 if( cRxedChar != *pcExpectedChar )
249                 {
250                     /* This was not the expected character so post a message for
251                      * printing to say that an error has occurred.  We will then wait
252                      * to resynchronise. */
253                     vPrintDisplayMessage( &pcTaskErrorMsg );
254                     sResyncRequired = pdTRUE;
255                 }
256                 else
257                 {
258                     /* This was the expected character so next time we will expect
259                      * the next character in the string.  Wrap back to the beginning
260                      * of the string when the null terminator has been reached. */
261                     pcExpectedChar++;
262
263                     if( *pcExpectedChar == '\0' )
264                     {
265                         pcExpectedChar = pcMessageToExchange;
266
267                         /* We have got through the entire string without error. */
268                         sConsecutiveErrors = 0;
269                     }
270                 }
271             }
272
273             /* Increment the count that is used to check that this task is still
274              * running.  This is only done if an error has never occurred. */
275             if( sLatchedError == pdFALSE )
276             {
277                 sRxCount++;
278             }
279         }
280         else
281         {
282             vPrintDisplayMessage( &pcTaskTimeoutMsg );
283         }
284     }
285 } /*lint !e715 !e818 pvParameters is required for a task function even if it is not referenced. */
286 /*-----------------------------------------------------------*/
287
288 static void vSemTestTask( void * pvParameters )
289 {
290     const char * const pcTaskStartMsg = "ISR Semaphore test started.\r\n";
291     portBASE_TYPE xError = pdFALSE;
292
293     /* Stop warnings. */
294     ( void ) pvParameters;
295
296     /* Queue a message for printing to say the task has started. */
297     vPrintDisplayMessage( &pcTaskStartMsg );
298
299     for( ; ; )
300     {
301         if( xSerialWaitForSemaphore( xPort ) )
302         {
303             if( xError == pdFALSE )
304             {
305                 sSemCount++;
306             }
307         }
308         else
309         {
310             xError = pdTRUE;
311         }
312     }
313 } /*lint !e715 !e830 !e818 pvParameters not used but function prototype must be standard for task function. */
314 /*-----------------------------------------------------------*/
315
316 /* This is called to check that all the created tasks are still running. */
317 portBASE_TYPE xAreComTestTasksStillRunning( void )
318 {
319     static short sLastTxCount = 0, sLastRxCount = 0, sLastSemCount = 0;
320     portBASE_TYPE xReturn;
321
322     /* Not too worried about mutual exclusion on these variables as they are 16
323      * bits and we are only reading them.  We also only care to see if they have
324      * changed or not. */
325
326     if( ( sTxCount == sLastTxCount ) || ( sRxCount == sLastRxCount ) || ( sSemCount == sLastSemCount ) )
327     {
328         xReturn = pdFALSE;
329     }
330     else
331     {
332         xReturn = pdTRUE;
333     }
334
335     sLastTxCount = sTxCount;
336     sLastRxCount = sRxCount;
337     sLastSemCount = sSemCount;
338
339     return xReturn;
340 }
341 /*-----------------------------------------------------------*/
342
343 void vComTestUnsuspendTask( void )
344 {
345     /* The task that is suspended on the semaphore will be referenced from the
346      * Suspended list as it is blocking indefinitely.  This call just checks that
347      * the kernel correctly detects this and does not attempt to unsuspend the
348      * task. */
349     xTaskResumeFromISR( xSemTestTaskHandle );
350 }