]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_A5_SAMA5D4x_EK_IAR/CDCCommandConsole.c
753636c7dc3a67e5ac55d0a21e07dccfb3b45621
[freertos] / FreeRTOS / Demo / CORTEX_A5_SAMA5D4x_EK_IAR / CDCCommandConsole.c
1 /*\r
2     FreeRTOS V8.1.2 - 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     ***************************************************************************\r
8      *                                                                       *\r
9      *    FreeRTOS provides completely free yet professionally developed,    *\r
10      *    robust, strictly quality controlled, supported, and cross          *\r
11      *    platform software that has become a de facto standard.             *\r
12      *                                                                       *\r
13      *    Help yourself get started quickly and support the FreeRTOS         *\r
14      *    project by purchasing a FreeRTOS tutorial book, reference          *\r
15      *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
16      *                                                                       *\r
17      *    Thank you!                                                         *\r
18      *                                                                       *\r
19     ***************************************************************************\r
20 \r
21     This file is part of the FreeRTOS distribution.\r
22 \r
23     FreeRTOS is free software; you can redistribute it and/or modify it under\r
24     the terms of the GNU General Public License (version 2) as published by the\r
25     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
26 \r
27     >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
28     >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
29     >>!   obliged to provide the source code for proprietary components     !<<\r
30     >>!   outside of the FreeRTOS kernel.                                   !<<\r
31 \r
32     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
33     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
34     FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
35     link: http://www.freertos.org/a00114.html\r
36 \r
37     1 tab == 4 spaces!\r
38 \r
39     ***************************************************************************\r
40      *                                                                       *\r
41      *    Having a problem?  Start by reading the FAQ "My application does   *\r
42      *    not run, what could be wrong?"                                     *\r
43      *                                                                       *\r
44      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
45      *                                                                       *\r
46     ***************************************************************************\r
47 \r
48     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
49     license and Real Time Engineers Ltd. contact details.\r
50 \r
51     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
52     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
53     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
54 \r
55     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
56     Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
57     licenses offer ticketed support, indemnification and middleware.\r
58 \r
59     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
60     engineered and independently SIL3 certified version for use in safety and\r
61     mission critical applications that require provable dependability.\r
62 \r
63     1 tab == 4 spaces!\r
64 */\r
65 \r
66 /*\r
67  * NOTE:  This file uses a third party USB CDC driver.\r
68  */\r
69 \r
70 /* Standard includes. */\r
71 #include "string.h"\r
72 #include "stdio.h"\r
73 \r
74 /* FreeRTOS includes. */\r
75 #include "FreeRTOS.h"\r
76 #include "task.h"\r
77 #include "event_groups.h"\r
78 \r
79 /* Example includes. */\r
80 #include "FreeRTOS_CLI.h"\r
81 \r
82 /* Library includes. */\r
83 #include "board.h"\r
84 #include "chip.h"\r
85 #include "USBD.h"\r
86 #include "CDCDSerialDriver.h"\r
87 \r
88 /*-----------------------------------------------------------*/\r
89 \r
90 /* Dimensions the buffer into which input characters are placed. */\r
91 #define cmdMAX_INPUT_SIZE               50\r
92 \r
93 /* DEL acts as a backspace. */\r
94 #define cmdASCII_DEL            ( 0x7F )\r
95 \r
96 /* The bits in the event group used to signal USB interrupt events to this\r
97 task. */\r
98 #define cmdRX_COMPLETE_BIT      ( 0x01 )\r
99 #define cmdTX_COMPLETE_BIT      ( 0x02 )\r
100 /*-----------------------------------------------------------*/\r
101 \r
102 /*\r
103  * The task that implements the command console processing.\r
104  */\r
105 static void prvCDCCommandConsoleTask( void *pvParameters );\r
106 \r
107 /*\r
108  * Initialise the USB hardware and driver.\r
109  */\r
110 static void prvCDCInit( void );\r
111 \r
112 /*\r
113  * Handler installed on the VBUS pin to detect connect() and disconnect()\r
114  * events.\r
115  */\r
116 static void prvVBusISRHandler( void );\r
117 \r
118 /*\r
119  * USB handler defined by the driver, installed after the CDC driver has been\r
120  * initialised.\r
121  */\r
122 extern void USBD_IrqHandler( void );\r
123 \r
124 /*\r
125  * The function that creates the CLI task.\r
126  */\r
127 void vUSBCommandConsoleStart( uint16_t usStackSize, UBaseType_t uxPriority );\r
128 \r
129 /*\r
130  * Send xDataLength bytes from pcData to the CDC port.\r
131  */\r
132 static void prvCDCSend( const char *pcData, size_t xDataLenth );\r
133 \r
134 /*\r
135  * Initiate a receive into the Rx buffer from the CDC port, then wait for a\r
136  * period for characters to be received.\r
137  */\r
138 static void prvCDCGetChar( void );\r
139 \r
140 /*\r
141  * Configure VBus pins and interrupts, and check for connection.\r
142  */\r
143 static void prvConfigureVBus( void );\r
144 \r
145 /*\r
146  * Callback which is invoked when a CDC read completes.  This callback is\r
147  * passed as a parameter to the CDC receive function.\r
148  */\r
149 static void prvCDCDataReceivedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesReceived, uint32_t ulBytesRemaining );\r
150 \r
151 /*\r
152  * Callback which is invoked when a CDC write completes.  This callback is\r
153  * passed as a parameter to the CDC send function.\r
154  */\r
155 static void prvCDCDataTransmittedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesSent, uint32_t ulBytesRemaining );\r
156 \r
157 /*\r
158  * Keep trying to initiate an Rx until it is started successfully\r
159  */\r
160 static void prvStartRx( void );\r
161 \r
162 /*-----------------------------------------------------------*/\r
163 \r
164 /* Const messages output by the command console. */\r
165 static const char * const pcWelcomeMessage = "FreeRTOS command server.\r\nType Help to view a list of registered commands.\r\n\r\n>";\r
166 static const char * const pcEndOfOutputMessage = "\r\n[Press ENTER to execute the previous command again]\r\n>";\r
167 static const char * const pcNewLine = "\r\n";\r
168 \r
169 /* Buffer into which received characters are placed. */\r
170 static char pcRxBuffer[ cmdMAX_INPUT_SIZE ];\r
171 \r
172 /* The number of bytes in pcRxBuffer that have not yet been read. */\r
173 static uint32_t ulBytesAvailable = 0;\r
174 \r
175 /* Used to unblock the task when bytes are received and when bytes have\r
176 completed sending. */\r
177 static EventGroupHandle_t xCDCEventBits;\r
178 \r
179 /*-----------------------------------------------------------*/\r
180 \r
181 void vUSBCommandConsoleStart( uint16_t usStackSize, UBaseType_t uxPriority )\r
182 {\r
183         /* Event group used to indicate that bytes are available in the Rx buffer\r
184         or that bytes have finished sending. */\r
185         xCDCEventBits = xEventGroupCreate();\r
186         configASSERT( xCDCEventBits );\r
187 \r
188         /* Create the task that handles the console itself. */\r
189         xTaskCreate(    prvCDCCommandConsoleTask,       /* The task that implements the command console. */\r
190                                         "CLI",                                          /* Text name assigned to the task.  This is just to assist debugging.  The kernel does not use this name itself. */\r
191                                         usStackSize,                            /* The size of the stack allocated to the task. */\r
192                                         NULL,                                           /* The parameter is not used, so NULL is passed. */\r
193                                         uxPriority,                                     /* The priority allocated to the task. */\r
194                                         NULL );                                         /* A handle is not required, so just pass NULL. */\r
195 }\r
196 /*-----------------------------------------------------------*/\r
197 \r
198 static void prvCDCCommandConsoleTask( void *pvParameters )\r
199 {\r
200 uint8_t ucInputIndex = 0;\r
201 char *pcOutputString, cRxedChar;\r
202 static char cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ];\r
203 BaseType_t xReturned;\r
204 uint32_t ulBufferIndex = 0;\r
205 \r
206         ( void ) pvParameters;\r
207 \r
208         /* Obtain the address of the output buffer.  Note there is no mutual\r
209         exclusion on this buffer as it is assumed only one command console interface\r
210         will be used at any one time. */\r
211         pcOutputString = FreeRTOS_CLIGetOutputBuffer();\r
212 \r
213         /* Initialise the CDC driver. */\r
214         prvCDCInit();\r
215 \r
216         /* Start receiving into the buffer. */\r
217         prvStartRx();\r
218 \r
219         /* Send the welcome message. */\r
220         prvCDCSend( pcWelcomeMessage, strlen( pcWelcomeMessage ) );\r
221 \r
222         for( ;; )\r
223         {\r
224                 /* Wait for my characters to be available. */\r
225                 prvCDCGetChar();\r
226 \r
227                 /* Process the bytes char for char on the assumption that as input comes\r
228                 from typing it is unlikely that more than a single byte will be received\r
229                 at a time anyway. */\r
230                 while( ulBytesAvailable > 0 )\r
231                 {\r
232                         /* Read next byte from the rx buffer. */\r
233                         cRxedChar = pcRxBuffer[ ulBufferIndex ];\r
234 \r
235                         taskENTER_CRITICAL();\r
236                         {\r
237                                 ulBytesAvailable--;\r
238                         }\r
239                         taskEXIT_CRITICAL();\r
240 \r
241                         /* Echo the character back. */\r
242                         prvCDCSend( &cRxedChar, sizeof( cRxedChar ) );\r
243 \r
244                         /* Was it the end of the line? */\r
245                         if( cRxedChar == '\n' || cRxedChar == '\r' )\r
246                         {\r
247                                 /* Just to space the output from the input. */\r
248                                 prvCDCSend( pcNewLine, strlen( pcNewLine ) );\r
249 \r
250                                 /* See if the command is empty, indicating that the last command\r
251                                 is to be executed again. */\r
252                                 if( ucInputIndex == 0 )\r
253                                 {\r
254                                         /* Copy the last command back into the input string. */\r
255                                         strcpy( cInputString, cLastInputString );\r
256                                 }\r
257 \r
258                                 /* Pass the received command to the command interpreter.  The\r
259                                 command interpreter is called repeatedly until it returns\r
260                                 pdFALSE (indicating there is no more output) as it might\r
261                                 generate more than one string. */\r
262                                 do\r
263                                 {\r
264                                         /* Get the next output string from the command interpreter. */\r
265                                         xReturned = FreeRTOS_CLIProcessCommand( cInputString, pcOutputString, configCOMMAND_INT_MAX_OUTPUT_SIZE );\r
266 \r
267                                         /* Write the generated string to the UART. */\r
268                                         prvCDCSend( pcOutputString, strlen( pcOutputString ) );\r
269 \r
270                                 } while( xReturned != pdFALSE );\r
271 \r
272                                 /* All the strings generated by the input command have been\r
273                                 sent.  Clear the input string ready to receive the next command.\r
274                                 Remember the command that was just processed first in case it is\r
275                                 to be processed again. */\r
276                                 strcpy( cLastInputString, cInputString );\r
277                                 ucInputIndex = 0;\r
278                                 memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );\r
279 \r
280                                 prvCDCSend( pcEndOfOutputMessage, strlen( pcEndOfOutputMessage ) );\r
281                         }\r
282                         else\r
283                         {\r
284                                 if( cRxedChar == '\r' )\r
285                                 {\r
286                                         /* Ignore the character. */\r
287                                 }\r
288                                 else if( ( cRxedChar == '\b' ) || ( cRxedChar == cmdASCII_DEL ) )\r
289                                 {\r
290                                         /* Backspace was pressed.  Erase the last character in the\r
291                                         string - if any. */\r
292                                         if( ucInputIndex > 0 )\r
293                                         {\r
294                                                 ucInputIndex--;\r
295                                                 cInputString[ ucInputIndex ] = '\0';\r
296                                         }\r
297                                 }\r
298                                 else\r
299                                 {\r
300                                         /* A character was entered.  Add it to the string entered so\r
301                                         far.  When a \n is entered the complete string will be\r
302                                         passed to the command interpreter. */\r
303                                         if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) )\r
304                                         {\r
305                                                 if( ucInputIndex < cmdMAX_INPUT_SIZE )\r
306                                                 {\r
307                                                         cInputString[ ucInputIndex ] = cRxedChar;\r
308                                                         ucInputIndex++;\r
309                                                 }\r
310                                         }\r
311                                 }\r
312                         }\r
313 \r
314                         /* Move onto the next byte the next time around. */\r
315                         ulBufferIndex++;\r
316                         if( ulBufferIndex >= cmdMAX_INPUT_SIZE )\r
317                         {\r
318                                 ulBufferIndex = 0;\r
319                         }\r
320                 }\r
321         }\r
322 }\r
323 /*-----------------------------------------------------------*/\r
324 \r
325 static void prvCDCInit( void )\r
326 {\r
327 extern WEAK const USBDDriverDescriptors cdcdSerialDriverDescriptors;\r
328 \r
329         /* If they are present, configure Vbus & Wake-up pins */\r
330         PIO_InitializeInterrupts( 0 );\r
331 \r
332         /* CDC serial driver initialization */\r
333         CDCDSerialDriver_Initialize( &cdcdSerialDriverDescriptors );\r
334 \r
335         /* Configure VBus pins and interrupts, and check for connection. */\r
336         prvConfigureVBus();\r
337 }\r
338 /*-----------------------------------------------------------*/\r
339 \r
340 static void prvCDCSend( const char *pcData, size_t xDataLength )\r
341 {\r
342 const TickType_t xTransferCompleteDelay = pdMS_TO_TICKS( 500UL );\r
343 \r
344         ( void ) pcData;\r
345         ( void ) xDataLength;\r
346 \r
347         if( xDataLength > 0 )\r
348         {\r
349                 if( CDCDSerialDriver_Write( ( void * ) pcData, xDataLength, ( TransferCallback ) prvCDCDataTransmittedCallback, 0 ) == USBD_STATUS_SUCCESS )\r
350                 {\r
351                         /* Wait for the transfer to complete. */\r
352                         xEventGroupWaitBits(    xCDCEventBits,\r
353                                                                         cmdTX_COMPLETE_BIT, /* The bit to wait for. */\r
354                                                                         pdTRUE, /* Clear the bit before exiting the function. */\r
355                                                                         pdFALSE, /* Only need to wait for one bit anyway. */\r
356                                                                         xTransferCompleteDelay ); /* The maximum time to wait for the event. */\r
357                 }\r
358         }\r
359 }\r
360 /*-----------------------------------------------------------*/\r
361 \r
362 static void prvStartRx( void )\r
363 {\r
364 const TickType_t xFailedReadDelay = pdMS_TO_TICKS( 150UL );\r
365 \r
366         while( CDCDSerialDriver_Read( pcRxBuffer, cmdMAX_INPUT_SIZE, ( TransferCallback ) prvCDCDataReceivedCallback, 0 ) != USBD_STATUS_SUCCESS )\r
367         {\r
368                 /* Maybe the CDC is not connected. */\r
369                 vTaskDelay( xFailedReadDelay );\r
370         }\r
371 }\r
372 /*-----------------------------------------------------------*/\r
373 \r
374 static void prvCDCGetChar( void )\r
375 {\r
376 const TickType_t xTransferCompleteDelay = pdMS_TO_TICKS( 750UL );\r
377 \r
378         if( ulBytesAvailable == 0 )\r
379         {\r
380                 /* Wait for a transfer to complete. */\r
381                 xEventGroupWaitBits(    xCDCEventBits,\r
382                                                                 cmdRX_COMPLETE_BIT, /* The bit to wait for. */\r
383                                                                 pdTRUE, /* Clear the bit before exiting the function. */\r
384                                                                 pdFALSE, /* Only need to wait for one bit anyway. */\r
385                                                                 xTransferCompleteDelay ); /* The maximum time to wait for the event. */\r
386         }\r
387 }\r
388 /*-----------------------------------------------------------*/\r
389 \r
390 static void prvVBusISRHandler( void )\r
391 {\r
392 const Pin xVBusPin = PIN_USB_VBUS;\r
393 \r
394     /* Check current level on VBus to detect a connect/disconnect. */\r
395     if( PIO_Get( &xVBusPin ) != 0 )\r
396     {\r
397         USBD_Connect();\r
398     }\r
399     else\r
400     {\r
401         USBD_Disconnect();\r
402     }\r
403 }\r
404 /*-----------------------------------------------------------*/\r
405 \r
406 static void prvCDCDataReceivedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesReceived, uint32_t ulBytesRemaining )\r
407 {\r
408 BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
409 static uint32_t ulNextRxPosition = 0;\r
410 \r
411         ( void ) ulUnused;\r
412         ( void ) ucStatus;\r
413         ( void ) ulBytesRemaining;\r
414 \r
415         /* If bytes were received then store the number of bytes placed into the Rx\r
416         buffer. */\r
417         if( ucStatus == USBD_STATUS_SUCCESS )\r
418         {\r
419                 ulBytesAvailable += ulBytesReceived;\r
420 \r
421                 /* Restart the Rx position from a buffer position past the newly\r
422                 received data. */\r
423                 ulNextRxPosition += ulBytesReceived;\r
424 \r
425                 if( ulNextRxPosition >= cmdMAX_INPUT_SIZE )\r
426                 {\r
427                         ulNextRxPosition = 0;\r
428                 }\r
429                 CDCDSerialDriver_Read( pcRxBuffer + ulNextRxPosition, cmdMAX_INPUT_SIZE - ulNextRxPosition, ( TransferCallback ) prvCDCDataReceivedCallback, 0 );\r
430 \r
431                 /* Ensure the task knows new data is available. */\r
432                 xEventGroupSetBitsFromISR( xCDCEventBits, cmdRX_COMPLETE_BIT, &xHigherPriorityTaskWoken );\r
433                 portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
434         }\r
435 }\r
436 /*-----------------------------------------------------------*/\r
437 \r
438 static void prvCDCDataTransmittedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesSent, uint32_t ulBytesRemaining )\r
439 {\r
440 BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
441 \r
442         ( void ) ulUnused;\r
443         ( void ) ucStatus;\r
444         ( void ) ulBytesRemaining;\r
445         ( void ) ulBytesSent;\r
446 \r
447         xEventGroupSetBitsFromISR( xCDCEventBits, cmdTX_COMPLETE_BIT, &xHigherPriorityTaskWoken );\r
448         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
449 }\r
450 /*-----------------------------------------------------------*/\r
451 \r
452 static void prvConfigureVBus( void )\r
453 {\r
454 const Pin xVBusPin = PIN_USB_VBUS;\r
455 const uint32_t ulPriority = 7; /* Highest. */\r
456 \r
457         /* Configure PIO to generate an interrupt on status change. */\r
458     PIO_Configure( &xVBusPin, 1 );\r
459     PIO_ConfigureIt( &xVBusPin );\r
460 \r
461         /* Ensure interrupt is disabled before setting the mode and installing the\r
462         handler.  The priority of the tick interrupt should always be set to the\r
463         lowest possible. */\r
464         AIC->AIC_SSR  = ID_PIOE;\r
465         AIC->AIC_IDCR = AIC_IDCR_INTD;\r
466         AIC->AIC_SMR  = AIC_SMR_SRCTYPE_EXT_POSITIVE_EDGE | ulPriority;\r
467         AIC->AIC_SVR = ( uint32_t ) prvVBusISRHandler;\r
468 \r
469         /* Start with the interrupt clear. */\r
470         AIC->AIC_ICCR = AIC_ICCR_INTCLR;\r
471         PIO_EnableIt( &xVBusPin );\r
472     AIC_EnableIT( ID_PIOE );\r
473 \r
474         /* Check current level on VBus */\r
475         if( PIO_Get( &xVBusPin ) != pdFALSE )\r
476         {\r
477                 /* If VBUS present, force the connect */\r
478                 USBD_Connect();\r
479         }\r
480         else\r
481         {\r
482                 USBD_Disconnect();\r
483         }\r
484 }\r
485 /*-----------------------------------------------------------*/\r
486 \r
487 void USBDCallbacks_Initialized( void )\r
488 {\r
489         /* CDC specific re-implementation of weak callback function.  Invoked after\r
490         the USB driver has been initialised. By default, configures the UDP/UDPHS\r
491         interrupt.  The interrupt priority is set to the highest to ensure the\r
492         interrupt nesting tests interfer as little as possible with the USB. */\r
493         AIC_EnableIT( ID_UDPHS );\r
494 }\r
495 /*-----------------------------------------------------------*/\r
496 \r
497 void USBDDriverCallbacks_ConfigurationChanged( uint8_t ucConfigNumber )\r
498 {\r
499         /* CDC specific re-implementation of weak callback function.  Invoked when\r
500         the configuration of the device changes. Parse used endpoints. */\r
501         CDCDSerialDriver_ConfigurationChangedHandler( ucConfigNumber );\r
502 }\r
503 /*-----------------------------------------------------------*/\r
504 \r
505 void USBDCallbacks_RequestReceived( const USBGenericRequest *pxRequest )\r
506 {\r
507         /* CDC specific re-implementation of weak callback function.  Invoked when\r
508         a new SETUP request is received from the host. */\r
509         CDCDSerialDriver_RequestHandler( pxRequest );\r
510 }\r
511 /*-----------------------------------------------------------*/\r