]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Debug/cli/cli.c
a5aa94c84daa80b59753800b76f946bc4c078f61
[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         // History starts empty
76         CLIHistoryHead = 0;
77         CLIHistoryCurrent = 0;
78         CLIHistoryTail = 0;
79
80         // Set prompt
81         prompt();
82
83         // Register first dictionary
84         CLIDictionariesUsed = 0;
85         CLI_registerDictionary( basicCLIDict, basicCLIDictName );
86
87         // Initialize main LED
88         init_errorLED();
89         CLILEDState = 0;
90
91         // Hex debug mode is off by default
92         CLIHexDebugMode = 0;
93 }
94
95 // Query the serial input buffer for any new characters
96 void CLI_process()
97 {
98         // Current buffer position
99         uint8_t prev_buf_pos = CLILineBufferCurrent;
100
101         // Process each character while available
102         while ( 1 )
103         {
104                 // No more characters to process
105                 if ( Output_availablechar() == 0 )
106                         break;
107
108                 // Retrieve from output module
109                 char cur_char = (char)Output_getchar();
110
111                 // Make sure buffer isn't full
112                 if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
113                 {
114                         print( NL );
115                         erro_print("Serial line buffer is full, dropping character and resetting...");
116
117                         // Clear buffer
118                         CLILineBufferCurrent = 0;
119
120                         // Reset the prompt
121                         prompt();
122
123                         return;
124                 }
125
126                 // Place into line buffer
127                 CLILineBuffer[CLILineBufferCurrent++] = cur_char;
128         }
129
130         // Display Hex Key Input if enabled
131         if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
132         {
133                 print("\033[s\r\n"); // Save cursor position, and move to the next line
134                 print("\033[2K");    // Erases the current line
135
136                 uint8_t pos = prev_buf_pos;
137                 while ( CLILineBufferCurrent > pos )
138                 {
139                         printHex( CLILineBuffer[pos++] );
140                         print(" ");
141                 }
142
143                 print("\033[u"); // Restore cursor position
144         }
145
146         // If buffer has changed, output to screen while there are still characters in the buffer not displayed
147         while ( CLILineBufferCurrent > prev_buf_pos )
148         {
149                 // Check for control characters
150                 switch ( CLILineBuffer[prev_buf_pos] )
151                 {
152                 // Enter
153                 case 0x0A: // LF
154                 case 0x0D: // CR
155                         CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
156
157                         // Remove the space if there is no command
158                         if ( CLILineBufferCurrent == 1 )
159                         {
160                                 CLILineBufferCurrent--;
161                         }
162                         else
163                         {
164                         // Only do command-related stuff if there was actually a command
165                         // Avoids clogging command history with blanks
166
167                                 // Process the current line buffer
168                                 CLI_commandLookup();
169
170                                 // Add the command to the history
171                                 CLI_saveHistory( CLILineBuffer );
172
173                                 // Keep the array circular, discarding the older entries
174                                 if ( CLIHistoryTail < CLIHistoryHead )
175                                         CLIHistoryHead = ( CLIHistoryHead + 1 ) % CLIMaxHistorySize;
176                                 CLIHistoryTail++;
177                                 if ( CLIHistoryTail == CLIMaxHistorySize )
178                                 {
179                                         CLIHistoryTail = 0;
180                                         CLIHistoryHead = 1;
181                                 }
182
183                                 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
184                                 CLI_saveHistory( NULL ); // delete the old temp buffer
185
186                         }
187
188                         // Reset the buffer
189                         CLILineBufferCurrent = 0;
190
191                         // Reset the prompt after processing has finished
192                         print( NL );
193                         prompt();
194
195                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
196                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
197                         return;
198
199                 case 0x09: // Tab
200                         // Tab completion for the current command
201                         CLI_tabCompletion();
202
203                         CLILineBufferCurrent--; // Remove the Tab
204
205                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
206                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
207                         return;
208
209                 case 0x1B: // Esc / Escape codes
210                         // Check for other escape sequence
211
212                         // \e[ is an escape code in vt100 compatible terminals
213                         if ( CLILineBufferCurrent >= prev_buf_pos + 3
214                                 && CLILineBuffer[ prev_buf_pos ] == 0x1B
215                                 && CLILineBuffer[ prev_buf_pos + 1] == 0x5B )
216                         {
217                                 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
218
219                                 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x41 ) // Hist prev
220                                 {
221                                         if ( CLIHistoryCurrent == CLIHistoryTail )
222                                         {
223                                                 // Is first time pressing arrow. Save the current buffer
224                                                 CLILineBuffer[ prev_buf_pos ] = '\0';
225                                                 CLI_saveHistory( CLILineBuffer );
226                                         }
227
228                                         // Grab the previus item from the history if there is one
229                                         if ( RING_PREV( CLIHistoryCurrent ) != RING_PREV( CLIHistoryHead ) )
230                                                 CLIHistoryCurrent = RING_PREV( CLIHistoryCurrent );
231                                         CLI_retreiveHistory( CLIHistoryCurrent );
232                                 }
233                                 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x42 ) // Hist next
234                                 {
235                                         // Grab the next item from the history if it exists
236                                         if ( RING_NEXT( CLIHistoryCurrent ) != RING_NEXT( CLIHistoryTail ) )
237                                                 CLIHistoryCurrent = RING_NEXT( CLIHistoryCurrent );
238                                         CLI_retreiveHistory( CLIHistoryCurrent );
239                                 }
240                         }
241                         return;
242
243                 case 0x08:
244                 case 0x7F: // Backspace
245                         // TODO - Does not handle case for arrow editing (arrows disabled atm)
246                         CLILineBufferCurrent--; // Remove the backspace
247
248                         // If there are characters in the buffer
249                         if ( CLILineBufferCurrent > 0 )
250                         {
251                                 // Remove character from current position in the line buffer
252                                 CLILineBufferCurrent--;
253
254                                 // Remove character from tty
255                                 print("\b \b");
256                         }
257
258                         break;
259
260                 default:
261                         // Place a null on the end (to use with string print)
262                         CLILineBuffer[CLILineBufferCurrent] = '\0';
263
264                         // Output buffer to screen
265                         dPrint( &CLILineBuffer[prev_buf_pos] );
266
267                         // Buffer reset
268                         prev_buf_pos++;
269
270                         break;
271                 }
272         }
273 }
274
275 // Takes a string, returns two pointers
276 //  One to the first non-space character
277 //  The second to the next argument (first NULL if there isn't an argument). delimited by a space
278 //  Places a NULL at the first space after the first argument
279 void CLI_argumentIsolation( char* string, char** first, char** second )
280 {
281         // Mark out the first argument
282         // This is done by finding the first space after a list of non-spaces and setting it NULL
283         char* cmdPtr = string - 1;
284         while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
285
286         // Locates first space delimiter
287         char* argPtr = cmdPtr + 1;
288         while ( *argPtr != ' ' && *argPtr != '\0' )
289                 argPtr++;
290
291         // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
292         (++argPtr)[-1] = '\0';
293
294         // Set return variables
295         *first = cmdPtr;
296         *second = argPtr;
297 }
298
299 // Scans the CLILineBuffer for any valid commands
300 void CLI_commandLookup()
301 {
302         // Ignore command if buffer is 0 length
303         if ( CLILineBufferCurrent == 0 )
304                 return;
305
306         // Set the last+1 character of the buffer to NULL for string processing
307         CLILineBuffer[CLILineBufferCurrent] = '\0';
308
309         // Retrieve pointers to command and beginning of arguments
310         // Places a NULL at the first space after the command
311         char* cmdPtr;
312         char* argPtr;
313         CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
314
315         // Scan array of dictionaries for a valid command match
316         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
317         {
318                 // Parse each cmd until a null command entry is found, or an argument match
319                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
320                 {
321                         // Compare the first argument and each command entry
322                         if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
323                         {
324                                 // Run the specified command function pointer
325                                 //   argPtr is already pointing at the first character of the arguments
326                                 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
327
328                                 return;
329                         }
330                 }
331         }
332
333         // No match for the command...
334         print( NL );
335         erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
336 }
337
338 // Registers a command dictionary with the CLI
339 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
340 {
341         // Make sure this max limit of dictionaries hasn't been reached
342         if ( CLIDictionariesUsed >= CLIMaxDictionaries )
343         {
344                 erro_print("Max number of dictionaries defined already...");
345                 return;
346         }
347
348         // Add dictionary
349         CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
350         CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
351 }
352
353 inline void CLI_tabCompletion()
354 {
355         // Ignore command if buffer is 0 length
356         if ( CLILineBufferCurrent == 0 )
357                 return;
358
359         // Set the last+1 character of the buffer to NULL for string processing
360         CLILineBuffer[CLILineBufferCurrent] = '\0';
361
362         // Retrieve pointers to command and beginning of arguments
363         // Places a NULL at the first space after the command
364         char* cmdPtr;
365         char* argPtr;
366         CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
367
368         // Tab match pointer
369         char* tabMatch = 0;
370         uint8_t matches = 0;
371
372         // Scan array of dictionaries for a valid command match
373         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
374         {
375                 // Parse each cmd until a null command entry is found, or an argument match
376                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
377                 {
378                         // Compare the first argument piece to each command entry to see if it is "like"
379                         // NOTE: To save on processing, we only care about the commands and ignore the arguments
380                         //       If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
381                         //       Also ignores full matches
382                         if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
383                         {
384                                 // TODO Make list of commands if multiple matches
385                                 matches++;
386                                 tabMatch = (char*)CLIDict[dict][cmd].name;
387                         }
388                 }
389         }
390
391         // Only tab complete if there was 1 match
392         if ( matches == 1 )
393         {
394                 // Reset the buffer
395                 CLILineBufferCurrent = 0;
396
397                 // Reprint the prompt (automatically clears the line)
398                 prompt();
399
400                 // Display the command
401                 dPrint( tabMatch );
402
403                 // There are no index counts, so just copy the whole string to the input buffer
404                 while ( *tabMatch != '\0' )
405                 {
406                         CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
407                 }
408         }
409 }
410
411 inline int CLI_wrap( int kX, int const kLowerBound, int const kUpperBound )
412 {
413         int range_size = kUpperBound - kLowerBound + 1;
414
415         if ( kX < kLowerBound )
416                 kX += range_size * ((kLowerBound - kX) / range_size + 1);
417
418         return kLowerBound + (kX - kLowerBound) % range_size;
419 }
420
421 inline void CLI_saveHistory( char *buff )
422 {
423         if ( buff == NULL )
424         {
425                 //clear the item
426                 CLIHistoryBuffer[ CLIHistoryTail ][ 0 ] = '\0';
427                 return;
428         }
429
430         // Copy the line to the history
431         int i;
432         for (i = 0; i < CLILineBufferCurrent; i++)
433         {
434                 CLIHistoryBuffer[ CLIHistoryTail ][ i ] = CLILineBuffer[ i ];
435         }
436 }
437
438 void CLI_retreiveHistory( int index )
439 {
440         char *histMatch = CLIHistoryBuffer[ index ];
441
442         // Reset the buffer
443         CLILineBufferCurrent = 0;
444
445         // Reprint the prompt (automatically clears the line)
446         prompt();
447
448         // Display the command
449         dPrint( histMatch );
450
451         // There are no index counts, so just copy the whole string to the input buffe
452         CLILineBufferCurrent = 0;
453         while ( *histMatch != '\0' )
454         {
455                 CLILineBuffer[ CLILineBufferCurrent++ ] = *histMatch++;
456         }
457 }
458
459
460
461 // ----- CLI Command Functions -----
462
463 void cliFunc_clear( char* args)
464 {
465         print("\033[2J\033[H\r"); // Erases the whole screen
466 }
467
468 void cliFunc_cliDebug( char* args )
469 {
470         // Toggle Hex Debug Mode
471         if ( CLIHexDebugMode )
472         {
473                 print( NL );
474                 info_print("Hex debug mode disabled...");
475                 CLIHexDebugMode = 0;
476         }
477         else
478         {
479                 print( NL );
480                 info_print("Hex debug mode enabled...");
481                 CLIHexDebugMode = 1;
482         }
483 }
484
485 void cliFunc_help( char* args )
486 {
487         // Scan array of dictionaries and print every description
488         //  (no alphabetical here, too much processing/memory to sort...)
489         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
490         {
491                 // Print the name of each dictionary as a title
492                 print( NL "\033[1;32m" );
493                 _print( CLIDictNames[dict] ); // This print is requride by AVR (flash)
494                 print( "\033[0m" NL );
495
496                 // Parse each cmd/description until a null command entry is found
497                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
498                 {
499                         dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
500
501                         // Determine number of spaces to tab by the length of the command and TabAlign
502                         uint8_t padLength = CLIEntryTabAlign - lenStr( (char*)CLIDict[dict][cmd].name );
503                         while ( padLength-- > 0 )
504                                 print(" ");
505
506                         _print( CLIDict[dict][cmd].description ); // This print is required by AVR (flash)
507                         print( NL );
508                 }
509         }
510 }
511
512 void cliFunc_led( char* args )
513 {
514         CLILEDState ^= 1 << 1; // Toggle between 0 and 1
515         errorLED( CLILEDState ); // Enable/Disable error LED
516 }
517
518 void cliFunc_reload( char* args )
519 {
520         // Request to output module to be set into firmware reload mode
521         Output_firmwareReload();
522 }
523
524 void cliFunc_reset( char* args )
525 {
526         print("\033c"); // Resets the terminal
527 }
528
529 void cliFunc_restart( char* args )
530 {
531         // Trigger an overall software reset
532         Output_softReset();
533 }
534
535 void cliFunc_version( char* args )
536 {
537         print( NL );
538         print( " \033[1mRevision:\033[0m      " CLI_Revision       NL );
539         print( " \033[1mBranch:\033[0m        " CLI_Branch         NL );
540         print( " \033[1mTree Status:\033[0m   " CLI_ModifiedStatus CLI_ModifiedFiles NL );
541         print( " \033[1mRepo Origin:\033[0m   " CLI_RepoOrigin     NL );
542         print( " \033[1mCommit Date:\033[0m   " CLI_CommitDate     NL );
543         print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor   NL );
544         print( " \033[1mBuild Date:\033[0m    " CLI_BuildDate      NL );
545         print( " \033[1mBuild OS:\033[0m      " CLI_BuildOS        NL );
546         print( " \033[1mArchitecture:\033[0m  " CLI_Arch           NL );
547         print( " \033[1mChip:\033[0m          " CLI_Chip           NL );
548         print( " \033[1mCPU:\033[0m           " CLI_CPU            NL );
549         print( " \033[1mDevice:\033[0m        " CLI_Device         NL );
550         print( " \033[1mModules:\033[0m       " CLI_Modules        NL );
551 }
552