Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

cli.c 16KB

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