]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Debug/cli/cli.c
Added more CLI commands.
[kiibohd-controller.git] / Debug / cli / cli.c
1 /* Copyright (C) 2014 by Jacob Alexander
2  *
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:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
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
19  * THE SOFTWARE.
20  */
21
22 // ----- Includes -----
23
24 // Compiler Includes
25 //#include <stdarg.h>
26
27 // Project Includes
28 #include <buildvars.h>
29 #include "cli.h"
30 #include <led.h>
31 #include <print.h>
32
33
34
35 // ----- Variables -----
36
37 // Basic command dictionary
38 CLIDictItem basicCLIDict[] = {
39         { "cliDebug", "Enables/Disables hex output of the most recent cli input.", cliFunc_cliDebug },
40         { "help",     "You're looking at it :P", cliFunc_help },
41         { "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 },
42         { "reload",   "Signals microcontroller to reflash/reload.", cliFunc_reload },
43         { "reset",    "Resets the terminal back to initial settings.", cliFunc_reset },
44         { "restart",  "Sends a software restart, should be similar to powering on the device.", cliFunc_restart },
45         { "version",  "Version information about this firmware.", cliFunc_version },
46         { 0, 0, 0 } // Null entry for dictionary end
47 };
48
49
50
51 // ----- Functions -----
52
53 inline void prompt()
54 {
55         print("\033[2K"); // Erases the current line
56         print(": ");
57 }
58
59 // Initialize the CLI
60 inline void init_cli()
61 {
62         // Reset the Line Buffer
63         CLILineBufferCurrent = 0;
64
65         // Set prompt
66         prompt();
67
68         // Register first dictionary
69         CLIDictionariesUsed = 0;
70         registerDictionary_cli( basicCLIDict );
71
72         // Initialize main LED
73         init_errorLED();
74         CLILEDState = 0;
75
76         // Hex debug mode is off by default
77         CLIHexDebugMode = 0;
78 }
79
80 // Query the serial input buffer for any new characters
81 void process_cli()
82 {
83         // Current buffer position
84         uint8_t prev_buf_pos = CLILineBufferCurrent;
85
86         // Process each character while available
87         int result = 0;
88         while ( 1 )
89         {
90                 // No more characters to process
91                 result = usb_serial_getchar(); // Retrieve from serial module // TODO Make USB agnostic
92                 if ( result == -1 )
93                         break;
94
95                 char cur_char = (char)result;
96
97                 // Make sure buffer isn't full
98                 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
99                 {
100                         print( NL );
101                         erro_print("Serial line buffer is full, dropping character and resetting...");
102
103                         // Clear buffer
104                         CLILineBufferCurrent = 0;
105
106                         // Reset the prompt
107                         prompt();
108
109                         return;
110                 }
111
112                 // Place into line buffer
113                 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
114         }
115
116         // Display Hex Key Input if enabled
117         if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
118         {
119                 print("\033[s\r\n"); // Save cursor position, and move to the next line
120                 print("\033[2K");    // Erases the current line
121
122                 uint8_t pos = prev_buf_pos;
123                 while ( CLILineBufferCurrent > pos )
124                 {
125                         printHex( CLILineBuffer[pos++] );
126                         print(" ");
127                 }
128
129                 print("\033[u"); // Restore cursor position
130         }
131
132         // If buffer has changed, output to screen while there are still characters in the buffer not displayed
133         while ( CLILineBufferCurrent > prev_buf_pos )
134         {
135                 // Check for control characters
136                 switch ( CLILineBuffer[prev_buf_pos] )
137                 {
138                 case 0x0D: // Enter
139                         CLILineBufferCurrent--; // Remove the Enter
140
141                         // Process the current line buffer
142                         commandLookup_cli();
143
144                         // Reset the buffer
145                         CLILineBufferCurrent = 0;
146
147                         // Reset the prompt after processing has finished
148                         print( NL );
149                         prompt();
150
151                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
152                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
153                         return;
154
155                 case 0x09: // Tab
156                         // Tab completion for the current command
157                         // TODO
158                         return;
159
160                 case 0x1B: // Esc
161                         // Check for escape sequence
162                         // TODO
163                         return;
164
165                 case 0x08:
166                 case 0x7F: // Backspace
167                         // TODO - Does not handle case for arrow editing (arrows disabled atm)
168                         CLILineBufferCurrent--; // Remove the backspace
169
170                         // If there are characters in the buffer
171                         if ( CLILineBufferCurrent > 0 )
172                         {
173                                 // Remove character from current position in the line buffer
174                                 CLILineBufferCurrent--;
175
176                                 // Remove character from tty
177                                 print("\b \b");
178                         }
179
180                         break;
181
182                 default:
183                         // Place a null on the end (to use with string print)
184                         CLILineBuffer[CLILineBufferCurrent] = '\0';
185
186                         // Output buffer to screen
187                         dPrint( &CLILineBuffer[prev_buf_pos] );
188
189                         // Buffer reset
190                         prev_buf_pos++;
191
192                         break;
193                 }
194         }
195 }
196
197 // Takes a string, returns two pointers
198 //  One to the first non-space character
199 //  The second to the next argument (first NULL if there isn't an argument). delimited by a space
200 //  Places a NULL at the first space after the first argument
201 inline void argumentIsolation_cli( char* string, char** first, char** second )
202 {
203         // Mark out the first argument
204         // This is done by finding the first space after a list of non-spaces and setting it NULL
205         char* cmdPtr = string - 1;
206         while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
207
208         // Locates first space delimiter
209         char* argPtr = cmdPtr + 1;
210         while ( *argPtr != ' ' && *argPtr != '\0' )
211                 argPtr++;
212
213         // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
214         (++argPtr)[-1] = '\0';
215
216         // Set return variables
217         *first = cmdPtr;
218         *second = argPtr;
219 }
220
221 // Scans the CLILineBuffer for any valid commands
222 void commandLookup_cli()
223 {
224         // Ignore command if buffer is 0 length
225         if ( CLILineBufferCurrent == 0 )
226                 return;
227
228         // Set the last+1 character of the buffer to NULL for string processing
229         CLILineBuffer[CLILineBufferCurrent] = '\0';
230
231         // Retrieve pointers to command and beginning of arguments
232         // Places a NULL at the first space after the command
233         char* cmdPtr;
234         char* argPtr;
235         argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
236
237         // Scan array of dictionaries for a valid command match
238         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
239         {
240                 // Parse each cmd until a null command entry is found, or an argument match
241                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
242                 {
243                         // Compare the first argument and each command entry
244                         if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) )
245                         {
246                                 // Run the specified command function pointer
247                                 //   argPtr is already pointing at the first character of the arguments
248                                 (*CLIDict[dict][cmd].function)( argPtr );
249
250                                 return;
251                         }
252                 }
253         }
254
255         // No match for the command...
256         print( NL );
257         erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
258 }
259
260 // Registers a command dictionary with the CLI
261 inline void registerDictionary_cli( CLIDictItem *cmdDict )
262 {
263         // Make sure this max limit of dictionaries hasn't been reached
264         if ( CLIDictionariesUsed >= CLIMaxDictionaries )
265         {
266                 erro_print("Max number of dictionaries defined already...");
267                 return;
268         }
269
270         // Add dictionary
271         CLIDict[CLIDictionariesUsed++] = cmdDict;
272 }
273
274
275
276 // ----- CLI Command Functions -----
277
278 void cliFunc_cliDebug( char* args )
279 {
280         // Toggle Hex Debug Mode
281         if ( CLIHexDebugMode )
282         {
283                 print( NL );
284                 info_print("Hex debug mode disabled...");
285                 CLIHexDebugMode = 0;
286         }
287         else
288         {
289                 print( NL );
290                 info_print("Hex debug mode enabled...");
291                 CLIHexDebugMode = 1;
292         }
293 }
294
295 void cliFunc_help( char* args )
296 {
297         // Scan array of dictionaries and print every description
298         //  (no alphabetical here, too much processing/memory to sort...)
299         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
300         {
301                 print( NL "\033[1;32mCOMMAND SET\033[0m " );
302                 printInt8( dict + 1 );
303                 print( NL );
304
305                 // Parse each cmd/description until a null command entry is found
306                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
307                 {
308                         dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
309
310                         // Determine number of spaces to tab by the length of the command and TabAlign
311                         uint8_t padLength = CLIEntryTabAlign - lenStr( CLIDict[dict][cmd].name );
312                         while ( padLength-- > 0 )
313                                 print(" ");
314
315                         dPrintStrNL( CLIDict[dict][cmd].description );
316                 }
317         }
318 }
319
320 void cliFunc_led( char* args )
321 {
322         CLILEDState ^= 1 << 1; // Toggle between 0 and 1
323         errorLED( CLILEDState ); // Enable/Disable error LED
324 }
325
326 void cliFunc_reload( char* args )
327 {
328         // Request to output module to be set into firmware reload mode
329         output_firmwareReload();
330 }
331
332 void cliFunc_reset( char* args )
333 {
334         print("\033c"); // Resets the terminal
335 }
336
337 void cliFunc_restart( char* args )
338 {
339         // Trigger an overall software reset
340         SOFTWARE_RESET();
341 }
342
343 void cliFunc_version( char* args )
344 {
345         print( NL );
346         print( " \033[1mRevision:\033[0m      " CLI_Revision       NL );
347         print( " \033[1mBranch:\033[0m        " CLI_Branch         NL );
348         print( " \033[1mTree Status:\033[0m   " CLI_ModifiedStatus NL );
349         print( " \033[1mRepo Origin:\033[0m   " CLI_RepoOrigin     NL );
350         print( " \033[1mCommit Date:\033[0m   " CLI_CommitDate     NL );
351         print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor   NL );
352         print( " \033[1mBuild Date:\033[0m    " CLI_BuildDate      NL );
353         print( " \033[1mBuild OS:\033[0m      " CLI_BuildOS        NL );
354         print( " \033[1mArchitecture:\033[0m  " CLI_Arch           NL );
355         print( " \033[1mChip:\033[0m          " CLI_Chip           NL );
356         print( " \033[1mCPU:\033[0m           " CLI_CPU            NL );
357         print( " \033[1mDevice:\033[0m        " CLI_Device         NL );
358         print( " \033[1mModules:\033[0m       " CLI_Modules        NL );
359 }
360