Kiibohd Controller
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
Repozitorijs ir arhivēts. Tam var aplūkot failus un to var klonēt, bet nevar iesūtīt jaunas izmaiņas, kā arī atvērt jaunas problēmas/izmaiņu pieprasījumus.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /* Copyright (C) 2014 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. // Compiler Includes
  23. //#include <stdarg.h>
  24. // Project Includes
  25. #include <buildvars.h>
  26. #include "cli.h"
  27. #include <led.h>
  28. #include <print.h>
  29. // ----- Variables -----
  30. // Basic command dictionary
  31. char* basicCLIDictName = "General Commands";
  32. CLIDictItem basicCLIDict[] = {
  33. { "cliDebug", "Enables/Disables hex output of the most recent cli input.", cliFunc_cliDebug },
  34. { "help", "You're looking at it :P", cliFunc_help },
  35. { "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...", cliFunc_led },
  36. { "reload", "Signals microcontroller to reflash/reload.", cliFunc_reload },
  37. { "reset", "Resets the terminal back to initial settings.", cliFunc_reset },
  38. { "restart", "Sends a software restart, should be similar to powering on the device.", cliFunc_restart },
  39. { "version", "Version information about this firmware.", cliFunc_version },
  40. { 0, 0, 0 } // Null entry for dictionary end
  41. };
  42. // ----- Functions -----
  43. inline void prompt()
  44. {
  45. print("\033[2K\r"); // Erases the current line and resets cursor to beginning of line
  46. print("\033[1;34m:\033[0m "); // Blue bold prompt
  47. }
  48. // Initialize the CLI
  49. inline void init_cli()
  50. {
  51. // Reset the Line Buffer
  52. CLILineBufferCurrent = 0;
  53. // Set prompt
  54. prompt();
  55. // Register first dictionary
  56. CLIDictionariesUsed = 0;
  57. registerDictionary_cli( basicCLIDict, basicCLIDictName );
  58. // Initialize main LED
  59. init_errorLED();
  60. CLILEDState = 0;
  61. // Hex debug mode is off by default
  62. CLIHexDebugMode = 0;
  63. }
  64. // Query the serial input buffer for any new characters
  65. void process_cli()
  66. {
  67. // Current buffer position
  68. uint8_t prev_buf_pos = CLILineBufferCurrent;
  69. // Process each character while available
  70. int result = 0;
  71. while ( 1 )
  72. {
  73. // No more characters to process
  74. result = usb_serial_getchar(); // Retrieve from serial module // TODO Make USB agnostic
  75. if ( result == -1 )
  76. break;
  77. char cur_char = (char)result;
  78. // Make sure buffer isn't full
  79. if ( CLILineBufferCurrent >= CLILineBufferMaxSize )
  80. {
  81. print( NL );
  82. erro_print("Serial line buffer is full, dropping character and resetting...");
  83. // Clear buffer
  84. CLILineBufferCurrent = 0;
  85. // Reset the prompt
  86. prompt();
  87. return;
  88. }
  89. // Place into line buffer
  90. CLILineBuffer[CLILineBufferCurrent++] = cur_char;
  91. }
  92. // Display Hex Key Input if enabled
  93. if ( CLIHexDebugMode && CLILineBufferCurrent > prev_buf_pos )
  94. {
  95. print("\033[s\r\n"); // Save cursor position, and move to the next line
  96. print("\033[2K"); // Erases the current line
  97. uint8_t pos = prev_buf_pos;
  98. while ( CLILineBufferCurrent > pos )
  99. {
  100. printHex( CLILineBuffer[pos++] );
  101. print(" ");
  102. }
  103. print("\033[u"); // Restore cursor position
  104. }
  105. // If buffer has changed, output to screen while there are still characters in the buffer not displayed
  106. while ( CLILineBufferCurrent > prev_buf_pos )
  107. {
  108. // Check for control characters
  109. switch ( CLILineBuffer[prev_buf_pos] )
  110. {
  111. case 0x0D: // Enter
  112. CLILineBuffer[CLILineBufferCurrent - 1] = ' '; // Replace Enter with a space (resolves a bug in args)
  113. // Remove the space if there is no command
  114. if ( CLILineBufferCurrent == 1 )
  115. CLILineBufferCurrent--;
  116. // Process the current line buffer
  117. commandLookup_cli();
  118. // Reset the buffer
  119. CLILineBufferCurrent = 0;
  120. // Reset the prompt after processing has finished
  121. print( NL );
  122. prompt();
  123. // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
  124. // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
  125. return;
  126. case 0x09: // Tab
  127. // Tab completion for the current command
  128. tabCompletion_cli();
  129. CLILineBufferCurrent--; // Remove the Tab
  130. // XXX There is a potential bug here when resetting the buffer (losing valid keypresses)
  131. // Doesn't look like it will happen *that* often, so not handling it for now -HaaTa
  132. return;
  133. case 0x1B: // Esc
  134. // Check for escape sequence
  135. // TODO
  136. return;
  137. case 0x08:
  138. case 0x7F: // Backspace
  139. // TODO - Does not handle case for arrow editing (arrows disabled atm)
  140. CLILineBufferCurrent--; // Remove the backspace
  141. // If there are characters in the buffer
  142. if ( CLILineBufferCurrent > 0 )
  143. {
  144. // Remove character from current position in the line buffer
  145. CLILineBufferCurrent--;
  146. // Remove character from tty
  147. print("\b \b");
  148. }
  149. break;
  150. default:
  151. // Place a null on the end (to use with string print)
  152. CLILineBuffer[CLILineBufferCurrent] = '\0';
  153. // Output buffer to screen
  154. dPrint( &CLILineBuffer[prev_buf_pos] );
  155. // Buffer reset
  156. prev_buf_pos++;
  157. break;
  158. }
  159. }
  160. }
  161. // Takes a string, returns two pointers
  162. // One to the first non-space character
  163. // The second to the next argument (first NULL if there isn't an argument). delimited by a space
  164. // Places a NULL at the first space after the first argument
  165. inline void argumentIsolation_cli( char* string, char** first, char** second )
  166. {
  167. // Mark out the first argument
  168. // This is done by finding the first space after a list of non-spaces and setting it NULL
  169. char* cmdPtr = string - 1;
  170. while ( *++cmdPtr == ' ' ); // Skips leading spaces, and points to first character of cmd
  171. // Locates first space delimiter
  172. char* argPtr = cmdPtr + 1;
  173. while ( *argPtr != ' ' && *argPtr != '\0' )
  174. argPtr++;
  175. // Point to the first character of args or a NULL (no args) and set the space delimiter as a NULL
  176. (++argPtr)[-1] = '\0';
  177. // Set return variables
  178. *first = cmdPtr;
  179. *second = argPtr;
  180. }
  181. // Scans the CLILineBuffer for any valid commands
  182. void commandLookup_cli()
  183. {
  184. // Ignore command if buffer is 0 length
  185. if ( CLILineBufferCurrent == 0 )
  186. return;
  187. // Set the last+1 character of the buffer to NULL for string processing
  188. CLILineBuffer[CLILineBufferCurrent] = '\0';
  189. // Retrieve pointers to command and beginning of arguments
  190. // Places a NULL at the first space after the command
  191. char* cmdPtr;
  192. char* argPtr;
  193. argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
  194. // Scan array of dictionaries for a valid command match
  195. for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
  196. {
  197. // Parse each cmd until a null command entry is found, or an argument match
  198. for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
  199. {
  200. // Compare the first argument and each command entry
  201. if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == -1 )
  202. {
  203. // Run the specified command function pointer
  204. // argPtr is already pointing at the first character of the arguments
  205. (*CLIDict[dict][cmd].function)( argPtr );
  206. return;
  207. }
  208. }
  209. }
  210. // No match for the command...
  211. print( NL );
  212. erro_dPrint("\"", CLILineBuffer, "\" is not a valid command...type \033[35mhelp\033[0m");
  213. }
  214. // Registers a command dictionary with the CLI
  215. inline void registerDictionary_cli( CLIDictItem *cmdDict, char* dictName )
  216. {
  217. // Make sure this max limit of dictionaries hasn't been reached
  218. if ( CLIDictionariesUsed >= CLIMaxDictionaries )
  219. {
  220. erro_print("Max number of dictionaries defined already...");
  221. return;
  222. }
  223. // Add dictionary
  224. CLIDictNames[CLIDictionariesUsed] = dictName;
  225. CLIDict[CLIDictionariesUsed++] = cmdDict;
  226. }
  227. inline void tabCompletion_cli()
  228. {
  229. // Ignore command if buffer is 0 length
  230. if ( CLILineBufferCurrent == 0 )
  231. return;
  232. // Set the last+1 character of the buffer to NULL for string processing
  233. CLILineBuffer[CLILineBufferCurrent] = '\0';
  234. // Retrieve pointers to command and beginning of arguments
  235. // Places a NULL at the first space after the command
  236. char* cmdPtr;
  237. char* argPtr;
  238. argumentIsolation_cli( CLILineBuffer, &cmdPtr, &argPtr );
  239. // Tab match pointer
  240. char* tabMatch = 0;
  241. uint8_t matches = 0;
  242. // Scan array of dictionaries for a valid command match
  243. for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
  244. {
  245. // Parse each cmd until a null command entry is found, or an argument match
  246. for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
  247. {
  248. // Compare the first argument piece to each command entry to see if it is "like"
  249. // NOTE: To save on processing, we only care about the commands and ignore the arguments
  250. // If there are arguments, and a valid tab match is found, buffer is cleared (args lost)
  251. // Also ignores full matches
  252. if ( eqStr( cmdPtr, CLIDict[dict][cmd].name ) == 0 )
  253. {
  254. // TODO Make list of commands if multiple matches
  255. matches++;
  256. tabMatch = CLIDict[dict][cmd].name;
  257. }
  258. }
  259. }
  260. // Only tab complete if there was 1 match
  261. if ( matches == 1 )
  262. {
  263. // Reset the buffer
  264. CLILineBufferCurrent = 0;
  265. // Reprint the prompt (automatically clears the line)
  266. prompt();
  267. // Display the command
  268. dPrint( tabMatch );
  269. // There are no index counts, so just copy the whole string to the input buffer
  270. while ( *tabMatch != '\0' )
  271. {
  272. CLILineBuffer[CLILineBufferCurrent++] = *tabMatch++;
  273. }
  274. }
  275. }
  276. // ----- CLI Command Functions -----
  277. void cliFunc_cliDebug( char* args )
  278. {
  279. // Toggle Hex Debug Mode
  280. if ( CLIHexDebugMode )
  281. {
  282. print( NL );
  283. info_print("Hex debug mode disabled...");
  284. CLIHexDebugMode = 0;
  285. }
  286. else
  287. {
  288. print( NL );
  289. info_print("Hex debug mode enabled...");
  290. CLIHexDebugMode = 1;
  291. }
  292. }
  293. void cliFunc_help( char* args )
  294. {
  295. // Scan array of dictionaries and print every description
  296. // (no alphabetical here, too much processing/memory to sort...)
  297. for ( uint8_t dict = 0; dict < CLIDictionariesUsed; dict++ )
  298. {
  299. // Print the name of each dictionary as a title
  300. dPrintStrsNL( NL, "\033[1;32m", CLIDictNames[dict], "\033[0m" );
  301. // Parse each cmd/description until a null command entry is found
  302. for ( uint8_t cmd = 0; CLIDict[dict][cmd].name != 0; cmd++ )
  303. {
  304. dPrintStrs(" \033[35m", CLIDict[dict][cmd].name, "\033[0m");
  305. // Determine number of spaces to tab by the length of the command and TabAlign
  306. uint8_t padLength = CLIEntryTabAlign - lenStr( CLIDict[dict][cmd].name );
  307. while ( padLength-- > 0 )
  308. print(" ");
  309. dPrintStrNL( CLIDict[dict][cmd].description );
  310. }
  311. }
  312. }
  313. void cliFunc_led( char* args )
  314. {
  315. CLILEDState ^= 1 << 1; // Toggle between 0 and 1
  316. errorLED( CLILEDState ); // Enable/Disable error LED
  317. }
  318. void cliFunc_reload( char* args )
  319. {
  320. // Request to output module to be set into firmware reload mode
  321. output_firmwareReload();
  322. }
  323. void cliFunc_reset( char* args )
  324. {
  325. print("\033c"); // Resets the terminal
  326. }
  327. void cliFunc_restart( char* args )
  328. {
  329. // Trigger an overall software reset
  330. SOFTWARE_RESET();
  331. }
  332. void cliFunc_version( char* args )
  333. {
  334. print( NL );
  335. print( " \033[1mRevision:\033[0m " CLI_Revision NL );
  336. print( " \033[1mBranch:\033[0m " CLI_Branch NL );
  337. print( " \033[1mTree Status:\033[0m " CLI_ModifiedStatus NL );
  338. print( " \033[1mRepo Origin:\033[0m " CLI_RepoOrigin NL );
  339. print( " \033[1mCommit Date:\033[0m " CLI_CommitDate NL );
  340. print( " \033[1mCommit Author:\033[0m " CLI_CommitAuthor NL );
  341. print( " \033[1mBuild Date:\033[0m " CLI_BuildDate NL );
  342. print( " \033[1mBuild OS:\033[0m " CLI_BuildOS NL );
  343. print( " \033[1mArchitecture:\033[0m " CLI_Arch NL );
  344. print( " \033[1mChip:\033[0m " CLI_Chip NL );
  345. print( " \033[1mCPU:\033[0m " CLI_CPU NL );
  346. print( " \033[1mDevice:\033[0m " CLI_Device NL );
  347. print( " \033[1mModules:\033[0m " CLI_Modules NL );
  348. }