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;
78 // Register first dictionary
79 CLIDictionariesUsed = 0;
80 CLI_registerDictionary( basicCLIDict, basicCLIDictName );
82 // Initialize main LED
86 // Hex debug mode is off by default
90 // Query the serial input buffer for any new characters
93 // Current buffer position
94 uint8_t prev_buf_pos = CLILineBufferCurrent;
96 // Process each character while available
99 // No more characters to process
100 if ( Output_availablechar() == 0 )
103 // Retrieve from output module
104 char cur_char = (char)Output_getchar();
106 // Make sure buffer isn't full
107 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
110 erro_print("Serial line buffer is full, dropping character and resetting...");
113 CLILineBufferCurrent = 0;
121 // Place into line buffer
122 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
125 // Display Hex Key Input if enabled
126 if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
128 print("\033[s\r\n"); // Save cursor position, and move to the next line
129 print("\033[2K"); // Erases the current line
131 uint8_t pos = prev_buf_pos;
132 while ( CLILineBufferCurrent > pos )
134 printHex( CLILineBuffer[pos++] );
138 print("\033[u"); // Restore cursor position
141 // If buffer has changed, output to screen while there are still characters in the buffer not displayed
142 while ( CLILineBufferCurrent > prev_buf_pos )
144 // Check for control characters
145 switch ( CLILineBuffer[prev_buf_pos] )
148 CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
150 // Remove the space if there is no command
151 if ( CLILineBufferCurrent == 1 )
152 CLILineBufferCurrent--;
154 // Process the current line buffer
158 CLILineBufferCurrent = 0;
160 // Reset the prompt after processing has finished
164 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
165 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
169 // Tab completion for the current command
172 CLILineBufferCurrent--; // Remove the Tab
174 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
175 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
179 // Check for escape sequence
184 case 0x7F: // Backspace
185 // TODO - Does not handle case for arrow editing (arrows disabled atm)
186 CLILineBufferCurrent--; // Remove the backspace
188 // If there are characters in the buffer
189 if ( CLILineBufferCurrent > 0 )
191 // Remove character from current position in the line buffer
192 CLILineBufferCurrent--;
194 // Remove character from tty
201 // Place a null on the end (to use with string print)
202 CLILineBuffer[CLILineBufferCurrent] = '\0';
204 // Output buffer to screen
205 dPrint( &CLILineBuffer[prev_buf_pos] );
215 // Takes a string, returns two pointers
216 // One to the first non-space character
217 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
218 // Places a NULL at the first space after the first argument
219 void CLI_argumentIsolation( char* string, char** first, char** second )
221 // Mark out the first argument
222 // This is done by finding the first space after a list of non-spaces and setting it NULL
223 char* cmdPtr = string - 1;
224 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
226 // Locates first space delimiter
227 char* argPtr = cmdPtr + 1;
228 while ( *argPtr != ' ' && *argPtr != '\0' )
231 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
232 (++argPtr)[-1] = '\0';
234 // Set return variables
239 // Scans the CLILineBuffer for any valid commands
240 void CLI_commandLookup()
242 // Ignore command if buffer is 0 length
243 if ( CLILineBufferCurrent == 0 )
246 // Set the last+1 character of the buffer to NULL for string processing
247 CLILineBuffer[CLILineBufferCurrent] = '\0';
249 // Retrieve pointers to command and beginning of arguments
250 // Places a NULL at the first space after the command
253 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
255 // Scan array of dictionaries for a valid command match
256 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
258 // Parse each cmd until a null command entry is found, or an argument match
259 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
261 // Compare the first argument and each command entry
262 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
264 // Run the specified command function pointer
265 // argPtr is already pointing at the first character of the arguments
266 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
273 // No match for the command...
275 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
278 // Registers a command dictionary with the CLI
279 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
281 // Make sure this max limit of dictionaries hasn't been reached
282 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
284 erro_print("Max number of dictionaries defined already...");
289 CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
290 CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
293 inline void CLI_tabCompletion()
295 // Ignore command if buffer is 0 length
296 if ( CLILineBufferCurrent == 0 )
299 // Set the last+1 character of the buffer to NULL for string processing
300 CLILineBuffer[CLILineBufferCurrent] = '\0';
302 // Retrieve pointers to command and beginning of arguments
303 // Places a NULL at the first space after the command
306 CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
312 // Scan array of dictionaries for a valid command match
313 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
315 // Parse each cmd until a null command entry is found, or an argument match
316 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
318 // Compare the first argument piece to each command entry to see if it is "like"
319 // NOTE: To save on processing, we only care about the commands and ignore the arguments
320 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
321 // Also ignores full matches
322 if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
324 // TODO Make list of commands if multiple matches
326 tabMatch = (char*)CLIDict[dict][cmd].name;
331 // Only tab complete if there was 1 match
335 CLILineBufferCurrent = 0;
337 // Reprint the prompt (automatically clears the line)
340 // Display the command
343 // There are no index counts, so just copy the whole string to the input buffer
344 while ( *tabMatch != '\0' )
346 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
353 // ----- CLI Command Functions -----
355 void cliFunc_clear( char* args)
357 print("\033[2J\033[H\r"); // Erases the whole screen
360 void cliFunc_cliDebug( char* args )
362 // Toggle Hex Debug Mode
363 if ( CLIHexDebugMode )
366 info_print("Hex debug mode disabled...");
372 info_print("Hex debug mode enabled...");
377 void cliFunc_help( char* args )
379 // Scan array of dictionaries and print every description
380 // (no alphabetical here, too much processing/memory to sort...)
381 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
383 // Print the name of each dictionary as a title
384 print( NL "\033[1;32m" );
385 _print( CLIDictNames[dict] ); // This print is requride by AVR (flash)
386 print( "\033[0m" NL );
388 // Parse each cmd/description until a null command entry is found
389 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
391 dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
393 // Determine number of spaces to tab by the length of the command and TabAlign
394 uint8_t padLength = CLIEntryTabAlign - lenStr( (char*)CLIDict[dict][cmd].name );
395 while ( padLength-- > 0 )
398 _print( CLIDict[dict][cmd].description ); // This print is required by AVR (flash)
404 void cliFunc_led( char* args )
406 CLILEDState ^= 1 << 1; // Toggle between 0 and 1
407 errorLED( CLILEDState ); // Enable/Disable error LED
410 void cliFunc_reload( char* args )
412 // Request to output module to be set into firmware reload mode
413 Output_firmwareReload();
416 void cliFunc_reset( char* args )
418 print("\033c"); // Resets the terminal
421 void cliFunc_restart( char* args )
423 // Trigger an overall software reset
427 void cliFunc_version( char* args )
430 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
431 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
432 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus CLI_ModifiedFiles NL );
433 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
434 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
435 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
436 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
437 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
438 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
439 print( " \033[1mChip:\033[0m " CLI_Chip NL );
440 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
441 print( " \033[1mDevice:\033[0m " CLI_Device NL );
442 print( " \033[1mModules:\033[0m " CLI_Modules NL );