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