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