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 // Add the command to the history
163 CLI_saveHistory( CLILineBuffer );
165 // Process the current line buffer
168 // Keep the array circular, discarding the older entries
169 if ( CLIHistoryTail < CLIHistoryHead )
170 CLIHistoryHead = ( CLIHistoryHead + 1 ) % CLIMaxHistorySize;
172 if ( CLIHistoryTail == CLIMaxHistorySize )
178 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
179 CLI_saveHistory( NULL ); // delete the old temp buffer
184 CLILineBufferCurrent = 0;
186 // Reset the prompt after processing has finished
190 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
191 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
195 // Tab completion for the current command
198 CLILineBufferCurrent--; // Remove the Tab
200 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
201 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
204 case 0x1B: // Esc / Escape codes
205 // Check for other escape sequence
207 // \e[ is an escape code in vt100 compatible terminals
208 if ( CLILineBufferCurrent >= prev_buf_pos + 3
209 && CLILineBuffer[ prev_buf_pos ] == 0x1B
210 && CLILineBuffer[ prev_buf_pos + 1] == 0x5B )
212 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
214 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x41 ) // Hist prev
216 if ( CLIHistoryCurrent == CLIHistoryTail )
218 // Is first time pressing arrow. Save the current buffer
219 CLILineBuffer[ prev_buf_pos ] = '\0';
220 CLI_saveHistory( CLILineBuffer );
223 // Grab the previus item from the history if there is one
224 if ( RING_PREV( CLIHistoryCurrent ) != RING_PREV( CLIHistoryHead ) )
225 CLIHistoryCurrent = RING_PREV( CLIHistoryCurrent );
226 CLI_retreiveHistory( CLIHistoryCurrent );
228 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x42 ) // Hist next
230 // Grab the next item from the history if it exists
231 if ( RING_NEXT( CLIHistoryCurrent ) != RING_NEXT( CLIHistoryTail ) )
232 CLIHistoryCurrent = RING_NEXT( CLIHistoryCurrent );
233 CLI_retreiveHistory( CLIHistoryCurrent );
239 case 0x7F: // Backspace
240 // TODO - Does not handle case for arrow editing (arrows disabled atm)
241 CLILineBufferCurrent--; // Remove the backspace
243 // If there are characters in the buffer
244 if ( CLILineBufferCurrent > 0 )
246 // Remove character from current position in the line buffer
247 CLILineBufferCurrent--;
249 // Remove character from tty
256 // Place a null on the end (to use with string print)
257 CLILineBuffer[CLILineBufferCurrent] = '\0';
259 // Output buffer to screen
260 dPrint( &CLILineBuffer[prev_buf_pos] );
270 // Takes a string, returns two pointers
271 // One to the first non-space character
272 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
273 // Places a NULL at the first space after the first argument
274 void CLI_argumentIsolation( char* string, char** first, char** second )
276 // Mark out the first argument
277 // This is done by finding the first space after a list of non-spaces and setting it NULL
278 char* cmdPtr = string - 1;
279 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
281 // Locates first space delimiter
282 char* argPtr = cmdPtr + 1;
283 while ( *argPtr != ' ' && *argPtr != '\0' )
286 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
287 (++argPtr)[-1] = '\0';
289 // Set return variables
294 // Scans the CLILineBuffer for any valid commands
295 void CLI_commandLookup()
297 // Ignore command if buffer is 0 length
298 if ( CLILineBufferCurrent == 0 )
301 // Set the last+1 character of the buffer to NULL for string processing
302 CLILineBuffer[CLILineBufferCurrent] = '\0';
304 // Retrieve pointers to command and beginning of arguments
305 // Places a NULL at the first space after the command
308 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
310 // Scan array of dictionaries for a valid command match
311 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
313 // Parse each cmd until a null command entry is found, or an argument match
314 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
316 // Compare the first argument and each command entry
317 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
319 // Run the specified command function pointer
320 // argPtr is already pointing at the first character of the arguments
321 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
328 // No match for the command...
330 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
333 // Registers a command dictionary with the CLI
334 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
336 // Make sure this max limit of dictionaries hasn't been reached
337 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
339 erro_print("Max number of dictionaries defined already...");
344 CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
345 CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
348 inline void CLI_tabCompletion()
350 // Ignore command if buffer is 0 length
351 if ( CLILineBufferCurrent == 0 )
354 // Set the last+1 character of the buffer to NULL for string processing
355 CLILineBuffer[CLILineBufferCurrent] = '\0';
357 // Retrieve pointers to command and beginning of arguments
358 // Places a NULL at the first space after the command
361 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
367 // Scan array of dictionaries for a valid command match
368 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
370 // Parse each cmd until a null command entry is found, or an argument match
371 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
373 // Compare the first argument piece to each command entry to see if it is "like"
374 // NOTE: To save on processing, we only care about the commands and ignore the arguments
375 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
376 // Also ignores full matches
377 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
379 // TODO Make list of commands if multiple matches
381 tabMatch = (char*)CLIDict[dict][cmd].name;
386 // Only tab complete if there was 1 match
390 CLILineBufferCurrent = 0;
392 // Reprint the prompt (automatically clears the line)
395 // Display the command
398 // There are no index counts, so just copy the whole string to the input buffer
399 while ( *tabMatch != '\0' )
401 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
406 inline int CLI_wrap( int kX, int const kLowerBound, int const kUpperBound )
408 int range_size = kUpperBound - kLowerBound + 1;
410 if ( kX < kLowerBound )
411 kX += range_size * ((kLowerBound - kX) / range_size + 1);
413 return kLowerBound + (kX - kLowerBound) % range_size;
416 inline void CLI_saveHistory( char *buff )
421 CLIHistoryBuffer[ CLIHistoryTail ][ 0 ] = '\0';
425 // Don't write empty lines to the history
426 const char *cursor = buff;
427 while (*cursor == ' ') { cursor++; } // advance past the leading whitespace
428 if (*cursor == '\0') { return ; }
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 if ( flashModeEnabled_define == 0 )
523 warn_print("flashModeEnabled not set, cancelling firmware reload...");
524 info_msg("Set flashModeEnabled to 1 in your kll configuration.");
528 // Request to output module to be set into firmware reload mode
529 Output_firmwareReload();
532 void cliFunc_reset( char* args )
534 print("\033c"); // Resets the terminal
537 void cliFunc_restart( char* args )
539 // Trigger an overall software reset
543 void cliFunc_version( char* args )
546 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
547 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
548 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus CLI_ModifiedFiles NL );
549 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
550 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
551 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
552 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
553 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
554 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
555 print( " \033[1mChip:\033[0m " CLI_Chip NL );
556 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
557 print( " \033[1mDevice:\033[0m " CLI_Device NL );
558 print( " \033[1mModules:\033[0m " CLI_Modules NL );
559 #if defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
560 print( " \033[1mUnique Id:\033[0m " );
561 printHex32_op( SIM_UIDH, 4 );
562 printHex32_op( SIM_UIDMH, 4 );
563 printHex32_op( SIM_UIDML, 4 );
564 printHex32_op( SIM_UIDL, 4 );
565 #elif defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_)
567 #error "No unique id defined."