1 /* Copyright (C) 2014-2015 by Jacob Alexander
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to deal
5 * in the Software without restriction, including without limitation the rights
6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 * copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 // ----- Includes -----
28 #include <buildvars.h>
35 // ----- Variables -----
37 // Basic command dictionary
38 CLIDict_Entry( clear, "Clear the screen.");
39 CLIDict_Entry( cliDebug, "Enables/Disables hex output of the most recent cli input." );
40 CLIDict_Entry( help, "You're looking at it :P" );
41 CLIDict_Entry( led, "Enables/Disables indicator LED. Try a couple times just in case the LED is in an odd state.\r\n\t\t\033[33mWarning\033[0m: May adversely affect some modules..." );
42 CLIDict_Entry( reload, "Signals microcontroller to reflash/reload." );
43 CLIDict_Entry( reset, "Resets the terminal back to initial settings." );
44 CLIDict_Entry( restart, "Sends a software restart, should be similar to powering on the device." );
45 CLIDict_Entry( version, "Version information about this firmware." );
47 CLIDict_Def( basicCLIDict, "General Commands" ) = {
48 CLIDict_Item( clear ),
49 CLIDict_Item( cliDebug ),
52 CLIDict_Item( reload ),
53 CLIDict_Item( reset ),
54 CLIDict_Item( restart ),
55 CLIDict_Item( version ),
56 { 0, 0, 0 } // Null entry for dictionary end
61 // ----- Functions -----
65 print("\033[2K\r"); // Erases the current line and resets cursor to beginning of line
66 print("\033[1;34m:\033[0m "); // Blue bold prompt
70 inline void CLI_init()
72 // Reset the Line Buffer
73 CLILineBufferCurrent = 0;
75 // History starts empty
77 CLIHistoryCurrent = 0;
83 // Register first dictionary
84 CLIDictionariesUsed = 0;
85 CLI_registerDictionary( basicCLIDict, basicCLIDictName );
87 // Initialize main LED
91 // Hex debug mode is off by default
95 // Query the serial input buffer for any new characters
98 // Current buffer position
99 uint8_t prev_buf_pos = CLILineBufferCurrent;
101 // Process each character while available
104 // No more characters to process
105 if ( Output_availablechar() == 0 )
108 // Retrieve from output module
109 char cur_char = (char)Output_getchar();
111 // Make sure buffer isn't full
112 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
115 erro_print("Serial line buffer is full, dropping character and resetting...");
118 CLILineBufferCurrent = 0;
126 // Place into line buffer
127 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
130 // Display Hex Key Input if enabled
131 if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
133 print("\033[s\r\n"); // Save cursor position, and move to the next line
134 print("\033[2K"); // Erases the current line
136 uint8_t pos = prev_buf_pos;
137 while ( CLILineBufferCurrent > pos )
139 printHex( CLILineBuffer[pos++] );
143 print("\033[u"); // Restore cursor position
146 // If buffer has changed, output to screen while there are still characters in the buffer not displayed
147 while ( CLILineBufferCurrent > prev_buf_pos )
149 // Check for control characters
150 switch ( CLILineBuffer[prev_buf_pos] )
155 CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
157 // Remove the space if there is no command
158 if ( CLILineBufferCurrent == 1 )
160 CLILineBufferCurrent--;
164 // Only do command-related stuff if there was actually a command
165 // Avoids clogging command history with blanks
167 // Process the current line buffer
170 // Add the command to the history
171 CLI_saveHistory( CLILineBuffer );
173 // Keep the array circular, discarding the older entries
174 if ( CLIHistoryTail < CLIHistoryHead )
175 CLIHistoryHead = ( CLIHistoryHead + 1 ) % CLIMaxHistorySize;
177 if ( CLIHistoryTail == CLIMaxHistorySize )
183 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
184 CLI_saveHistory( NULL ); // delete the old temp buffer
189 CLILineBufferCurrent = 0;
191 // Reset the prompt after processing has finished
195 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
196 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
200 // Tab completion for the current command
203 CLILineBufferCurrent--; // Remove the Tab
205 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
206 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
209 case 0x1B: // Esc / Escape codes
210 // Check for other escape sequence
212 // \e[ is an escape code in vt100 compatible terminals
213 if ( CLILineBufferCurrent >= prev_buf_pos + 3
214 && CLILineBuffer[ prev_buf_pos ] == 0x1B
215 && CLILineBuffer[ prev_buf_pos + 1] == 0x5B )
217 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
219 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x41 ) // Hist prev
221 if ( CLIHistoryCurrent == CLIHistoryTail )
223 // Is first time pressing arrow. Save the current buffer
224 CLILineBuffer[ prev_buf_pos ] = '\0';
225 CLI_saveHistory( CLILineBuffer );
228 // Grab the previus item from the history if there is one
229 if ( RING_PREV( CLIHistoryCurrent ) != RING_PREV( CLIHistoryHead ) )
230 CLIHistoryCurrent = RING_PREV( CLIHistoryCurrent );
231 CLI_retreiveHistory( CLIHistoryCurrent );
233 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x42 ) // Hist next
235 // Grab the next item from the history if it exists
236 if ( RING_NEXT( CLIHistoryCurrent ) != RING_NEXT( CLIHistoryTail ) )
237 CLIHistoryCurrent = RING_NEXT( CLIHistoryCurrent );
238 CLI_retreiveHistory( CLIHistoryCurrent );
244 case 0x7F: // Backspace
245 // TODO - Does not handle case for arrow editing (arrows disabled atm)
246 CLILineBufferCurrent--; // Remove the backspace
248 // If there are characters in the buffer
249 if ( CLILineBufferCurrent > 0 )
251 // Remove character from current position in the line buffer
252 CLILineBufferCurrent--;
254 // Remove character from tty
261 // Place a null on the end (to use with string print)
262 CLILineBuffer[CLILineBufferCurrent] = '\0';
264 // Output buffer to screen
265 dPrint( &CLILineBuffer[prev_buf_pos] );
275 // Takes a string, returns two pointers
276 // One to the first non-space character
277 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
278 // Places a NULL at the first space after the first argument
279 void CLI_argumentIsolation( char* string, char** first, char** second )
281 // Mark out the first argument
282 // This is done by finding the first space after a list of non-spaces and setting it NULL
283 char* cmdPtr = string - 1;
284 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
286 // Locates first space delimiter
287 char* argPtr = cmdPtr + 1;
288 while ( *argPtr != ' ' && *argPtr != '\0' )
291 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
292 (++argPtr)[-1] = '\0';
294 // Set return variables
299 // Scans the CLILineBuffer for any valid commands
300 void CLI_commandLookup()
302 // Ignore command if buffer is 0 length
303 if ( CLILineBufferCurrent == 0 )
306 // Set the last+1 character of the buffer to NULL for string processing
307 CLILineBuffer[CLILineBufferCurrent] = '\0';
309 // Retrieve pointers to command and beginning of arguments
310 // Places a NULL at the first space after the command
313 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
315 // Scan array of dictionaries for a valid command match
316 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
318 // Parse each cmd until a null command entry is found, or an argument match
319 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
321 // Compare the first argument and each command entry
322 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
324 // Run the specified command function pointer
325 // argPtr is already pointing at the first character of the arguments
326 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
333 // No match for the command...
335 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
338 // Registers a command dictionary with the CLI
339 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
341 // Make sure this max limit of dictionaries hasn't been reached
342 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
344 erro_print("Max number of dictionaries defined already...");
349 CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
350 CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
353 inline void CLI_tabCompletion()
355 // Ignore command if buffer is 0 length
356 if ( CLILineBufferCurrent == 0 )
359 // Set the last+1 character of the buffer to NULL for string processing
360 CLILineBuffer[CLILineBufferCurrent] = '\0';
362 // Retrieve pointers to command and beginning of arguments
363 // Places a NULL at the first space after the command
366 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
372 // Scan array of dictionaries for a valid command match
373 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
375 // Parse each cmd until a null command entry is found, or an argument match
376 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
378 // Compare the first argument piece to each command entry to see if it is "like"
379 // NOTE: To save on processing, we only care about the commands and ignore the arguments
380 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
381 // Also ignores full matches
382 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
384 // TODO Make list of commands if multiple matches
386 tabMatch = (char*)CLIDict[dict][cmd].name;
391 // Only tab complete if there was 1 match
395 CLILineBufferCurrent = 0;
397 // Reprint the prompt (automatically clears the line)
400 // Display the command
403 // There are no index counts, so just copy the whole string to the input buffer
404 while ( *tabMatch != '\0' )
406 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
411 inline int CLI_wrap( int kX, int const kLowerBound, int const kUpperBound )
413 int range_size = kUpperBound - kLowerBound + 1;
415 if ( kX < kLowerBound )
416 kX += range_size * ((kLowerBound - kX) / range_size + 1);
418 return kLowerBound + (kX - kLowerBound) % range_size;
421 inline void CLI_saveHistory( char *buff )
426 CLIHistoryBuffer[ CLIHistoryTail ][ 0 ] = '\0';
430 // Copy the line to the history
432 for (i = 0; i < CLILineBufferCurrent; i++)
434 CLIHistoryBuffer[ CLIHistoryTail ][ i ] = CLILineBuffer[ i ];
438 void CLI_retreiveHistory( int index )
440 char *histMatch = CLIHistoryBuffer[ index ];
443 CLILineBufferCurrent = 0;
445 // Reprint the prompt (automatically clears the line)
448 // Display the command
451 // There are no index counts, so just copy the whole string to the input buffe
452 CLILineBufferCurrent = 0;
453 while ( *histMatch != '\0' )
455 CLILineBuffer[ CLILineBufferCurrent++ ] = *histMatch++;
461 // ----- CLI Command Functions -----
463 void cliFunc_clear( char* args)
465 print("\033[2J\033[H\r"); // Erases the whole screen
468 void cliFunc_cliDebug( char* args )
470 // Toggle Hex Debug Mode
471 if ( CLIHexDebugMode )
474 info_print("Hex debug mode disabled...");
480 info_print("Hex debug mode enabled...");
485 void cliFunc_help( char* args )
487 // Scan array of dictionaries and print every description
488 // (no alphabetical here, too much processing/memory to sort...)
489 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
491 // Print the name of each dictionary as a title
492 print( NL "\033[1;32m" );
493 _print( CLIDictNames[dict] ); // This print is requride by AVR (flash)
494 print( "\033[0m" NL );
496 // Parse each cmd/description until a null command entry is found
497 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
499 dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
501 // Determine number of spaces to tab by the length of the command and TabAlign
502 uint8_t padLength = CLIEntryTabAlign - lenStr( (char*)CLIDict[dict][cmd].name );
503 while ( padLength-- > 0 )
506 _print( CLIDict[dict][cmd].description ); // This print is required by AVR (flash)
512 void cliFunc_led( char* args )
514 CLILEDState ^= 1 << 1; // Toggle between 0 and 1
515 errorLED( CLILEDState ); // Enable/Disable error LED
518 void cliFunc_reload( char* args )
520 // Request to output module to be set into firmware reload mode
521 Output_firmwareReload();
524 void cliFunc_reset( char* args )
526 print("\033c"); // Resets the terminal
529 void cliFunc_restart( char* args )
531 // Trigger an overall software reset
535 void cliFunc_version( char* args )
538 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
539 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
540 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus CLI_ModifiedFiles NL );
541 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
542 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
543 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
544 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
545 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
546 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
547 print( " \033[1mChip:\033[0m " CLI_Chip NL );
548 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
549 print( " \033[1mDevice:\033[0m " CLI_Device NL );
550 print( " \033[1mModules:\033[0m " CLI_Modules NL );