]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_A5_SAMA5D3x_Xplained_IAR/CDCCommandConsole.c
Update version numbers in preparation for V8.2.0 release candidate 1.
[freertos] / FreeRTOS / Demo / CORTEX_A5_SAMA5D3x_Xplained_IAR / CDCCommandConsole.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  * NOTE:  This file uses a third party USB CDC driver.\r
98  */\r
99 \r
100 /* Standard includes. */\r
101 #include "string.h"\r
102 #include "stdio.h"\r
103 \r
104 /* FreeRTOS includes. */\r
105 #include "FreeRTOS.h"\r
106 #include "task.h"\r
107 #include "event_groups.h"\r
108 \r
109 /* Example includes. */\r
110 #include "FreeRTOS_CLI.h"\r
111 \r
112 /* Library includes. */\r
113 #include "board.h"\r
114 #include "chip.h"\r
115 #include "USBD.h"\r
116 #include "CDCDSerialDriver.h"\r
117 \r
118 /*-----------------------------------------------------------*/\r
119 \r
120 /* Dimensions the buffer into which input characters are placed. */\r
121 #define cmdMAX_INPUT_SIZE               50\r
122 \r
123 /* DEL acts as a backspace. */\r
124 #define cmdASCII_DEL            ( 0x7F )\r
125 \r
126 /* The bits in the event group used to signal USB interrupt events to this\r
127 task. */\r
128 #define cmdRX_COMPLETE_BIT      ( 0x01 )\r
129 #define cmdTX_COMPLETE_BIT      ( 0x02 )\r
130 /*-----------------------------------------------------------*/\r
131 \r
132 /*\r
133  * The task that implements the command console processing.\r
134  */\r
135 static void prvCDCCommandConsoleTask( void *pvParameters );\r
136 \r
137 /*\r
138  * Initialise the USB hardware and driver.\r
139  */\r
140 static void prvCDCInit( void );\r
141 \r
142 /*\r
143  * Handler installed on the VBUS pin to detect connect() and disconnect()\r
144  * events.\r
145  */\r
146 static void prvVBusISRHandler( const Pin *pxPin );\r
147 \r
148 /*\r
149  * USB handler defined by the driver, installed after the CDC driver has been\r
150  * initialised.\r
151  */\r
152 extern void USBD_IrqHandler( void );\r
153 \r
154 /*\r
155  * The function that creates the CLI task.\r
156  */\r
157 void vUSBCommandConsoleStart( uint16_t usStackSize, UBaseType_t uxPriority );\r
158 \r
159 /*\r
160  * Send xDataLength bytes from pcData to the CDC port.\r
161  */\r
162 static void prvCDCSend( const char *pcData, size_t xDataLenth );\r
163 \r
164 /*\r
165  * Initiate a receive into the Rx buffer from the CDC port, then wait for a\r
166  * period for characters to be received.\r
167  */\r
168 static void prvCDCGetChar( void );\r
169 \r
170 /*\r
171  * Configure VBus pins and interrupts, and check for connection.\r
172  */\r
173 static void prvConfigureVBus( void );\r
174 \r
175 /*\r
176  * Callback which is invoked when a CDC read completes.  This callback is\r
177  * passed as a parameter to the CDC receive function.\r
178  */\r
179 static void prvCDCDataReceivedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesReceived, uint32_t ulBytesRemaining );\r
180 \r
181 /*\r
182  * Callback which is invoked when a CDC write completes.  This callback is\r
183  * passed as a parameter to the CDC send function.\r
184  */\r
185 static void prvCDCDataTransmittedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesSent, uint32_t ulBytesRemaining );\r
186 \r
187 /*\r
188  * Keep trying to initiate an Rx until it is started successfully\r
189  */\r
190 static void prvStartRx( void );\r
191 \r
192 /*-----------------------------------------------------------*/\r
193 \r
194 /* Const messages output by the command console. */\r
195 static const char * const pcWelcomeMessage = "FreeRTOS command server.\r\nType Help to view a list of registered commands.\r\n\r\n>";\r
196 static const char * const pcEndOfOutputMessage = "\r\n[Press ENTER to execute the previous command again]\r\n>";\r
197 static const char * const pcNewLine = "\r\n";\r
198 \r
199 /* Buffer into which received characters are placed. */\r
200 static char pcRxBuffer[ cmdMAX_INPUT_SIZE ];\r
201 \r
202 /* The number of bytes in pcRxBuffer that have not yet been read. */\r
203 static uint32_t ulBytesAvailable = 0;\r
204 \r
205 /* Used to unblock the task when bytes are received and when bytes have\r
206 completed sending. */\r
207 static EventGroupHandle_t xCDCEventBits;\r
208 \r
209 /*-----------------------------------------------------------*/\r
210 \r
211 void vUSBCommandConsoleStart( uint16_t usStackSize, UBaseType_t uxPriority )\r
212 {\r
213         /* Event group used to indicate that bytes are available in the Rx buffer\r
214         or that bytes have finished sending. */\r
215         xCDCEventBits = xEventGroupCreate();\r
216         configASSERT( xCDCEventBits );\r
217 \r
218         /* Create the task that handles the console itself. */\r
219         xTaskCreate(    prvCDCCommandConsoleTask,       /* The task that implements the command console. */\r
220                                         "CLI",                                          /* Text name assigned to the task.  This is just to assist debugging.  The kernel does not use this name itself. */\r
221                                         usStackSize,                            /* The size of the stack allocated to the task. */\r
222                                         NULL,                                           /* The parameter is not used, so NULL is passed. */\r
223                                         uxPriority,                                     /* The priority allocated to the task. */\r
224                                         NULL );                                         /* A handle is not required, so just pass NULL. */\r
225 }\r
226 /*-----------------------------------------------------------*/\r
227 \r
228 static void prvCDCCommandConsoleTask( void *pvParameters )\r
229 {\r
230 uint8_t ucInputIndex = 0;\r
231 char *pcOutputString, cRxedChar;\r
232 static char cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ];\r
233 BaseType_t xReturned;\r
234 uint32_t ulBufferIndex = 0;\r
235 \r
236         ( void ) pvParameters;\r
237 \r
238         /* Obtain the address of the output buffer.  Note there is no mutual\r
239         exclusion on this buffer as it is assumed only one command console interface\r
240         will be used at any one time. */\r
241         pcOutputString = FreeRTOS_CLIGetOutputBuffer();\r
242 \r
243         /* Initialise the CDC driver. */\r
244         prvCDCInit();\r
245 \r
246         /* Start receiving into the buffer. */\r
247         prvStartRx();\r
248 \r
249         /* Send the welcome message. */\r
250         prvCDCSend( pcWelcomeMessage, strlen( pcWelcomeMessage ) );\r
251 \r
252         for( ;; )\r
253         {\r
254                 /* Wait for my characters to be available. */\r
255                 prvCDCGetChar();\r
256 \r
257                 /* Process the bytes char for char on the assumption that as input comes\r
258                 from typing it is unlikely that more than a single byte will be received\r
259                 at a time anyway. */\r
260                 while( ulBytesAvailable > 0 )\r
261                 {\r
262                         /* Read next byte from the rx buffer. */\r
263                         cRxedChar = pcRxBuffer[ ulBufferIndex ];\r
264 \r
265                         taskENTER_CRITICAL();\r
266                         {\r
267                                 ulBytesAvailable--;\r
268                         }\r
269                         taskEXIT_CRITICAL();\r
270 \r
271                         /* Echo the character back. */\r
272                         prvCDCSend( &cRxedChar, sizeof( cRxedChar ) );\r
273 \r
274                         /* Was it the end of the line? */\r
275                         if( cRxedChar == '\n' || cRxedChar == '\r' )\r
276                         {\r
277                                 /* Just to space the output from the input. */\r
278                                 prvCDCSend( pcNewLine, strlen( pcNewLine ) );\r
279 \r
280                                 /* See if the command is empty, indicating that the last command\r
281                                 is to be executed again. */\r
282                                 if( ucInputIndex == 0 )\r
283                                 {\r
284                                         /* Copy the last command back into the input string. */\r
285                                         strcpy( cInputString, cLastInputString );\r
286                                 }\r
287 \r
288                                 /* Pass the received command to the command interpreter.  The\r
289                                 command interpreter is called repeatedly until it returns\r
290                                 pdFALSE (indicating there is no more output) as it might\r
291                                 generate more than one string. */\r
292                                 do\r
293                                 {\r
294                                         /* Get the next output string from the command interpreter. */\r
295                                         xReturned = FreeRTOS_CLIProcessCommand( cInputString, pcOutputString, configCOMMAND_INT_MAX_OUTPUT_SIZE );\r
296 \r
297                                         /* Write the generated string to the UART. */\r
298                                         prvCDCSend( pcOutputString, strlen( pcOutputString ) );\r
299 \r
300                                 } while( xReturned != pdFALSE );\r
301 \r
302                                 /* All the strings generated by the input command have been\r
303                                 sent.  Clear the input string ready to receive the next command.\r
304                                 Remember the command that was just processed first in case it is\r
305                                 to be processed again. */\r
306                                 strcpy( cLastInputString, cInputString );\r
307                                 ucInputIndex = 0;\r
308                                 memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );\r
309 \r
310                                 prvCDCSend( pcEndOfOutputMessage, strlen( pcEndOfOutputMessage ) );\r
311                         }\r
312                         else\r
313                         {\r
314                                 if( cRxedChar == '\r' )\r
315                                 {\r
316                                         /* Ignore the character. */\r
317                                 }\r
318                                 else if( ( cRxedChar == '\b' ) || ( cRxedChar == cmdASCII_DEL ) )\r
319                                 {\r
320                                         /* Backspace was pressed.  Erase the last character in the\r
321                                         string - if any. */\r
322                                         if( ucInputIndex > 0 )\r
323                                         {\r
324                                                 ucInputIndex--;\r
325                                                 cInputString[ ucInputIndex ] = '\0';\r
326                                         }\r
327                                 }\r
328                                 else\r
329                                 {\r
330                                         /* A character was entered.  Add it to the string entered so\r
331                                         far.  When a \n is entered the complete string will be\r
332                                         passed to the command interpreter. */\r
333                                         if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) )\r
334                                         {\r
335                                                 if( ucInputIndex < cmdMAX_INPUT_SIZE )\r
336                                                 {\r
337                                                         cInputString[ ucInputIndex ] = cRxedChar;\r
338                                                         ucInputIndex++;\r
339                                                 }\r
340                                         }\r
341                                 }\r
342                         }\r
343 \r
344                         /* Move onto the next byte the next time around. */\r
345                         ulBufferIndex++;\r
346                         if( ulBufferIndex >= cmdMAX_INPUT_SIZE )\r
347                         {\r
348                                 ulBufferIndex = 0;\r
349                         }\r
350                 }\r
351         }\r
352 }\r
353 /*-----------------------------------------------------------*/\r
354 \r
355 static void prvCDCInit( void )\r
356 {\r
357 extern WEAK const USBDDriverDescriptors cdcdSerialDriverDescriptors;\r
358 \r
359         /* If they are present, configure Vbus & Wake-up pins */\r
360         PIO_InitializeInterrupts( 0 );\r
361 \r
362         /* CDC serial driver initialization */\r
363         CDCDSerialDriver_Initialize( &cdcdSerialDriverDescriptors );\r
364 \r
365         /* Configure VBus pins and interrupts, and check for connection. */\r
366         prvConfigureVBus();\r
367 }\r
368 /*-----------------------------------------------------------*/\r
369 \r
370 static void prvCDCSend( const char *pcData, size_t xDataLength )\r
371 {\r
372 const TickType_t xTransferCompleteDelay = pdMS_TO_TICKS( 500UL );\r
373 \r
374         ( void ) pcData;\r
375         ( void ) xDataLength;\r
376 \r
377         if( xDataLength > 0 )\r
378         {\r
379                 if( CDCDSerialDriver_Write( ( void * ) pcData, xDataLength, ( TransferCallback ) prvCDCDataTransmittedCallback, 0 ) == USBD_STATUS_SUCCESS )\r
380                 {\r
381                         /* Wait for the transfer to complete. */\r
382                         xEventGroupWaitBits(    xCDCEventBits,\r
383                                                                         cmdTX_COMPLETE_BIT, /* The bit to wait for. */\r
384                                                                         pdTRUE, /* Clear the bit before exiting the function. */\r
385                                                                         pdFALSE, /* Only need to wait for one bit anyway. */\r
386                                                                         xTransferCompleteDelay ); /* The maximum time to wait for the event. */\r
387                 }\r
388         }\r
389 }\r
390 /*-----------------------------------------------------------*/\r
391 \r
392 static void prvStartRx( void )\r
393 {\r
394 const TickType_t xFailedReadDelay = pdMS_TO_TICKS( 150UL );\r
395 \r
396         while( CDCDSerialDriver_Read( pcRxBuffer, cmdMAX_INPUT_SIZE, ( TransferCallback ) prvCDCDataReceivedCallback, 0 ) != USBD_STATUS_SUCCESS )\r
397         {\r
398                 /* Maybe the CDC is not connected. */\r
399                 vTaskDelay( xFailedReadDelay );\r
400         }\r
401 }\r
402 /*-----------------------------------------------------------*/\r
403 \r
404 static void prvCDCGetChar( void )\r
405 {\r
406 const TickType_t xTransferCompleteDelay = pdMS_TO_TICKS( 750UL );\r
407 \r
408         if( ulBytesAvailable == 0 )\r
409         {\r
410                 /* Wait for a transfer to complete. */\r
411                 xEventGroupWaitBits(    xCDCEventBits,\r
412                                                                 cmdRX_COMPLETE_BIT, /* The bit to wait for. */\r
413                                                                 pdTRUE, /* Clear the bit before exiting the function. */\r
414                                                                 pdFALSE, /* Only need to wait for one bit anyway. */\r
415                                                                 xTransferCompleteDelay ); /* The maximum time to wait for the event. */\r
416         }\r
417 }\r
418 /*-----------------------------------------------------------*/\r
419 \r
420 static void prvVBusISRHandler( const Pin *pxPin )\r
421 {\r
422         /* NOTE: As this was written for the XPlained board, which is powered\r
423         through the USB and cannot be on without the USB connected, this function\r
424         has not been exercised. */\r
425 \r
426     /* Check current level on VBus to detect a connect/disconnect. */\r
427     if( PIO_Get( pxPin ) != 0 )\r
428     {\r
429         USBD_Connect();\r
430     }\r
431     else\r
432     {\r
433         USBD_Disconnect();\r
434     }\r
435 }\r
436 /*-----------------------------------------------------------*/\r
437 \r
438 static void prvCDCDataReceivedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesReceived, uint32_t ulBytesRemaining )\r
439 {\r
440 BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
441 static uint32_t ulNextRxPosition = 0;\r
442 \r
443         ( void ) ulUnused;\r
444         ( void ) ucStatus;\r
445         ( void ) ulBytesRemaining;\r
446 \r
447         /* If bytes were received then store the number of bytes placed into the Rx\r
448         buffer. */\r
449         if( ucStatus == USBD_STATUS_SUCCESS )\r
450         {\r
451                 ulBytesAvailable += ulBytesReceived;\r
452 \r
453                 /* Restart the Rx position from a buffer position past the newly\r
454                 received data. */\r
455                 ulNextRxPosition += ulBytesReceived;\r
456 \r
457                 if( ulNextRxPosition >= cmdMAX_INPUT_SIZE )\r
458                 {\r
459                         ulNextRxPosition = 0;\r
460                 }\r
461                 CDCDSerialDriver_Read( pcRxBuffer + ulNextRxPosition, cmdMAX_INPUT_SIZE - ulNextRxPosition, ( TransferCallback ) prvCDCDataReceivedCallback, 0 );\r
462 \r
463                 /* Ensure the task knows new data is available. */\r
464                 xEventGroupSetBitsFromISR( xCDCEventBits, cmdRX_COMPLETE_BIT, &xHigherPriorityTaskWoken );\r
465                 portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
466         }\r
467 }\r
468 /*-----------------------------------------------------------*/\r
469 \r
470 static void prvCDCDataTransmittedCallback( uint32_t ulUnused, uint8_t ucStatus, uint32_t ulBytesSent, uint32_t ulBytesRemaining )\r
471 {\r
472 BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
473 \r
474         ( void ) ulUnused;\r
475         ( void ) ucStatus;\r
476         ( void ) ulBytesRemaining;\r
477         ( void ) ulBytesSent;\r
478 \r
479         xEventGroupSetBitsFromISR( xCDCEventBits, cmdTX_COMPLETE_BIT, &xHigherPriorityTaskWoken );\r
480         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
481 }\r
482 /*-----------------------------------------------------------*/\r
483 \r
484 static void prvConfigureVBus( void )\r
485 {\r
486 const Pin xVBusPin = PIN_USB_VBUS;\r
487 \r
488         /* Configure PIO to generate an interrupt on status change. */\r
489         PIO_Configure( &xVBusPin, 1 );\r
490         PIO_ConfigureIt( &xVBusPin, prvVBusISRHandler );\r
491         PIO_EnableIt( &xVBusPin );\r
492 \r
493         /* Check current level on VBus */\r
494         if( PIO_Get( &xVBusPin ) != pdFALSE )\r
495         {\r
496                 /* if VBUS present, force the connect */\r
497                 USBD_Connect();\r
498         }\r
499         else\r
500         {\r
501                 USBD_Disconnect();\r
502         }\r
503 }\r
504 /*-----------------------------------------------------------*/\r
505 \r
506 void USBDCallbacks_Initialized( void )\r
507 {\r
508         /* CDC specific re-implementation of weak callback function.  Invoked after\r
509         the USB driver has been initialised. By default, configures the UDP/UDPHS\r
510         interrupt.  The interrupt priority is set to the highest to ensure the\r
511         interrupt nesting tests interfer as little as possible with the USB. */\r
512         IRQ_ConfigureIT( ID_UDPHS, 7, USBD_IrqHandler );\r
513         IRQ_EnableIT( ID_UDPHS );\r
514 }\r
515 /*-----------------------------------------------------------*/\r
516 \r
517 void USBDDriverCallbacks_ConfigurationChanged( uint8_t ucConfigNumber )\r
518 {\r
519         /* CDC specific re-implementation of weak callback function.  Invoked when\r
520         the configuration of the device changes. Parse used endpoints. */\r
521         CDCDSerialDriver_ConfigurationChangedHandler( ucConfigNumber );\r
522 }\r
523 /*-----------------------------------------------------------*/\r
524 \r
525 void USBDCallbacks_RequestReceived( const USBGenericRequest *pxRequest )\r
526 {\r
527         /* CDC specific re-implementation of weak callback function.  Invoked when\r
528         a new SETUP request is received from the host. */\r
529         CDCDSerialDriver_RequestHandler( pxRequest );\r
530 }\r
531 /*-----------------------------------------------------------*/\r