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.

output_com.c 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /* Copyright (C) 2011-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 <Lib/OutputLib.h>
  24. // Project Includes
  25. #include <cli.h>
  26. #include <led.h>
  27. #include <print.h>
  28. #include <scan_loop.h>
  29. // USB Includes
  30. #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_)
  31. #include "avr/usb_keyboard_serial.h"
  32. #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_)
  33. #include "arm/usb_dev.h"
  34. #include "arm/usb_keyboard.h"
  35. #include "arm/usb_serial.h"
  36. #endif
  37. // Local Includes
  38. #include "output_com.h"
  39. // ----- Macros -----
  40. // Used to build a bitmap lookup table from a byte addressable array
  41. #define byteLookup( byte ) case (( byte ) * ( 8 )): bytePosition = byte; byteShift = 0; break; \
  42. case (( byte ) * ( 8 ) + ( 1 )): bytePosition = byte; byteShift = 1; break; \
  43. case (( byte ) * ( 8 ) + ( 2 )): bytePosition = byte; byteShift = 2; break; \
  44. case (( byte ) * ( 8 ) + ( 3 )): bytePosition = byte; byteShift = 3; break; \
  45. case (( byte ) * ( 8 ) + ( 4 )): bytePosition = byte; byteShift = 4; break; \
  46. case (( byte ) * ( 8 ) + ( 5 )): bytePosition = byte; byteShift = 5; break; \
  47. case (( byte ) * ( 8 ) + ( 6 )): bytePosition = byte; byteShift = 6; break; \
  48. case (( byte ) * ( 8 ) + ( 7 )): bytePosition = byte; byteShift = 7; break
  49. // ----- Function Declarations -----
  50. void cliFunc_kbdProtocol( char* args );
  51. void cliFunc_readLEDs ( char* args );
  52. void cliFunc_sendKeys ( char* args );
  53. void cliFunc_setKeys ( char* args );
  54. void cliFunc_setMod ( char* args );
  55. // ----- Variables -----
  56. // Output Module command dictionary
  57. CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
  58. CLIDict_Entry( readLEDs, "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
  59. CLIDict_Entry( sendKeys, "Send the prepared list of USB codes and modifier byte." );
  60. CLIDict_Entry( setKeys, "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
  61. CLIDict_Entry( setMod, "Set the modfier byte:" NL "\t\t1 LCtrl, 2 LShft, 4 LAlt, 8 LGUI, 16 RCtrl, 32 RShft, 64 RAlt, 128 RGUI" );
  62. CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
  63. CLIDict_Item( kbdProtocol ),
  64. CLIDict_Item( readLEDs ),
  65. CLIDict_Item( sendKeys ),
  66. CLIDict_Item( setKeys ),
  67. CLIDict_Item( setMod ),
  68. { 0, 0, 0 } // Null entry for dictionary end
  69. };
  70. // Which modifier keys are currently pressed
  71. // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
  72. // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
  73. uint8_t USBKeys_Modifiers = 0;
  74. uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
  75. // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
  76. uint8_t USBKeys_Keys [USB_NKRO_BITFIELD_SIZE_KEYS];
  77. uint8_t USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
  78. // System Control and Consumer Control 1KRO containers
  79. uint8_t USBKeys_SysCtrl;
  80. uint16_t USBKeys_ConsCtrl;
  81. // The number of keys sent to the usb in the array
  82. uint8_t USBKeys_Sent = 0;
  83. uint8_t USBKeys_SentCLI = 0;
  84. // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
  85. volatile uint8_t USBKeys_LEDs = 0;
  86. // Protocol setting from the host.
  87. // 0 - Boot Mode
  88. // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
  89. volatile uint8_t USBKeys_Protocol = 1;
  90. // Indicate if USB should send update
  91. // OS only needs update if there has been a change in state
  92. USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
  93. // the idle configuration, how often we send the report to the
  94. // host (ms * 4) even when it hasn't changed
  95. uint8_t USBKeys_Idle_Config = 125;
  96. // count until idle timeout
  97. uint8_t USBKeys_Idle_Count = 0;
  98. // ----- Capabilities -----
  99. // Set Boot Keyboard Protocol
  100. void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  101. {
  102. // Display capability name
  103. if ( stateType == 0xFF && state == 0xFF )
  104. {
  105. print("Output_kbdProtocolBoot()");
  106. return;
  107. }
  108. // Only set if necessary
  109. if ( USBKeys_Protocol == 0 )
  110. return;
  111. // TODO Analog inputs
  112. // Only set on key press
  113. if ( stateType != 0x01 )
  114. return;
  115. // Flush the key buffers
  116. Output_flushBuffers();
  117. // Set the keyboard protocol to Boot Mode
  118. USBKeys_Protocol = 0;
  119. }
  120. // Set NKRO Keyboard Protocol
  121. void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  122. {
  123. // Display capability name
  124. if ( stateType == 0xFF && state == 0xFF )
  125. {
  126. print("Output_kbdProtocolNKRO()");
  127. return;
  128. }
  129. // Only set if necessary
  130. if ( USBKeys_Protocol == 1 )
  131. return;
  132. // TODO Analog inputs
  133. // Only set on key press
  134. if ( stateType != 0x01 )
  135. return;
  136. // Flush the key buffers
  137. Output_flushBuffers();
  138. // Set the keyboard protocol to NKRO Mode
  139. USBKeys_Protocol = 1;
  140. }
  141. // Sends a Consumer Control code to the USB Output buffer
  142. void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  143. {
  144. // Display capability name
  145. if ( stateType == 0xFF && state == 0xFF )
  146. {
  147. print("Output_consCtrlSend(consCode)");
  148. return;
  149. }
  150. // Not implemented in Boot Mode
  151. if ( USBKeys_Protocol == 0 )
  152. {
  153. warn_print("Consumer Control is not implemented for Boot Mode");
  154. return;
  155. }
  156. // TODO Analog inputs
  157. // Only indicate USB has changed if either a press or release has occured
  158. if ( state == 0x01 || state == 0x03 )
  159. USBKeys_Changed |= USBKeyChangeState_Consumer;
  160. // Only send keypresses if press or hold state
  161. if ( stateType == 0x00 && state == 0x03 ) // Release state
  162. return;
  163. // Set consumer control code
  164. USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
  165. }
  166. // Sends a System Control code to the USB Output buffer
  167. void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  168. {
  169. // Display capability name
  170. if ( stateType == 0xFF && state == 0xFF )
  171. {
  172. print("Output_sysCtrlSend(sysCode)");
  173. return;
  174. }
  175. // Not implemented in Boot Mode
  176. if ( USBKeys_Protocol == 0 )
  177. {
  178. warn_print("System Control is not implemented for Boot Mode");
  179. return;
  180. }
  181. // TODO Analog inputs
  182. // Only indicate USB has changed if either a press or release has occured
  183. if ( state == 0x01 || state == 0x03 )
  184. USBKeys_Changed |= USBKeyChangeState_System;
  185. // Only send keypresses if press or hold state
  186. if ( stateType == 0x00 && state == 0x03 ) // Release state
  187. return;
  188. // Set system control code
  189. USBKeys_SysCtrl = args[0];
  190. }
  191. // Adds a single USB Code to the USB Output buffer
  192. // Argument #1: USB Code
  193. void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  194. {
  195. // Display capability name
  196. if ( stateType == 0xFF && state == 0xFF )
  197. {
  198. print("Output_usbCodeSend(usbCode)");
  199. return;
  200. }
  201. // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
  202. uint8_t keyPress = 0; // Default to key release, only used for NKRO
  203. switch ( USBKeys_Protocol )
  204. {
  205. case 0: // Boot Mode
  206. // TODO Analog inputs
  207. // Only indicate USB has changed if either a press or release has occured
  208. if ( state == 0x01 || state == 0x03 )
  209. USBKeys_Changed = USBKeyChangeState_MainKeys;
  210. // Only send keypresses if press or hold state
  211. if ( stateType == 0x00 && state == 0x03 ) // Release state
  212. return;
  213. break;
  214. case 1: // NKRO Mode
  215. // Only send press and release events
  216. if ( stateType == 0x00 && state == 0x02 ) // Hold state
  217. return;
  218. // Determine if setting or unsetting the bitfield (press == set)
  219. if ( stateType == 0x00 && state == 0x01 ) // Press state
  220. keyPress = 1;
  221. break;
  222. }
  223. // Get the keycode from arguments
  224. uint8_t key = args[0];
  225. // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
  226. // Boot mode - Maximum of 6 byte codes
  227. // NKRO mode - Each bit of the 26 byte corresponds to a key
  228. // Bits 0 - 45 (bytes 0 - 5) correspond to USB Codes 4 - 49 (Main)
  229. // Bits 48 - 161 (bytes 6 - 20) correspond to USB Codes 51 - 164 (Secondary)
  230. // Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
  231. // Bits 214 - 216 unused
  232. uint8_t bytePosition = 0;
  233. uint8_t byteShift = 0;
  234. switch ( USBKeys_Protocol )
  235. {
  236. case 0: // Boot Mode
  237. // Set the modifier bit if this key is a modifier
  238. if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
  239. {
  240. USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
  241. }
  242. // Normal USB Code
  243. else
  244. {
  245. // USB Key limit reached
  246. if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
  247. {
  248. warn_print("USB Key limit reached");
  249. return;
  250. }
  251. // Make sure key is within the USB HID range
  252. if ( key <= 104 )
  253. {
  254. USBKeys_Keys[USBKeys_Sent++] = key;
  255. }
  256. // Invalid key
  257. else
  258. {
  259. warn_msg("USB Code above 104/0x68 in Boot Mode: ");
  260. printHex( key );
  261. print( NL );
  262. }
  263. }
  264. break;
  265. case 1: // NKRO Mode
  266. // Set the modifier bit if this key is a modifier
  267. if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
  268. {
  269. if ( keyPress )
  270. {
  271. USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
  272. }
  273. else // Release
  274. {
  275. USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
  276. }
  277. USBKeys_Changed |= USBKeyChangeState_Modifiers;
  278. break;
  279. }
  280. // First 6 bytes
  281. else if ( key >= 4 && key <= 50 )
  282. {
  283. // Lookup (otherwise division or multiple checks are needed to do alignment)
  284. uint8_t keyPos = key - (4 - 0); // Starting position in array
  285. switch ( keyPos )
  286. {
  287. byteLookup( 0 );
  288. byteLookup( 1 );
  289. byteLookup( 2 );
  290. byteLookup( 3 );
  291. byteLookup( 4 );
  292. byteLookup( 5 );
  293. }
  294. USBKeys_Changed |= USBKeyChangeState_MainKeys;
  295. }
  296. // Next 15 bytes
  297. else if ( key >= 51 && key <= 164 )
  298. {
  299. // Lookup (otherwise division or multiple checks are needed to do alignment)
  300. uint8_t keyPos = key - (51 - 48); // Starting position in array
  301. switch ( keyPos )
  302. {
  303. byteLookup( 6 );
  304. byteLookup( 7 );
  305. byteLookup( 8 );
  306. byteLookup( 9 );
  307. byteLookup( 10 );
  308. byteLookup( 11 );
  309. byteLookup( 12 );
  310. byteLookup( 13 );
  311. byteLookup( 14 );
  312. byteLookup( 15 );
  313. byteLookup( 16 );
  314. byteLookup( 17 );
  315. byteLookup( 18 );
  316. byteLookup( 19 );
  317. byteLookup( 20 );
  318. }
  319. USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
  320. }
  321. // Last 6 bytes
  322. else if ( key >= 176 && key <= 221 )
  323. {
  324. // Lookup (otherwise division or multiple checks are needed to do alignment)
  325. uint8_t keyPos = key - (176 - 168); // Starting position in array
  326. switch ( keyPos )
  327. {
  328. byteLookup( 21 );
  329. byteLookup( 22 );
  330. byteLookup( 23 );
  331. byteLookup( 24 );
  332. byteLookup( 25 );
  333. byteLookup( 26 );
  334. }
  335. USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
  336. }
  337. // Invalid key
  338. else
  339. {
  340. warn_msg("USB Code not within 4-164 (0x4-0xA4) or 176-221 (0xB0-0xDD) NKRO Mode: ");
  341. printHex( key );
  342. print( NL );
  343. break;
  344. }
  345. // Set/Unset
  346. if ( keyPress )
  347. {
  348. USBKeys_Keys[bytePosition] |= (1 << byteShift);
  349. USBKeys_Sent++;
  350. }
  351. else // Release
  352. {
  353. USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
  354. USBKeys_Sent++;
  355. }
  356. break;
  357. }
  358. }
  359. // ----- Functions -----
  360. // Flush Key buffers
  361. void Output_flushBuffers()
  362. {
  363. // Zero out USBKeys_Keys array
  364. for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
  365. USBKeys_Keys[ c ] = 0;
  366. // Zero out other key buffers
  367. USBKeys_ConsCtrl = 0;
  368. USBKeys_Modifiers = 0;
  369. USBKeys_SysCtrl = 0;
  370. }
  371. // USB Module Setup
  372. inline void Output_setup()
  373. {
  374. // Initialize the USB, and then wait for the host to set configuration.
  375. // This will hang forever if USB does not initialize
  376. usb_init();
  377. while ( !usb_configured() );
  378. // Register USB Output CLI dictionary
  379. CLI_registerDictionary( outputCLIDict, outputCLIDictName );
  380. // Flush key buffers
  381. Output_flushBuffers();
  382. }
  383. // USB Data Send
  384. inline void Output_send()
  385. {
  386. // Boot Mode Only, unset stale keys
  387. if ( USBKeys_Protocol == 0 )
  388. for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
  389. USBKeys_Keys[c] = 0;
  390. // Send keypresses while there are pending changes
  391. while ( USBKeys_Changed )
  392. usb_keyboard_send();
  393. // Clear modifiers and keys
  394. USBKeys_Modifiers = 0;
  395. USBKeys_Sent = 0;
  396. // Signal Scan Module we are finished
  397. switch ( USBKeys_Protocol )
  398. {
  399. case 0: // Boot Mode
  400. Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
  401. break;
  402. case 1: // NKRO Mode
  403. Scan_finishedWithOutput( USBKeys_Sent );
  404. break;
  405. }
  406. }
  407. // Sets the device into firmware reload mode
  408. inline void Output_firmwareReload()
  409. {
  410. usb_device_reload();
  411. }
  412. // USB Input buffer available
  413. inline unsigned int Output_availablechar()
  414. {
  415. return usb_serial_available();
  416. }
  417. // USB Get Character from input buffer
  418. inline int Output_getchar()
  419. {
  420. // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
  421. return (int)usb_serial_getchar();
  422. }
  423. // USB Send Character to output buffer
  424. inline int Output_putchar( char c )
  425. {
  426. return usb_serial_putchar( c );
  427. }
  428. // USB Send String to output buffer, null terminated
  429. inline int Output_putstr( char* str )
  430. {
  431. #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
  432. uint16_t count = 0;
  433. #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) // ARM
  434. uint32_t count = 0;
  435. #endif
  436. // Count characters until NULL character, then send the amount counted
  437. while ( str[count] != '\0' )
  438. count++;
  439. return usb_serial_write( str, count );
  440. }
  441. // Soft Chip Reset
  442. inline void Output_softReset()
  443. {
  444. usb_device_software_reset();
  445. }
  446. // ----- CLI Command Functions -----
  447. void cliFunc_kbdProtocol( char* args )
  448. {
  449. print( NL );
  450. info_msg("Keyboard Protocol: ");
  451. printInt8( USBKeys_Protocol );
  452. }
  453. void cliFunc_readLEDs( char* args )
  454. {
  455. print( NL );
  456. info_msg("LED State: ");
  457. printInt8( USBKeys_LEDs );
  458. }
  459. void cliFunc_sendKeys( char* args )
  460. {
  461. // Copy USBKeys_KeysCLI to USBKeys_Keys
  462. for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
  463. {
  464. // TODO
  465. //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
  466. }
  467. USBKeys_Sent = USBKeys_SentCLI;
  468. // Set modifier byte
  469. USBKeys_Modifiers = USBKeys_ModifiersCLI;
  470. }
  471. void cliFunc_setKeys( char* args )
  472. {
  473. char* curArgs;
  474. char* arg1Ptr;
  475. char* arg2Ptr = args;
  476. // Parse up to USBKeys_MaxSize args (whichever is least)
  477. for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
  478. {
  479. curArgs = arg2Ptr;
  480. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  481. // Stop processing args if no more are found
  482. if ( *arg1Ptr == '\0' )
  483. break;
  484. // Add the USB code to be sent
  485. // TODO
  486. //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
  487. }
  488. }
  489. void cliFunc_setMod( char* args )
  490. {
  491. // Parse number from argument
  492. // NOTE: Only first argument is used
  493. char* arg1Ptr;
  494. char* arg2Ptr;
  495. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  496. USBKeys_ModifiersCLI = numToInt( arg1Ptr );
  497. }