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] )
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 )
157 CLILineBufferCurrent--;
159 // Process the current line buffer
162 // Add the command to the history
163 cli_saveHistory(CLILineBuffer);
165 // Keep the array circular, discarding the older entries
166 if (CLIHistoryTail < CLIHistoryHead)
167 CLIHistoryHead = (CLIHistoryHead+1)%CLIMaxHistorySize;
169 if (CLIHistoryTail==CLIMaxHistorySize)
175 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
176 cli_saveHistory(NULL); // delete the old temp buffer
179 CLILineBufferCurrent = 0;
181 // Reset the prompt after processing has finished
185 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
186 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
190 // Tab completion for the current command
193 CLILineBufferCurrent--; // Remove the Tab
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
199 case 0x1B: // Esc / Escape codes
200 // Check for other escape sequence
202 // \e[ is an escape code in vt100 compatable terminals
203 if (CLILineBufferCurrent>=prev_buf_pos+3
204 && CLILineBuffer[prev_buf_pos]==0x1B
205 && CLILineBuffer[prev_buf_pos+1]==0x5B)
207 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
209 if (CLILineBuffer[prev_buf_pos+2]==0x41) // Hist prev
211 if (CLIHistoryCurrent==CLIHistoryTail)
213 // Is first time pressing arrow. Save the current buffer
214 CLILineBuffer[prev_buf_pos] = '\0';
215 cli_saveHistory(CLILineBuffer);
218 // Grab the previus item from the history if there is one
219 if (RING_PREV(CLIHistoryCurrent)!=RING_PREV(CLIHistoryHead))
220 CLIHistoryCurrent = RING_PREV(CLIHistoryCurrent);
221 cli_retreiveHistory(CLIHistoryCurrent);
223 if (CLILineBuffer[prev_buf_pos+2]==0x42) // Hist next
225 // Grab the next item from the history if it exists
226 if (RING_NEXT(CLIHistoryCurrent)!=RING_NEXT(CLIHistoryTail))
227 CLIHistoryCurrent = RING_NEXT(CLIHistoryCurrent);
228 cli_retreiveHistory(CLIHistoryCurrent);
234 case 0x7F: // Backspace
235 // TODO - Does not handle case for arrow editing (arrows disabled atm)
236 CLILineBufferCurrent--; // Remove the backspace
238 // If there are characters in the buffer
239 if ( CLILineBufferCurrent > 0 )
241 // Remove character from current position in the line buffer
242 CLILineBufferCurrent--;
244 // Remove character from tty
251 // Place a null on the end (to use with string print)
252 CLILineBuffer[CLILineBufferCurrent] = '\0';
254 // Output buffer to screen
255 dPrint( &CLILineBuffer[prev_buf_pos] );
265 // Takes a string, returns two pointers
266 // One to the first non-space character
267 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
268 // Places a NULL at the first space after the first argument
269 void CLI_argumentIsolation( char* string, char** first, char** second )
271 // Mark out the first argument
272 // This is done by finding the first space after a list of non-spaces and setting it NULL
273 char* cmdPtr = string - 1;
274 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
276 // Locates first space delimiter
277 char* argPtr = cmdPtr + 1;
278 while ( *argPtr != ' ' && *argPtr != '\0' )
281 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
282 (++argPtr)[-1] = '\0';
284 // Set return variables
289 // Scans the CLILineBuffer for any valid commands
290 void CLI_commandLookup()
292 // Ignore command if buffer is 0 length
293 if ( CLILineBufferCurrent == 0 )
296 // Set the last+1 character of the buffer to NULL for string processing
297 CLILineBuffer[CLILineBufferCurrent] = '\0';
299 // Retrieve pointers to command and beginning of arguments
300 // Places a NULL at the first space after the command
303 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
305 // Scan array of dictionaries for a valid command match
306 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
308 // Parse each cmd until a null command entry is found, or an argument match
309 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
311 // Compare the first argument and each command entry
312 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
314 // Run the specified command function pointer
315 // argPtr is already pointing at the first character of the arguments
316 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
323 // No match for the command...
325 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
328 // Registers a command dictionary with the CLI
329 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
331 // Make sure this max limit of dictionaries hasn't been reached
332 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
334 erro_print("Max number of dictionaries defined already...");
339 CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
340 CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
343 inline void CLI_tabCompletion()
345 // Ignore command if buffer is 0 length
346 if ( CLILineBufferCurrent == 0 )
349 // Set the last+1 character of the buffer to NULL for string processing
350 CLILineBuffer[CLILineBufferCurrent] = '\0';
352 // Retrieve pointers to command and beginning of arguments
353 // Places a NULL at the first space after the command
356 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
362 // Scan array of dictionaries for a valid command match
363 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
365 // Parse each cmd until a null command entry is found, or an argument match
366 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
368 // Compare the first argument piece to each command entry to see if it is "like"
369 // NOTE: To save on processing, we only care about the commands and ignore the arguments
370 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
371 // Also ignores full matches
372 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
374 // TODO Make list of commands if multiple matches
376 tabMatch = (char*)CLIDict[dict][cmd].name;
381 // Only tab complete if there was 1 match
385 CLILineBufferCurrent = 0;
387 // Reprint the prompt (automatically clears the line)
390 // Display the command
393 // There are no index counts, so just copy the whole string to the input buffer
394 while ( *tabMatch != '\0' )
396 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
401 inline int wrap(int kX, int const kLowerBound, int const kUpperBound)
403 int range_size = kUpperBound - kLowerBound + 1;
405 if (kX < kLowerBound)
406 kX += range_size * ((kLowerBound - kX) / range_size + 1);
408 return kLowerBound + (kX - kLowerBound) % range_size;
411 inline void cli_saveHistory(char *buff) {
414 CLIHistoryBuffer[CLIHistoryTail][0] = '\0';
418 // Copy the line to the history
420 for (i=0; i<CLILineBufferCurrent; i++)
422 CLIHistoryBuffer[CLIHistoryTail][i] = CLILineBuffer[i];
426 void cli_retreiveHistory(int index) {
427 char *histMatch = CLIHistoryBuffer[index];
430 CLILineBufferCurrent = 0;
432 // Reprint the prompt (automatically clears the line)
435 // Display the command
438 // There are no index counts, so just copy the whole string to the input buffe
439 CLILineBufferCurrent = 0;
440 while ( *histMatch != '\0' )
442 CLILineBuffer[CLILineBufferCurrent++] = *histMatch++;
448 // ----- CLI Command Functions -----
450 void cliFunc_clear( char* args)
452 print("\033[2J\033[H\r"); // Erases the whole screen
455 void cliFunc_cliDebug( char* args )
457 // Toggle Hex Debug Mode
458 if ( CLIHexDebugMode )
461 info_print("Hex debug mode disabled...");
467 info_print("Hex debug mode enabled...");
472 void cliFunc_help( char* args )
474 // Scan array of dictionaries and print every description
475 // (no alphabetical here, too much processing/memory to sort...)
476 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
478 // Print the name of each dictionary as a title
479 print( NL "\033[1;32m" );
480 _print( CLIDictNames[dict] ); // This print is requride by AVR (flash)
481 print( "\033[0m" NL );
483 // Parse each cmd/description until a null command entry is found
484 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
486 dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
488 // Determine number of spaces to tab by the length of the command and TabAlign
489 uint8_t padLength = CLIEntryTabAlign - lenStr( (char*)CLIDict[dict][cmd].name );
490 while ( padLength-- > 0 )
493 _print( CLIDict[dict][cmd].description ); // This print is required by AVR (flash)
499 void cliFunc_led( char* args )
501 CLILEDState ^= 1 << 1; // Toggle between 0 and 1
502 errorLED( CLILEDState ); // Enable/Disable error LED
505 void cliFunc_reload( char* args )
507 // Request to output module to be set into firmware reload mode
508 Output_firmwareReload();
511 void cliFunc_reset( char* args )
513 print("\033c"); // Resets the terminal
516 void cliFunc_restart( char* args )
518 // Trigger an overall software reset
522 void cliFunc_version( char* args )
525 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
526 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
527 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus CLI_ModifiedFiles NL );
528 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
529 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
530 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
531 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
532 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
533 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
534 print( " \033[1mChip:\033[0m " CLI_Chip NL );
535 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
536 print( " \033[1mDevice:\033[0m " CLI_Device NL );
537 print( " \033[1mModules:\033[0m " CLI_Modules NL );