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 -----
25 #include <buildvars.h>
33 // ----- Variables -----
35 // Basic command dictionary
36 CLIDict_Entry( clear, "Clear the screen.");
37 CLIDict_Entry( cliDebug, "Enables/Disables hex output of the most recent cli input." );
38 CLIDict_Entry( help, "You're looking at it :P" );
39 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..." );
40 CLIDict_Entry( reload, "Signals microcontroller to reflash/reload." );
41 CLIDict_Entry( reset, "Resets the terminal back to initial settings." );
42 CLIDict_Entry( restart, "Sends a software restart, should be similar to powering on the device." );
43 CLIDict_Entry( version, "Version information about this firmware." );
45 CLIDict_Def( basicCLIDict, "General Commands" ) = {
46 CLIDict_Item( clear ),
47 CLIDict_Item( cliDebug ),
50 CLIDict_Item( reload ),
51 CLIDict_Item( reset ),
52 CLIDict_Item( restart ),
53 CLIDict_Item( version ),
54 { 0, 0, 0 } // Null entry for dictionary end
59 // ----- Functions -----
63 print("\033[2K\r"); // Erases the current line and resets cursor to beginning of line
64 print("\033[1;34m:\033[0m "); // Blue bold prompt
68 inline void CLI_init()
70 // Reset the Line Buffer
71 CLILineBufferCurrent = 0;
73 // History starts empty
75 CLIHistoryCurrent = 0;
81 // Register first dictionary
82 CLIDictionariesUsed = 0;
83 CLI_registerDictionary( basicCLIDict, basicCLIDictName );
85 // Initialize main LED
89 // Hex debug mode is off by default
93 // Query the serial input buffer for any new characters
96 // Current buffer position
97 uint8_t prev_buf_pos = CLILineBufferCurrent;
99 // Process each character while available
102 // No more characters to process
103 if ( Output_availablechar() == 0 )
106 // Retrieve from output module
107 char cur_char = (char)Output_getchar();
109 // Make sure buffer isn't full
110 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
113 erro_print("Serial line buffer is full, dropping character and resetting...");
116 CLILineBufferCurrent = 0;
124 // Place into line buffer
125 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
128 // Display Hex Key Input if enabled
129 if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
131 print("\033[s\r\n"); // Save cursor position, and move to the next line
132 print("\033[2K"); // Erases the current line
134 uint8_t pos = prev_buf_pos;
135 while ( CLILineBufferCurrent > pos )
137 printHex( CLILineBuffer[pos++] );
141 print("\033[u"); // Restore cursor position
144 // If buffer has changed, output to screen while there are still characters in the buffer not displayed
145 while ( CLILineBufferCurrent > prev_buf_pos )
147 // Check for control characters
148 switch ( CLILineBuffer[prev_buf_pos] )
153 CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
155 // Remove the space if there is no command
156 if ( CLILineBufferCurrent == 1 )
158 CLILineBufferCurrent--;
162 // Only do command-related stuff if there was actually a command
163 // Avoids clogging command history with blanks
165 // Process the current line buffer
168 // Add the command to the history
169 CLI_saveHistory( CLILineBuffer );
171 // Keep the array circular, discarding the older entries
172 if ( CLIHistoryTail < CLIHistoryHead )
173 CLIHistoryHead = ( CLIHistoryHead + 1 ) % CLIMaxHistorySize;
175 if ( CLIHistoryTail == CLIMaxHistorySize )
181 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
182 CLI_saveHistory( NULL ); // delete the old temp buffer
187 CLILineBufferCurrent = 0;
189 // Reset the prompt after processing has finished
193 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
194 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
198 // Tab completion for the current command
201 CLILineBufferCurrent--; // Remove the Tab
203 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
204 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
207 case 0x1B: // Esc / Escape codes
208 // Check for other escape sequence
210 // \e[ is an escape code in vt100 compatible terminals
211 if ( CLILineBufferCurrent >= prev_buf_pos + 3
212 && CLILineBuffer[ prev_buf_pos ] == 0x1B
213 && CLILineBuffer[ prev_buf_pos + 1] == 0x5B )
215 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
217 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x41 ) // Hist prev
219 if ( CLIHistoryCurrent == CLIHistoryTail )
221 // Is first time pressing arrow. Save the current buffer
222 CLILineBuffer[ prev_buf_pos ] = '\0';
223 CLI_saveHistory( CLILineBuffer );
226 // Grab the previus item from the history if there is one
227 if ( RING_PREV( CLIHistoryCurrent ) != RING_PREV( CLIHistoryHead ) )
228 CLIHistoryCurrent = RING_PREV( CLIHistoryCurrent );
229 CLI_retreiveHistory( CLIHistoryCurrent );
231 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x42 ) // Hist next
233 // Grab the next item from the history if it exists
234 if ( RING_NEXT( CLIHistoryCurrent ) != RING_NEXT( CLIHistoryTail ) )
235 CLIHistoryCurrent = RING_NEXT( CLIHistoryCurrent );
236 CLI_retreiveHistory( CLIHistoryCurrent );
242 case 0x7F: // Backspace
243 // TODO - Does not handle case for arrow editing (arrows disabled atm)
244 CLILineBufferCurrent--; // Remove the backspace
246 // If there are characters in the buffer
247 if ( CLILineBufferCurrent > 0 )
249 // Remove character from current position in the line buffer
250 CLILineBufferCurrent--;
252 // Remove character from tty
259 // Place a null on the end (to use with string print)
260 CLILineBuffer[CLILineBufferCurrent] = '\0';
262 // Output buffer to screen
263 dPrint( &CLILineBuffer[prev_buf_pos] );
273 // Takes a string, returns two pointers
274 // One to the first non-space character
275 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
276 // Places a NULL at the first space after the first argument
277 void CLI_argumentIsolation( char* string, char** first, char** second )
279 // Mark out the first argument
280 // This is done by finding the first space after a list of non-spaces and setting it NULL
281 char* cmdPtr = string - 1;
282 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
284 // Locates first space delimiter
285 char* argPtr = cmdPtr + 1;
286 while ( *argPtr != ' ' && *argPtr != '\0' )
289 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
290 (++argPtr)[-1] = '\0';
292 // Set return variables
297 // Scans the CLILineBuffer for any valid commands
298 void CLI_commandLookup()
300 // Ignore command if buffer is 0 length
301 if ( CLILineBufferCurrent == 0 )
304 // Set the last+1 character of the buffer to NULL for string processing
305 CLILineBuffer[CLILineBufferCurrent] = '\0';
307 // Retrieve pointers to command and beginning of arguments
308 // Places a NULL at the first space after the command
311 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
313 // Scan array of dictionaries for a valid command match
314 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
316 // Parse each cmd until a null command entry is found, or an argument match
317 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
319 // Compare the first argument and each command entry
320 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
322 // Run the specified command function pointer
323 // argPtr is already pointing at the first character of the arguments
324 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
331 // No match for the command...
333 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
336 // Registers a command dictionary with the CLI
337 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
339 // Make sure this max limit of dictionaries hasn't been reached
340 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
342 erro_print("Max number of dictionaries defined already...");
347 CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
348 CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
351 inline void CLI_tabCompletion()
353 // Ignore command if buffer is 0 length
354 if ( CLILineBufferCurrent == 0 )
357 // Set the last+1 character of the buffer to NULL for string processing
358 CLILineBuffer[CLILineBufferCurrent] = '\0';
360 // Retrieve pointers to command and beginning of arguments
361 // Places a NULL at the first space after the command
364 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
370 // Scan array of dictionaries for a valid command match
371 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
373 // Parse each cmd until a null command entry is found, or an argument match
374 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
376 // Compare the first argument piece to each command entry to see if it is "like"
377 // NOTE: To save on processing, we only care about the commands and ignore the arguments
378 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
379 // Also ignores full matches
380 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
382 // TODO Make list of commands if multiple matches
384 tabMatch = (char*)CLIDict[dict][cmd].name;
389 // Only tab complete if there was 1 match
393 CLILineBufferCurrent = 0;
395 // Reprint the prompt (automatically clears the line)
398 // Display the command
401 // There are no index counts, so just copy the whole string to the input buffer
402 while ( *tabMatch != '\0' )
404 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
409 inline int CLI_wrap( int kX, int const kLowerBound, int const kUpperBound )
411 int range_size = kUpperBound - kLowerBound + 1;
413 if ( kX < kLowerBound )
414 kX += range_size * ((kLowerBound - kX) / range_size + 1);
416 return kLowerBound + (kX - kLowerBound) % range_size;
419 inline void CLI_saveHistory( char *buff )
424 CLIHistoryBuffer[ CLIHistoryTail ][ 0 ] = '\0';
428 // Copy the line to the history
430 for (i = 0; i < CLILineBufferCurrent; i++)
432 CLIHistoryBuffer[ CLIHistoryTail ][ i ] = CLILineBuffer[ i ];
436 void CLI_retreiveHistory( int index )
438 char *histMatch = CLIHistoryBuffer[ index ];
441 CLILineBufferCurrent = 0;
443 // Reprint the prompt (automatically clears the line)
446 // Display the command
449 // There are no index counts, so just copy the whole string to the input buffe
450 CLILineBufferCurrent = 0;
451 while ( *histMatch != '\0' )
453 CLILineBuffer[ CLILineBufferCurrent++ ] = *histMatch++;
459 // ----- CLI Command Functions -----
461 void cliFunc_clear( char* args)
463 print("\033[2J\033[H\r"); // Erases the whole screen
466 void cliFunc_cliDebug( char* args )
468 // Toggle Hex Debug Mode
469 if ( CLIHexDebugMode )
472 info_print("Hex debug mode disabled...");
478 info_print("Hex debug mode enabled...");
483 void cliFunc_help( char* args )
485 // Scan array of dictionaries and print every description
486 // (no alphabetical here, too much processing/memory to sort...)
487 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
489 // Print the name of each dictionary as a title
490 print( NL "\033[1;32m" );
491 _print( CLIDictNames[dict] ); // This print is requride by AVR (flash)
492 print( "\033[0m" NL );
494 // Parse each cmd/description until a null command entry is found
495 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
497 dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
499 // Determine number of spaces to tab by the length of the command and TabAlign
500 uint8_t padLength = CLIEntryTabAlign - lenStr( (char*)CLIDict[dict][cmd].name );
501 while ( padLength-- > 0 )
504 _print( CLIDict[dict][cmd].description ); // This print is required by AVR (flash)
510 void cliFunc_led( char* args )
512 CLILEDState ^= 1 << 1; // Toggle between 0 and 1
513 errorLED( CLILEDState ); // Enable/Disable error LED
516 void cliFunc_reload( char* args )
518 if ( flashModeEnabled_define == 0 )
521 warn_print("flashModeEnabled not set, cancelling firmware reload...");
522 info_msg("Set flashModeEnabled to 1 in your kll configuration.");
526 // Request to output module to be set into firmware reload mode
527 Output_firmwareReload();
530 void cliFunc_reset( char* args )
532 print("\033c"); // Resets the terminal
535 void cliFunc_restart( char* args )
537 // Trigger an overall software reset
541 void cliFunc_version( char* args )
544 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
545 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
546 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus CLI_ModifiedFiles NL );
547 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
548 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
549 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
550 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
551 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
552 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
553 print( " \033[1mChip:\033[0m " CLI_Chip NL );
554 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
555 print( " \033[1mDevice:\033[0m " CLI_Device NL );
556 print( " \033[1mModules:\033[0m " CLI_Modules NL );
557 #if defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
558 print( " \033[1mUnique Id:\033[0m " );
559 printHex32_op( SIM_UIDH, 4 );
560 printHex32_op( SIM_UIDMH, 4 );
561 printHex32_op( SIM_UIDML, 4 );
562 printHex32_op( SIM_UIDL, 4 );
563 #elif defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_)
565 #error "No unique id defined."