]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Debug/cli/cli.c
Write whole debug cli command to history
[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                                 // Add the command to the history
163                                 CLI_saveHistory( CLILineBuffer );
164
165                                 // Process the current line buffer
166                                 CLI_commandLookup();
167
168                                 // Keep the array circular, discarding the older entries
169                                 if ( CLIHistoryTail < CLIHistoryHead )
170                                         CLIHistoryHead = ( CLIHistoryHead + 1 ) % CLIMaxHistorySize;
171                                 CLIHistoryTail++;
172                                 if ( CLIHistoryTail == CLIMaxHistorySize )
173                                 {
174                                         CLIHistoryTail = 0;
175                                         CLIHistoryHead = 1;
176                                 }
177
178                                 CLIHistoryCurrent = CLIHistoryTail; // 'Up' starts at the last item
179                                 CLI_saveHistory( NULL ); // delete the old temp buffer
180
181                         }
182
183                         // Reset the buffer
184                         CLILineBufferCurrent = 0;
185
186                         // Reset the prompt after processing has finished
187                         print( NL );
188                         prompt();
189
190                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
191                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
192                         return;
193
194                 case 0x09: // Tab
195                         // Tab completion for the current command
196                         CLI_tabCompletion();
197
198                         CLILineBufferCurrent--; // Remove the Tab
199
200                         // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
201                         //     Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
202                         return;
203
204                 case 0x1B: // Esc / Escape codes
205                         // Check for other escape sequence
206
207                         // \e[ is an escape code in vt100 compatible terminals
208                         if ( CLILineBufferCurrent >= prev_buf_pos + 3
209                                 && CLILineBuffer[ prev_buf_pos ] == 0x1B
210                                 && CLILineBuffer[ prev_buf_pos + 1] == 0x5B )
211                         {
212                                 // Arrow Keys: A (0x41) = Up, B (0x42) = Down, C (0x43) = Right, D (0x44) = Left
213
214                                 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x41 ) // Hist prev
215                                 {
216                                         if ( CLIHistoryCurrent == CLIHistoryTail )
217                                         {
218                                                 // Is first time pressing arrow. Save the current buffer
219                                                 CLILineBuffer[ prev_buf_pos ] = '\0';
220                                                 CLI_saveHistory( CLILineBuffer );
221                                         }
222
223                                         // Grab the previus item from the history if there is one
224                                         if ( RING_PREV( CLIHistoryCurrent ) != RING_PREV( CLIHistoryHead ) )
225                                                 CLIHistoryCurrent = RING_PREV( CLIHistoryCurrent );
226                                         CLI_retreiveHistory( CLIHistoryCurrent );
227                                 }
228                                 if ( CLILineBuffer[ prev_buf_pos + 2 ] == 0x42 ) // Hist next
229                                 {
230                                         // Grab the next item from the history if it exists
231                                         if ( RING_NEXT( CLIHistoryCurrent ) != RING_NEXT( CLIHistoryTail ) )
232                                                 CLIHistoryCurrent = RING_NEXT( CLIHistoryCurrent );
233                                         CLI_retreiveHistory( CLIHistoryCurrent );
234                                 }
235                         }
236                         return;
237
238                 case 0x08:
239                 case 0x7F: // Backspace
240                         // TODO - Does not handle case for arrow editing (arrows disabled atm)
241                         CLILineBufferCurrent--; // Remove the backspace
242
243                         // If there are characters in the buffer
244                         if ( CLILineBufferCurrent > 0 )
245                         {
246                                 // Remove character from current position in the line buffer
247                                 CLILineBufferCurrent--;
248
249                                 // Remove character from tty
250                                 print("\b \b");
251                         }
252
253                         break;
254
255                 default:
256                         // Place a null on the end (to use with string print)
257                         CLILineBuffer[CLILineBufferCurrent] = '\0';
258
259                         // Output buffer to screen
260                         dPrint( &CLILineBuffer[prev_buf_pos] );
261
262                         // Buffer reset
263                         prev_buf_pos++;
264
265                         break;
266                 }
267         }
268 }
269
270 // Takes a string, returns two pointers
271 //  One to the first non-space character
272 //  The second to the next argument (first NULL if there isn't an argument). delimited by a space
273 //  Places a NULL at the first space after the first argument
274 void CLI_argumentIsolation( char* string, char** first, char** second )
275 {
276         // Mark out the first argument
277         // This is done by finding the first space after a list of non-spaces and setting it NULL
278         char* cmdPtr = string - 1;
279         while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
280
281         // Locates first space delimiter
282         char* argPtr = cmdPtr + 1;
283         while ( *argPtr != ' ' && *argPtr != '\0' )
284                 argPtr++;
285
286         // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
287         (++argPtr)[-1] = '\0';
288
289         // Set return variables
290         *first = cmdPtr;
291         *second = argPtr;
292 }
293
294 // Scans the CLILineBuffer for any valid commands
295 void CLI_commandLookup()
296 {
297         // Ignore command if buffer is 0 length
298         if ( CLILineBufferCurrent == 0 )
299                 return;
300
301         // Set the last+1 character of the buffer to NULL for string processing
302         CLILineBuffer[CLILineBufferCurrent] = '\0';
303
304         // Retrieve pointers to command and beginning of arguments
305         // Places a NULL at the first space after the command
306         char* cmdPtr;
307         char* argPtr;
308         CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
309
310         // Scan array of dictionaries for a valid command match
311         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
312         {
313                 // Parse each cmd until a null command entry is found, or an argument match
314                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
315                 {
316                         // Compare the first argument and each command entry
317                         if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == -1 )
318                         {
319                                 // Run the specified command function pointer
320                                 //   argPtr is already pointing at the first character of the arguments
321                                 (*(void (*)(char*))CLIDict[dict][cmd].function)( argPtr );
322
323                                 return;
324                         }
325                 }
326         }
327
328         // No match for the command...
329         print( NL );
330         erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
331 }
332
333 // Registers a command dictionary with the CLI
334 void CLI_registerDictionary( const CLIDictItem *cmdDict, const char* dictName )
335 {
336         // Make sure this max limit of dictionaries hasn't been reached
337         if ( CLIDictionariesUsed >= CLIMaxDictionaries )
338         {
339                 erro_print("Max number of dictionaries defined already...");
340                 return;
341         }
342
343         // Add dictionary
344         CLIDictNames[CLIDictionariesUsed] = (char*)dictName;
345         CLIDict[CLIDictionariesUsed++] = (CLIDictItem*)cmdDict;
346 }
347
348 inline void CLI_tabCompletion()
349 {
350         // Ignore command if buffer is 0 length
351         if ( CLILineBufferCurrent == 0 )
352                 return;
353
354         // Set the last+1 character of the buffer to NULL for string processing
355         CLILineBuffer[CLILineBufferCurrent] = '\0';
356
357         // Retrieve pointers to command and beginning of arguments
358         // Places a NULL at the first space after the command
359         char* cmdPtr;
360         char* argPtr;
361         CLI_argumentIsolation( CLILineBuffer, &cmdPtr, &argPtr );
362
363         // Tab match pointer
364         char* tabMatch = 0;
365         uint8_t matches = 0;
366
367         // Scan array of dictionaries for a valid command match
368         for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
369         {
370                 // Parse each cmd until a null command entry is found, or an argument match
371                 for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
372                 {
373                         // Compare the first argument piece to each command entry to see if it is "like"
374                         // NOTE: To save on processing, we only care about the commands and ignore the arguments
375                         //       If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
376                         //       Also ignores full matches
377                         if ( eqStr( cmdPtr, (char*)CLIDict[dict][cmd].name ) == 0 )
378                         {
379                                 // TODO Make list of commands if multiple matches
380                                 matches++;
381                                 tabMatch = (char*)CLIDict[dict][cmd].name;
382                         }
383                 }
384         }
385
386         // Only tab complete if there was 1 match
387         if ( matches == 1 )
388         {
389                 // Reset the buffer
390                 CLILineBufferCurrent = 0;
391
392                 // Reprint the prompt (automatically clears the line)
393                 prompt();
394
395                 // Display the command
396                 dPrint( tabMatch );
397
398                 // There are no index counts, so just copy the whole string to the input buffer
399                 while ( *tabMatch != '\0' )
400                 {
401                         CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
402                 }
403         }
404 }
405
406 inline int CLI_wrap( int kX, int const kLowerBound, int const kUpperBound )
407 {
408         int range_size = kUpperBound - kLowerBound + 1;
409
410         if ( kX < kLowerBound )
411                 kX += range_size * ((kLowerBound - kX) / range_size + 1);
412
413         return kLowerBound + (kX - kLowerBound) % range_size;
414 }
415
416 inline void CLI_saveHistory( char *buff )
417 {
418         if ( buff == NULL )
419         {
420                 //clear the item
421                 CLIHistoryBuffer[ CLIHistoryTail ][ 0 ] = '\0';
422                 return;
423         }
424
425         // Don't write empty lines to the history
426         const char *cursor = buff;
427         while (*cursor == ' ') { cursor++; } // advance past the leading whitespace
428         if (*cursor == '\0') { return ; }
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         if ( flashModeEnabled_define == 0 )
521         {
522                 print( NL );
523                 warn_print("flashModeEnabled not set, cancelling firmware reload...");
524                 info_msg("Set flashModeEnabled to 1 in your kll configuration.");
525                 return;
526         }
527
528         // Request to output module to be set into firmware reload mode
529         Output_firmwareReload();
530 }
531
532 void cliFunc_reset( char* args )
533 {
534         print("\033c"); // Resets the terminal
535 }
536
537 void cliFunc_restart( char* args )
538 {
539         // Trigger an overall software reset
540         Output_softReset();
541 }
542
543 void cliFunc_version( char* args )
544 {
545         print( NL );
546         print( " \033[1mRevision:\033[0m      " CLI_Revision       NL );
547         print( " \033[1mBranch:\033[0m        " CLI_Branch         NL );
548         print( " \033[1mTree Status:\033[0m   " CLI_ModifiedStatus CLI_ModifiedFiles NL );
549         print( " \033[1mRepo Origin:\033[0m   " CLI_RepoOrigin     NL );
550         print( " \033[1mCommit Date:\033[0m   " CLI_CommitDate     NL );
551         print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor   NL );
552         print( " \033[1mBuild Date:\033[0m    " CLI_BuildDate      NL );
553         print( " \033[1mBuild OS:\033[0m      " CLI_BuildOS        NL );
554         print( " \033[1mArchitecture:\033[0m  " CLI_Arch           NL );
555         print( " \033[1mChip:\033[0m          " CLI_Chip           NL );
556         print( " \033[1mCPU:\033[0m           " CLI_CPU            NL );
557         print( " \033[1mDevice:\033[0m        " CLI_Device         NL );
558         print( " \033[1mModules:\033[0m       " CLI_Modules        NL );
559 #if defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
560         print( " \033[1mUnique Id:\033[0m     " );
561         printHex32_op( SIM_UIDH, 4 );
562         printHex32_op( SIM_UIDMH, 4 );
563         printHex32_op( SIM_UIDML, 4 );
564         printHex32_op( SIM_UIDL, 4 );
565 #elif defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_)
566 #else
567 #error "No unique id defined."
568 #endif
569 }
570