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