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