1 /* Copyright (C) 2014 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 char* basicCLIDictName = "General Commands";
39 CLIDictItem basicCLIDict[] = {
40 { "cliDebug", "Enables/Disables hex output of the most recent cli input.", cliFunc_cliDebug },
41 { "help", "You're looking at it :P", cliFunc_help },
42 { "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...", cliFunc_led },
43 { "reload", "Signals microcontroller to reflash/reload.", cliFunc_reload },
44 { "reset", "Resets the terminal back to initial settings.", cliFunc_reset },
45 { "restart", "Sends a software restart, should be similar to powering on the device.", cliFunc_restart },
46 { "version", "Version information about this firmware.", cliFunc_version },
47 { 0, 0, 0 } // Null entry for dictionary end
52 // ----- Functions -----
56 print("\033[2K\r"); // Erases the current line and resets cursor to beginning of line
57 print("\033[1;34m:\033[0m "); // Blue bold prompt
61 inline void init_cli()
63 // Reset the Line Buffer
64 CLILineBufferCurrent = 0;
69 // Register first dictionary
70 CLIDictionariesUsed = 0;
71 registerDictionary_cli( basicCLIDict, basicCLIDictName );
73 // Initialize main LED
77 // Hex debug mode is off by default
81 // Query the serial input buffer for any new characters
84 // Current buffer position
85 uint8_t prev_buf_pos = CLILineBufferCurrent;
87 // Process each character while available
91 // No more characters to process
92 result = usb_serial_getchar(); // Retrieve from serial module // TODO Make USB agnostic
96 char cur_char = (char)result;
98 // Make sure buffer isn't full
99 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
102 erro_print("Serial line buffer is full, dropping character and resetting...");
105 CLILineBufferCurrent = 0;
113 // Place into line buffer
114 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
117 // Display Hex Key Input if enabled
118 if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
120 print("\033[s\r\n"); // Save cursor position, and move to the next line
121 print("\033[2K"); // Erases the current line
123 uint8_t pos = prev_buf_pos;
124 while ( CLILineBufferCurrent > pos )
126 printHex( CLILineBuffer[pos++] );
130 print("\033[u"); // Restore cursor position
133 // If buffer has changed, output to screen while there are still characters in the buffer not displayed
134 while ( CLILineBufferCurrent > prev_buf_pos )
136 // Check for control characters
137 switch ( CLILineBuffer[prev_buf_pos] )
140 CLILineBufferCurrent--; // Remove the Enter
142 // Process the current line buffer
146 CLILineBufferCurrent = 0;
148 // Reset the prompt after processing has finished
152 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
153 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
157 // Tab completion for the current command
160 CLILineBufferCurrent--; // Remove the Tab
162 // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
163 // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
167 // Check for escape sequence
172 case 0x7F: // Backspace
173 // TODO - Does not handle case for arrow editing (arrows disabled atm)
174 CLILineBufferCurrent--; // Remove the backspace
176 // If there are characters in the buffer
177 if ( CLILineBufferCurrent > 0 )
179 // Remove character from current position in the line buffer
180 CLILineBufferCurrent--;
182 // Remove character from tty
189 // Place a null on the end (to use with string print)
190 CLILineBuffer[CLILineBufferCurrent] = '\0';
192 // Output buffer to screen
193 dPrint( &CLILineBuffer[prev_buf_pos] );
203 // Takes a string, returns two pointers
204 // One to the first non-space character
205 // The second to the next argument (first NULL if there isn't an argument). delimited by a space
206 // Places a NULL at the first space after the first argument
207 inline void argumentIsolation_cli( char* string, char** first, char** second )
209 // Mark out the first argument
210 // This is done by finding the first space after a list of non-spaces and setting it NULL
211 char* cmdPtr = string - 1;
212 while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
214 // Locates first space delimiter
215 char* argPtr = cmdPtr + 1;
216 while ( *argPtr != ' ' && *argPtr != '\0' )
219 // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
220 (++argPtr)[-1] = '\0';
222 // Set return variables
227 // Scans the CLILineBuffer for any valid commands
228 void commandLookup_cli()
230 // Ignore command if buffer is 0 length
231 if ( CLILineBufferCurrent == 0 )
234 // Set the last+1 character of the buffer to NULL for string processing
235 CLILineBuffer[CLILineBufferCurrent] = '\0';
237 // Retrieve pointers to command and beginning of arguments
238 // Places a NULL at the first space after the command
241 argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
243 // Scan array of dictionaries for a valid command match
244 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
246 // Parse each cmd until a null command entry is found, or an argument match
247 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
249 // Compare the first argument and each command entry
250 if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == -1 )
252 // Run the specified command function pointer
253 // argPtr is already pointing at the first character of the arguments
254 (*CLIDict[dict][cmd].function)( argPtr );
261 // No match for the command...
263 erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
266 // Registers a command dictionary with the CLI
267 inline void registerDictionary_cli( CLIDictItem *cmdDict, char* dictName )
269 // Make sure this max limit of dictionaries hasn't been reached
270 if ( CLIDictionariesUsed >= CLIMaxDictionaries )
272 erro_print("Max number of dictionaries defined already...");
277 CLIDictNames[CLIDictionariesUsed] = dictName;
278 CLIDict[CLIDictionariesUsed++] = cmdDict;
281 inline void tabCompletion_cli()
283 // Ignore command if buffer is 0 length
284 if ( CLILineBufferCurrent == 0 )
287 // Set the last+1 character of the buffer to NULL for string processing
288 CLILineBuffer[CLILineBufferCurrent] = '\0';
290 // Retrieve pointers to command and beginning of arguments
291 // Places a NULL at the first space after the command
294 argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
300 // Scan array of dictionaries for a valid command match
301 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
303 // Parse each cmd until a null command entry is found, or an argument match
304 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
306 // Compare the first argument piece to each command entry to see if it is "like"
307 // NOTE: To save on processing, we only care about the commands and ignore the arguments
308 // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
309 // Also ignores full matches
310 if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == 0 )
312 // TODO Make list of commands if multiple matches
314 tabMatch = CLIDict[dict][cmd].name;
319 // Only tab complete if there was 1 match
323 CLILineBufferCurrent = 0;
325 // Reprint the prompt (automatically clears the line)
328 // Display the command
331 // There are no index counts, so just copy the whole string to the input buffer
332 while ( *tabMatch != '\0' )
334 CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
341 // ----- CLI Command Functions -----
343 void cliFunc_cliDebug( char* args )
345 // Toggle Hex Debug Mode
346 if ( CLIHexDebugMode )
349 info_print("Hex debug mode disabled...");
355 info_print("Hex debug mode enabled...");
360 void cliFunc_help( char* args )
362 // Scan array of dictionaries and print every description
363 // (no alphabetical here, too much processing/memory to sort...)
364 for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
366 // Print the name of each dictionary as a title
367 dPrintStrsNL( NL, "\033[1;32m", CLIDictNames[dict], "\033[0m" );
369 // Parse each cmd/description until a null command entry is found
370 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
372 dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
374 // Determine number of spaces to tab by the length of the command and TabAlign
375 uint8_t padLength = CLIEntryTabAlign - lenStr( CLIDict[dict][cmd].name );
376 while ( padLength-- > 0 )
379 dPrintStrNL( CLIDict[dict][cmd].description );
384 void cliFunc_led( char* args )
386 CLILEDState ^= 1 << 1; // Toggle between 0 and 1
387 errorLED( CLILEDState ); // Enable/Disable error LED
390 void cliFunc_reload( char* args )
392 // Request to output module to be set into firmware reload mode
393 output_firmwareReload();
396 void cliFunc_reset( char* args )
398 print("\033c"); // Resets the terminal
401 void cliFunc_restart( char* args )
403 // Trigger an overall software reset
407 void cliFunc_version( char* args )
410 print( " \033[1mRevision:\033[0m " CLI_Revision NL );
411 print( " \033[1mBranch:\033[0m " CLI_Branch NL );
412 print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus NL );
413 print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
414 print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
415 print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
416 print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
417 print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
418 print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
419 print( " \033[1mChip:\033[0m " CLI_Chip NL );
420 print( " \033[1mCPU:\033[0m " CLI_CPU NL );
421 print( " \033[1mDevice:\033[0m " CLI_Device NL );
422 print( " \033[1mModules:\033[0m " CLI_Modules NL );