Kiibohd Controller
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

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