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