]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Debug/cli/cli.c
Force curve gauge is feature complete!!
[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 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
48 };
49
50
51
52 // ----- Functions -----
53
54 inline void prompt()
55 {
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
58 }
59
60 // Initialize the CLI
61 inline void init_cli()
62 {
63         // Reset the Line Buffer
64         CLILineBufferCurrent = 0;
65
66         // Set prompt
67         prompt();
68
69         // Register first dictionary
70         CLIDictionariesUsed = 0;
71         registerDictionary_cli( basicCLIDict, basicCLIDictName );
72
73         // Initialize main LED
74         init_errorLED();
75         CLILEDState = 0;
76
77         // Hex debug mode is off by default
78         CLIHexDebugMode = 0;
79 }
80
81 // Query the serial input buffer for any new characters
82 void process_cli()
83 {
84         // Current buffer position
85         uint8_t prev_buf_pos = CLILineBufferCurrent;
86
87         // Process each character while available
88         int result = 0;
89         while ( 1 )
90         {
91                 // No more characters to process
92                 result = usb_serial_getchar(); // Retrieve from serial module // TODO Make USB agnostic
93                 if ( result == -1 )
94                         break;
95
96                 char cur_char = (char)result;
97
98                 // Make sure buffer isn't full
99                 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
100                 {
101                         print( NL );
102                         erro_print("Serial line buffer is full, dropping character and resetting...");
103
104                         // Clear buffer
105                         CLILineBufferCurrent = 0;
106
107                         // Reset the prompt
108                         prompt();
109
110                         return;
111                 }
112
113                 // Place into line buffer
114                 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
115         }
116
117         // Display Hex Key Input if enabled
118         if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
119         {
120                 print("\033[s\r\n"); // Save cursor position, and move to the next line
121                 print("\033[2K");    // Erases the current line
122
123                 uint8_t pos = prev_buf_pos;
124                 while ( CLILineBufferCurrent > pos )
125                 {
126                         printHex( CLILineBuffer[pos++] );
127                         print(" ");
128                 }
129
130                 print("\033[u"); // Restore cursor position
131         }
132
133         // If buffer has changed, output to screen while there are still characters in the buffer not displayed
134         while ( CLILineBufferCurrent > prev_buf_pos )
135         {
136                 // Check for control characters
137                 switch ( CLILineBuffer[prev_buf_pos] )
138                 {
139                 case 0x0D: // Enter
140                         CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
141
142                         // Remove the space if there is no command
143                         if ( CLILineBufferCurrent == 1 )
144                                 CLILineBufferCurrent--;
145
146                         // Process the current line buffer
147                         commandLookup_cli();
148
149                         // Reset the buffer
150                         CLILineBufferCurrent = 0;
151
152                         // Reset the prompt after processing has finished
153                         print( NL );
154                         prompt();
155
156                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
157                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
158                         return;
159
160                 case 0x09: // Tab
161                         // Tab completion for the current command
162                         tabCompletion_cli();
163
164                         CLILineBufferCurrent--; // Remove the Tab
165
166                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
167                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
168                         return;
169
170                 case 0x1B: // Esc
171                         // Check for escape sequence
172                         // TODO
173                         return;
174
175                 case 0x08:
176                 case 0x7F: // Backspace
177                         // TODO - Does not handle case for arrow editing (arrows disabled atm)
178                         CLILineBufferCurrent--; // Remove the backspace
179
180                         // If there are characters in the buffer
181                         if ( CLILineBufferCurrent > 0 )
182                         {
183                                 // Remove character from current position in the line buffer
184                                 CLILineBufferCurrent--;
185
186                                 // Remove character from tty
187                                 print("\b \b");
188                         }
189
190                         break;
191
192                 default:
193                         // Place a null on the end (to use with string print)
194                         CLILineBuffer[CLILineBufferCurrent] = '\0';
195
196                         // Output buffer to screen
197                         dPrint( &CLILineBuffer[prev_buf_pos] );
198
199                         // Buffer reset
200                         prev_buf_pos++;
201
202                         break;
203                 }
204         }
205 }
206
207 // Takes a string, returns two pointers
208 //  One to the first non-space character
209 //  The second to the next argument (first NULL if there isn't an argument). delimited by a space
210 //  Places a NULL at the first space after the first argument
211 inline void argumentIsolation_cli( char* string, char** first, char** second )
212 {
213         // Mark out the first argument
214         // This is done by finding the first space after a list of non-spaces and setting it NULL
215         char* cmdPtr = string - 1;
216         while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
217
218         // Locates first space delimiter
219         char* argPtr = cmdPtr + 1;
220         while ( *argPtr != ' ' && *argPtr != '\0' )
221                 argPtr++;
222
223         // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
224         (++argPtr)[-1] = '\0';
225
226         // Set return variables
227         *first = cmdPtr;
228         *second = argPtr;
229 }
230
231 // Scans the CLILineBuffer for any valid commands
232 void commandLookup_cli()
233 {
234         // Ignore command if buffer is 0 length
235         if ( CLILineBufferCurrent == 0 )
236                 return;
237
238         // Set the last+1 character of the buffer to NULL for string processing
239         CLILineBuffer[CLILineBufferCurrent] = '\0';
240
241         // Retrieve pointers to command and beginning of arguments
242         // Places a NULL at the first space after the command
243         char* cmdPtr;
244         char* argPtr;
245         argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
246
247         // Scan array of dictionaries for a valid command match
248         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
249         {
250                 // Parse each cmd until a null command entry is found, or an argument match
251                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
252                 {
253                         // Compare the first argument and each command entry
254                         if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == -1 )
255                         {
256                                 // Run the specified command function pointer
257                                 //   argPtr is already pointing at the first character of the arguments
258                                 (*CLIDict[dict][cmd].function)( argPtr );
259
260                                 return;
261                         }
262                 }
263         }
264
265         // No match for the command...
266         print( NL );
267         erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
268 }
269
270 // Registers a command dictionary with the CLI
271 inline void registerDictionary_cli( CLIDictItem *cmdDict, char* dictName )
272 {
273         // Make sure this max limit of dictionaries hasn't been reached
274         if ( CLIDictionariesUsed >= CLIMaxDictionaries )
275         {
276                 erro_print("Max number of dictionaries defined already...");
277                 return;
278         }
279
280         // Add dictionary
281         CLIDictNames[CLIDictionariesUsed] = dictName;
282         CLIDict[CLIDictionariesUsed++] = cmdDict;
283 }
284
285 inline void tabCompletion_cli()
286 {
287         // Ignore command if buffer is 0 length
288         if ( CLILineBufferCurrent == 0 )
289                 return;
290
291         // Set the last+1 character of the buffer to NULL for string processing
292         CLILineBuffer[CLILineBufferCurrent] = '\0';
293
294         // Retrieve pointers to command and beginning of arguments
295         // Places a NULL at the first space after the command
296         char* cmdPtr;
297         char* argPtr;
298         argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
299
300         // Tab match pointer
301         char* tabMatch = 0;
302         uint8_t matches = 0;
303
304         // Scan array of dictionaries for a valid command match
305         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
306         {
307                 // Parse each cmd until a null command entry is found, or an argument match
308                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
309                 {
310                         // Compare the first argument piece to each command entry to see if it is "like"
311                         // NOTE: To save on processing, we only care about the commands and ignore the arguments
312                         //       If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
313                         //       Also ignores full matches
314                         if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == 0 )
315                         {
316                                 // TODO Make list of commands if multiple matches
317                                 matches++;
318                                 tabMatch = CLIDict[dict][cmd].name;
319                         }
320                 }
321         }
322
323         // Only tab complete if there was 1 match
324         if ( matches == 1 )
325         {
326                 // Reset the buffer
327                 CLILineBufferCurrent = 0;
328
329                 // Reprint the prompt (automatically clears the line)
330                 prompt();
331
332                 // Display the command
333                 dPrint( tabMatch );
334
335                 // There are no index counts, so just copy the whole string to the input buffer
336                 while ( *tabMatch != '\0' )
337                 {
338                         CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
339                 }
340         }
341 }
342
343
344
345 // ----- CLI Command Functions -----
346
347 void cliFunc_cliDebug( char* args )
348 {
349         // Toggle Hex Debug Mode
350         if ( CLIHexDebugMode )
351         {
352                 print( NL );
353                 info_print("Hex debug mode disabled...");
354                 CLIHexDebugMode = 0;
355         }
356         else
357         {
358                 print( NL );
359                 info_print("Hex debug mode enabled...");
360                 CLIHexDebugMode = 1;
361         }
362 }
363
364 void cliFunc_help( char* args )
365 {
366         // Scan array of dictionaries and print every description
367         //  (no alphabetical here, too much processing/memory to sort...)
368         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
369         {
370                 // Print the name of each dictionary as a title
371                 dPrintStrsNL( NL, "\033[1;32m", CLIDictNames[dict], "\033[0m" );
372
373                 // Parse each cmd/description until a null command entry is found
374                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
375                 {
376                         dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
377
378                         // Determine number of spaces to tab by the length of the command and TabAlign
379                         uint8_t padLength = CLIEntryTabAlign - lenStr( CLIDict[dict][cmd].name );
380                         while ( padLength-- > 0 )
381                                 print(" ");
382
383                         dPrintStrNL( CLIDict[dict][cmd].description );
384                 }
385         }
386 }
387
388 void cliFunc_led( char* args )
389 {
390         CLILEDState ^= 1 << 1; // Toggle between 0 and 1
391         errorLED( CLILEDState ); // Enable/Disable error LED
392 }
393
394 void cliFunc_reload( char* args )
395 {
396         // Request to output module to be set into firmware reload mode
397         output_firmwareReload();
398 }
399
400 void cliFunc_reset( char* args )
401 {
402         print("\033c"); // Resets the terminal
403 }
404
405 void cliFunc_restart( char* args )
406 {
407         // Trigger an overall software reset
408         SOFTWARE_RESET();
409 }
410
411 void cliFunc_version( char* args )
412 {
413         print( NL );
414         print( " \033[1mRevision:\033[0m      " CLI_Revision       NL );
415         print( " \033[1mBranch:\033[0m        " CLI_Branch         NL );
416         print( " \033[1mTree Status:\033[0m   " CLI_ModifiedStatus NL );
417         print( " \033[1mRepo Origin:\033[0m   " CLI_RepoOrigin     NL );
418         print( " \033[1mCommit Date:\033[0m   " CLI_CommitDate     NL );
419         print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor   NL );
420         print( " \033[1mBuild Date:\033[0m    " CLI_BuildDate      NL );
421         print( " \033[1mBuild OS:\033[0m      " CLI_BuildOS        NL );
422         print( " \033[1mArchitecture:\033[0m  " CLI_Arch           NL );
423         print( " \033[1mChip:\033[0m          " CLI_Chip           NL );
424         print( " \033[1mCPU:\033[0m           " CLI_CPU            NL );
425         print( " \033[1mDevice:\033[0m        " CLI_Device         NL );
426         print( " \033[1mModules:\033[0m       " CLI_Modules        NL );
427 }
428