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