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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. // 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. #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
  32. #include <arm/uart_serial.h>
  33. #include <arm/usb_dev.h>
  34. #include <arm/usb_keyboard.h>
  35. #include <arm/usb_serial.h>
  36. #include "arm/usb_mouse.h"
  37. #endif
  38. // KLL
  39. #include <kll_defs.h>
  40. // Local Includes
  41. #include "output_com.h"
  42. // ----- Macros -----
  43. // Used to build a bitmap lookup table from a byte addressable array
  44. #define byteLookup( byte ) case (( byte ) * ( 8 )): bytePosition = byte; byteShift = 0; break; \
  45. case (( byte ) * ( 8 ) + ( 1 )): bytePosition = byte; byteShift = 1; break; \
  46. case (( byte ) * ( 8 ) + ( 2 )): bytePosition = byte; byteShift = 2; break; \
  47. case (( byte ) * ( 8 ) + ( 3 )): bytePosition = byte; byteShift = 3; break; \
  48. case (( byte ) * ( 8 ) + ( 4 )): bytePosition = byte; byteShift = 4; break; \
  49. case (( byte ) * ( 8 ) + ( 5 )): bytePosition = byte; byteShift = 5; break; \
  50. case (( byte ) * ( 8 ) + ( 6 )): bytePosition = byte; byteShift = 6; break; \
  51. case (( byte ) * ( 8 ) + ( 7 )): bytePosition = byte; byteShift = 7; break
  52. // ----- Function Declarations -----
  53. void cliFunc_kbdProtocol( char* args );
  54. void cliFunc_outputDebug( char* args );
  55. void cliFunc_readLEDs ( char* args );
  56. void cliFunc_readUART ( char* args );
  57. void cliFunc_sendKeys ( char* args );
  58. void cliFunc_sendUART ( char* args );
  59. void cliFunc_setKeys ( char* args );
  60. void cliFunc_setMod ( char* args );
  61. // ----- Variables -----
  62. // Output Module command dictionary
  63. CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
  64. CLIDict_Entry( outputDebug, "Toggle Output Debug mode." );
  65. CLIDict_Entry( readLEDs, "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
  66. CLIDict_Entry( readUART, "Read UART buffer until empty." );
  67. CLIDict_Entry( sendKeys, "Send the prepared list of USB codes and modifier byte." );
  68. CLIDict_Entry( sendUART, "Send characters over UART0." );
  69. CLIDict_Entry( setKeys, "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
  70. 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" );
  71. CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
  72. CLIDict_Item( kbdProtocol ),
  73. CLIDict_Item( outputDebug ),
  74. CLIDict_Item( readLEDs ),
  75. CLIDict_Item( readUART ),
  76. CLIDict_Item( sendKeys ),
  77. CLIDict_Item( sendUART ),
  78. CLIDict_Item( setKeys ),
  79. CLIDict_Item( setMod ),
  80. { 0, 0, 0 } // Null entry for dictionary end
  81. };
  82. // Which modifier keys are currently pressed
  83. // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
  84. // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
  85. uint8_t USBKeys_Modifiers = 0;
  86. uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
  87. // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
  88. uint8_t USBKeys_Keys [USB_NKRO_BITFIELD_SIZE_KEYS];
  89. uint8_t USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
  90. // System Control and Consumer Control 1KRO containers
  91. uint8_t USBKeys_SysCtrl;
  92. uint16_t USBKeys_ConsCtrl;
  93. // The number of keys sent to the usb in the array
  94. uint8_t USBKeys_Sent = 0;
  95. uint8_t USBKeys_SentCLI = 0;
  96. // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
  97. volatile uint8_t USBKeys_LEDs = 0;
  98. // Currently pressed mouse buttons, bitmask, 0 represents no buttons pressed
  99. volatile uint16_t USBMouse_Buttons = 0;
  100. // Relative mouse axis movement, stores pending movement
  101. volatile uint16_t USBMouse_Relative_x = 0;
  102. volatile uint16_t USBMouse_Relative_y = 0;
  103. // Protocol setting from the host.
  104. // 0 - Boot Mode
  105. // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
  106. volatile uint8_t USBKeys_Protocol = USBProtocol_define;
  107. // Indicate if USB should send update
  108. // OS only needs update if there has been a change in state
  109. USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
  110. // Indicate if USB should send update
  111. USBMouseChangeState USBMouse_Changed = 0;
  112. // the idle configuration, how often we send the report to the
  113. // host (ms * 4) even when it hasn't changed
  114. // 0 - Disables
  115. uint8_t USBKeys_Idle_Config = 0;
  116. // Count until idle timeout
  117. uint32_t USBKeys_Idle_Expiry = 0;
  118. uint8_t USBKeys_Idle_Count = 0;
  119. // Indicates whether the Output module is fully functional
  120. // 0 - Not fully functional, 1 - Fully functional
  121. // 0 is often used to show that a USB cable is not plugged in (but has power)
  122. volatile uint8_t Output_Available = 0;
  123. // Debug control variable for Output modules
  124. // 0 - Debug disabled (default)
  125. // 1 - Debug enabled
  126. uint8_t Output_DebugMode = 0;
  127. // mA - Set by outside module if not using USB (i.e. Interconnect)
  128. // Generally set to 100 mA (low power) or 500 mA (high power)
  129. uint16_t Output_ExtCurrent_Available = 0;
  130. // mA - Set by USB module (if exists)
  131. // Initially 100 mA, but may be negotiated higher (e.g. 500 mA)
  132. uint16_t Output_USBCurrent_Available = 0;
  133. // ----- Capabilities -----
  134. // Set Boot Keyboard Protocol
  135. void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  136. {
  137. // Display capability name
  138. if ( stateType == 0xFF && state == 0xFF )
  139. {
  140. print("Output_kbdProtocolBoot()");
  141. return;
  142. }
  143. // Only set if necessary
  144. if ( USBKeys_Protocol == 0 )
  145. return;
  146. // TODO Analog inputs
  147. // Only set on key press
  148. if ( stateType != 0x01 )
  149. return;
  150. // Flush the key buffers
  151. Output_flushBuffers();
  152. // Set the keyboard protocol to Boot Mode
  153. USBKeys_Protocol = 0;
  154. }
  155. // Set NKRO Keyboard Protocol
  156. void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  157. {
  158. // Display capability name
  159. if ( stateType == 0xFF && state == 0xFF )
  160. {
  161. print("Output_kbdProtocolNKRO()");
  162. return;
  163. }
  164. // Only set if necessary
  165. if ( USBKeys_Protocol == 1 )
  166. return;
  167. // TODO Analog inputs
  168. // Only set on key press
  169. if ( stateType != 0x01 )
  170. return;
  171. // Flush the key buffers
  172. Output_flushBuffers();
  173. // Set the keyboard protocol to NKRO Mode
  174. USBKeys_Protocol = 1;
  175. }
  176. // Toggle Keyboard Protocol
  177. void Output_toggleKbdProtocol_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  178. {
  179. // Display capability name
  180. if ( stateType == 0xFF && state == 0xFF )
  181. {
  182. print("Output_toggleKbdProtocol()");
  183. return;
  184. }
  185. // Only toggle protocol if release state
  186. if ( stateType == 0x00 && state == 0x03 )
  187. {
  188. // Flush the key buffers
  189. Output_flushBuffers();
  190. // Toggle the keyboard protocol Mode
  191. USBKeys_Protocol = !USBKeys_Protocol;
  192. }
  193. }
  194. // Sends a Consumer Control code to the USB Output buffer
  195. void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  196. {
  197. // Display capability name
  198. if ( stateType == 0xFF && state == 0xFF )
  199. {
  200. print("Output_consCtrlSend(consCode)");
  201. return;
  202. }
  203. // Not implemented in Boot Mode
  204. if ( USBKeys_Protocol == 0 )
  205. {
  206. warn_print("Consumer Control is not implemented for Boot Mode");
  207. return;
  208. }
  209. // TODO Analog inputs
  210. // Only indicate USB has changed if either a press or release has occured
  211. if ( state == 0x01 || state == 0x03 )
  212. USBKeys_Changed |= USBKeyChangeState_Consumer;
  213. // Only send keypresses if press or hold state
  214. if ( stateType == 0x00 && state == 0x03 ) // Release state
  215. {
  216. USBKeys_ConsCtrl = 0;
  217. return;
  218. }
  219. // Set consumer control code
  220. USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
  221. }
  222. // Ignores the given key status update
  223. // Used to prevent fall-through, this is the None keyword in KLL
  224. void Output_noneSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  225. {
  226. // Display capability name
  227. if ( stateType == 0xFF && state == 0xFF )
  228. {
  229. print("Output_noneSend()");
  230. return;
  231. }
  232. // Nothing to do, because that's the point :P
  233. }
  234. // Sends a System Control code to the USB Output buffer
  235. void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  236. {
  237. // Display capability name
  238. if ( stateType == 0xFF && state == 0xFF )
  239. {
  240. print("Output_sysCtrlSend(sysCode)");
  241. return;
  242. }
  243. // Not implemented in Boot Mode
  244. if ( USBKeys_Protocol == 0 )
  245. {
  246. warn_print("System Control is not implemented for Boot Mode");
  247. return;
  248. }
  249. // TODO Analog inputs
  250. // Only indicate USB has changed if either a press or release has occured
  251. if ( state == 0x01 || state == 0x03 )
  252. USBKeys_Changed |= USBKeyChangeState_System;
  253. // Only send keypresses if press or hold state
  254. if ( stateType == 0x00 && state == 0x03 ) // Release state
  255. {
  256. USBKeys_SysCtrl = 0;
  257. return;
  258. }
  259. // Set system control code
  260. USBKeys_SysCtrl = args[0];
  261. }
  262. // Adds a single USB Code to the USB Output buffer
  263. // Argument #1: USB Code
  264. void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  265. {
  266. // Display capability name
  267. if ( stateType == 0xFF && state == 0xFF )
  268. {
  269. print("Output_usbCodeSend(usbCode)");
  270. return;
  271. }
  272. // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
  273. uint8_t keyPress = 0; // Default to key release, only used for NKRO
  274. switch ( USBKeys_Protocol )
  275. {
  276. case 0: // Boot Mode
  277. // TODO Analog inputs
  278. // Only indicate USB has changed if either a press or release has occured
  279. if ( state == 0x01 || state == 0x03 )
  280. USBKeys_Changed = USBKeyChangeState_MainKeys;
  281. // Only send keypresses if press or hold state
  282. if ( stateType == 0x00 && state == 0x03 ) // Release state
  283. return;
  284. break;
  285. case 1: // NKRO Mode
  286. // Only send press and release events
  287. if ( stateType == 0x00 && state == 0x02 ) // Hold state
  288. return;
  289. // Determine if setting or unsetting the bitfield (press == set)
  290. if ( stateType == 0x00 && state == 0x01 ) // Press state
  291. keyPress = 1;
  292. break;
  293. }
  294. // Get the keycode from arguments
  295. uint8_t key = args[0];
  296. // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
  297. // Boot mode - Maximum of 6 byte codes
  298. // NKRO mode - Each bit of the 26 byte corresponds to a key
  299. // Bits 0 - 45 (bytes 0 - 5) correspond to USB Codes 4 - 49 (Main)
  300. // Bits 48 - 161 (bytes 6 - 20) correspond to USB Codes 51 - 164 (Secondary)
  301. // Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
  302. // Bits 214 - 216 unused
  303. uint8_t bytePosition = 0;
  304. uint8_t byteShift = 0;
  305. switch ( USBKeys_Protocol )
  306. {
  307. case 0: // Boot Mode
  308. // Set the modifier bit if this key is a modifier
  309. if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
  310. {
  311. USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
  312. }
  313. // Normal USB Code
  314. else
  315. {
  316. // USB Key limit reached
  317. if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
  318. {
  319. warn_print("USB Key limit reached");
  320. return;
  321. }
  322. // Make sure key is within the USB HID range
  323. if ( key <= 104 )
  324. {
  325. USBKeys_Keys[USBKeys_Sent++] = key;
  326. }
  327. // Invalid key
  328. else
  329. {
  330. warn_msg("USB Code above 104/0x68 in Boot Mode: ");
  331. printHex( key );
  332. print( NL );
  333. }
  334. }
  335. break;
  336. case 1: // NKRO Mode
  337. // Set the modifier bit if this key is a modifier
  338. if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
  339. {
  340. if ( keyPress )
  341. {
  342. USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
  343. }
  344. else // Release
  345. {
  346. USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
  347. }
  348. USBKeys_Changed |= USBKeyChangeState_Modifiers;
  349. break;
  350. }
  351. // First 6 bytes
  352. else if ( key >= 4 && key <= 49 )
  353. {
  354. // Lookup (otherwise division or multiple checks are needed to do alignment)
  355. // Starting at 0th position, each byte has 8 bits, starting at 4th bit
  356. uint8_t keyPos = key + (0 * 8 - 4); // Starting position in array, Ignoring 4 keys
  357. switch ( keyPos )
  358. {
  359. byteLookup( 0 );
  360. byteLookup( 1 );
  361. byteLookup( 2 );
  362. byteLookup( 3 );
  363. byteLookup( 4 );
  364. byteLookup( 5 );
  365. }
  366. USBKeys_Changed |= USBKeyChangeState_MainKeys;
  367. }
  368. // Next 14 bytes
  369. else if ( key >= 51 && key <= 155 )
  370. {
  371. // Lookup (otherwise division or multiple checks are needed to do alignment)
  372. // Starting at 6th byte position, each byte has 8 bits, starting at 51st bit
  373. uint8_t keyPos = key + (6 * 8 - 51); // Starting position in array
  374. switch ( keyPos )
  375. {
  376. byteLookup( 6 );
  377. byteLookup( 7 );
  378. byteLookup( 8 );
  379. byteLookup( 9 );
  380. byteLookup( 10 );
  381. byteLookup( 11 );
  382. byteLookup( 12 );
  383. byteLookup( 13 );
  384. byteLookup( 14 );
  385. byteLookup( 15 );
  386. byteLookup( 16 );
  387. byteLookup( 17 );
  388. byteLookup( 18 );
  389. byteLookup( 19 );
  390. }
  391. USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
  392. }
  393. // Next byte
  394. else if ( key >= 157 && key <= 164 )
  395. {
  396. // Lookup (otherwise division or multiple checks are needed to do alignment)
  397. uint8_t keyPos = key + (20 * 8 - 157); // Starting position in array, Ignoring 6 keys
  398. switch ( keyPos )
  399. {
  400. byteLookup( 20 );
  401. }
  402. USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
  403. }
  404. // Last 6 bytes
  405. else if ( key >= 176 && key <= 221 )
  406. {
  407. // Lookup (otherwise division or multiple checks are needed to do alignment)
  408. uint8_t keyPos = key + (21 * 8 - 176); // Starting position in array
  409. switch ( keyPos )
  410. {
  411. byteLookup( 21 );
  412. byteLookup( 22 );
  413. byteLookup( 23 );
  414. byteLookup( 24 );
  415. byteLookup( 25 );
  416. byteLookup( 26 );
  417. }
  418. USBKeys_Changed |= USBKeyChangeState_QuartiaryKeys;
  419. }
  420. // Received 0x00
  421. // This is a special USB Code that internally indicates a "break"
  422. // It is used to send "nothing" in order to break up sequences of USB Codes
  423. else if ( key == 0x00 )
  424. {
  425. USBKeys_Changed |= USBKeyChangeState_MainKeys;
  426. // Also flush out buffers just in case
  427. Output_flushBuffers();
  428. break;
  429. }
  430. // Invalid key
  431. else
  432. {
  433. warn_msg("USB Code not within 4-49 (0x4-0x31), 51-155 (0x33-0x9B), 157-164 (0x9D-0xA4), 176-221 (0xB0-0xDD) or 224-231 (0xE0-0xE7) NKRO Mode: ");
  434. printHex( key );
  435. print( NL );
  436. break;
  437. }
  438. // Set/Unset
  439. if ( keyPress )
  440. {
  441. USBKeys_Keys[bytePosition] |= (1 << byteShift);
  442. USBKeys_Sent++;
  443. }
  444. else // Release
  445. {
  446. USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
  447. USBKeys_Sent++;
  448. }
  449. break;
  450. }
  451. }
  452. void Output_flashMode_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  453. {
  454. // Display capability name
  455. if ( stateType == 0xFF && state == 0xFF )
  456. {
  457. print("Output_flashMode()");
  458. return;
  459. }
  460. // Start flash mode
  461. Output_firmwareReload();
  462. }
  463. // Sends a mouse command over the USB Output buffer
  464. // XXX This function *will* be changing in the future
  465. // If you use it, be prepared that your .kll files will break in the future (post KLL 0.5)
  466. // Argument #1: USB Mouse Button (16 bit)
  467. // Argument #2: USB X Axis (16 bit) relative
  468. // Argument #3: USB Y Axis (16 bit) relative
  469. void Output_usbMouse_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  470. {
  471. // Display capability name
  472. if ( stateType == 0xFF && state == 0xFF )
  473. {
  474. print("Output_usbMouse(mouseButton,relX,relY)");
  475. return;
  476. }
  477. // Determine which mouse button was sent
  478. // The USB spec defines up to a max of 0xFFFF buttons
  479. // The usual are:
  480. // 1 - Button 1 - (Primary)
  481. // 2 - Button 2 - (Secondary)
  482. // 3 - Button 3 - (Tertiary)
  483. uint16_t mouse_button = *(uint16_t*)(&args[0]);
  484. // X/Y Relative Axis
  485. uint16_t mouse_x = *(uint16_t*)(&args[2]);
  486. uint16_t mouse_y = *(uint16_t*)(&args[4]);
  487. // Adjust for bit shift
  488. uint16_t mouse_button_shift = mouse_button - 1;
  489. // Only send mouse button if in press or hold state
  490. if ( stateType == 0x00 && state == 0x03 ) // Release state
  491. {
  492. // Release
  493. if ( mouse_button )
  494. USBMouse_Buttons &= ~(1 << mouse_button_shift);
  495. }
  496. else
  497. {
  498. // Press or hold
  499. if ( mouse_button )
  500. USBMouse_Buttons |= (1 << mouse_button_shift);
  501. if ( mouse_x )
  502. USBMouse_Relative_x = mouse_x;
  503. if ( mouse_y )
  504. USBMouse_Relative_y = mouse_y;
  505. }
  506. // Trigger updates
  507. if ( mouse_button )
  508. USBMouse_Changed |= USBMouseChangeState_Buttons;
  509. if ( mouse_x || mouse_y )
  510. USBMouse_Changed |= USBMouseChangeState_Relative;
  511. }
  512. // ----- Functions -----
  513. // Flush Key buffers
  514. void Output_flushBuffers()
  515. {
  516. // Zero out USBKeys_Keys array
  517. for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
  518. USBKeys_Keys[ c ] = 0;
  519. // Zero out other key buffers
  520. USBKeys_ConsCtrl = 0;
  521. USBKeys_Modifiers = 0;
  522. USBKeys_SysCtrl = 0;
  523. }
  524. // USB Module Setup
  525. inline void Output_setup()
  526. {
  527. // Setup UART
  528. uart_serial_setup();
  529. // Initialize the USB
  530. // If a USB connection does not exist, just ignore it
  531. // All usb related functions will non-fatally fail if called
  532. // If the USB initialization is delayed, then functionality will just be delayed
  533. usb_init();
  534. // Register USB Output CLI dictionary
  535. CLI_registerDictionary( outputCLIDict, outputCLIDictName );
  536. // Flush key buffers
  537. Output_flushBuffers();
  538. }
  539. // USB Data Send
  540. inline void Output_send()
  541. {
  542. // USB status checks
  543. // Non-standard USB state manipulation, usually does nothing
  544. usb_device_check();
  545. // Boot Mode Only, unset stale keys
  546. if ( USBKeys_Protocol == 0 )
  547. for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
  548. USBKeys_Keys[c] = 0;
  549. // XXX - Behaves oddly on Mac OSX, might help with corrupted packets specific to OSX? -HaaTa
  550. /*
  551. // Check if idle count has been exceed, this forces usb_keyboard_send and usb_mouse_send to update
  552. // TODO Add joystick as well (may be endpoint specific, currently not kept track of)
  553. if ( usb_configuration && USBKeys_Idle_Config && (
  554. USBKeys_Idle_Expiry < systick_millis_count ||
  555. USBKeys_Idle_Expiry + USBKeys_Idle_Config * 4 >= systick_millis_count ) )
  556. {
  557. USBKeys_Changed = USBKeyChangeState_All;
  558. USBMouse_Changed = USBMouseChangeState_All;
  559. }
  560. */
  561. // Process mouse actions
  562. while ( USBMouse_Changed )
  563. usb_mouse_send();
  564. // Send keypresses while there are pending changes
  565. while ( USBKeys_Changed )
  566. usb_keyboard_send();
  567. // Clear keys sent
  568. USBKeys_Sent = 0;
  569. // Signal Scan Module we are finished
  570. switch ( USBKeys_Protocol )
  571. {
  572. case 0: // Boot Mode
  573. // Clear modifiers only in boot mode
  574. USBKeys_Modifiers = 0;
  575. Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
  576. break;
  577. case 1: // NKRO Mode
  578. Scan_finishedWithOutput( USBKeys_Sent );
  579. break;
  580. }
  581. }
  582. // Sets the device into firmware reload mode
  583. void Output_firmwareReload()
  584. {
  585. usb_device_reload();
  586. }
  587. // USB Input buffer available
  588. inline unsigned int Output_availablechar()
  589. {
  590. return usb_serial_available() + uart_serial_available();
  591. }
  592. // USB Get Character from input buffer
  593. inline int Output_getchar()
  594. {
  595. // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
  596. if ( usb_serial_available() > 0 )
  597. {
  598. return (int)usb_serial_getchar();
  599. }
  600. if ( uart_serial_available() > 0 )
  601. {
  602. return (int)uart_serial_getchar();
  603. }
  604. return -1;
  605. }
  606. // USB Send Character to output buffer
  607. inline int Output_putchar( char c )
  608. {
  609. // First send to UART
  610. uart_serial_putchar( c );
  611. // Then send to USB
  612. return usb_serial_putchar( c );
  613. }
  614. // USB Send String to output buffer, null terminated
  615. inline int Output_putstr( char* str )
  616. {
  617. #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
  618. uint16_t count = 0;
  619. #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
  620. uint32_t count = 0;
  621. #endif
  622. // Count characters until NULL character, then send the amount counted
  623. while ( str[count] != '\0' )
  624. count++;
  625. // First send to UART
  626. uart_serial_write( str, count );
  627. // Then send to USB
  628. return usb_serial_write( str, count );
  629. }
  630. // Soft Chip Reset
  631. inline void Output_softReset()
  632. {
  633. usb_device_software_reset();
  634. }
  635. // Update USB current (mA)
  636. // Triggers power change event
  637. void Output_update_usb_current( unsigned int current )
  638. {
  639. // Only signal if changed
  640. if ( current == Output_USBCurrent_Available )
  641. return;
  642. // Update USB current
  643. Output_USBCurrent_Available = current;
  644. /* XXX Affects sleep states due to USB messages
  645. unsigned int total_current = Output_current_available();
  646. info_msg("USB Available Current Changed. Total Available: ");
  647. printInt32( total_current );
  648. print(" mA" NL);
  649. */
  650. // Send new total current to the Scan Modules
  651. Scan_currentChange( Output_current_available() );
  652. }
  653. // Update external current (mA)
  654. // Triggers power change event
  655. void Output_update_external_current( unsigned int current )
  656. {
  657. // Only signal if changed
  658. if ( current == Output_ExtCurrent_Available )
  659. return;
  660. // Update external current
  661. Output_ExtCurrent_Available = current;
  662. unsigned int total_current = Output_current_available();
  663. info_msg("External Available Current Changed. Total Available: ");
  664. printInt32( total_current );
  665. print(" mA" NL);
  666. // Send new total current to the Scan Modules
  667. Scan_currentChange( Output_current_available() );
  668. }
  669. // Power/Current Available
  670. unsigned int Output_current_available()
  671. {
  672. unsigned int total_current = 0;
  673. // Check for USB current source
  674. total_current += Output_USBCurrent_Available;
  675. // Check for external current source
  676. total_current += Output_ExtCurrent_Available;
  677. // XXX If the total available current is still 0
  678. // Set to 100 mA, which is generally a safe assumption at startup
  679. // before we've been able to determine actual available current
  680. if ( total_current == 0 )
  681. {
  682. total_current = 100;
  683. }
  684. return total_current;
  685. }
  686. // ----- CLI Command Functions -----
  687. void cliFunc_kbdProtocol( char* args )
  688. {
  689. print( NL );
  690. info_msg("Keyboard Protocol: ");
  691. printInt8( USBKeys_Protocol );
  692. }
  693. void cliFunc_outputDebug( char* args )
  694. {
  695. // Parse number from argument
  696. // NOTE: Only first argument is used
  697. char* arg1Ptr;
  698. char* arg2Ptr;
  699. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  700. // Default to 1 if no argument is given
  701. Output_DebugMode = 1;
  702. if ( arg1Ptr[0] != '\0' )
  703. {
  704. Output_DebugMode = (uint16_t)numToInt( arg1Ptr );
  705. }
  706. }
  707. void cliFunc_readLEDs( char* args )
  708. {
  709. print( NL );
  710. info_msg("LED State: ");
  711. printInt8( USBKeys_LEDs );
  712. }
  713. void cliFunc_readUART( char* args )
  714. {
  715. print( NL );
  716. // Read UART buffer until empty
  717. while ( uart_serial_available() > 0 )
  718. {
  719. char out[] = { (char)uart_serial_getchar(), '\0' };
  720. dPrint( out );
  721. }
  722. }
  723. void cliFunc_sendKeys( char* args )
  724. {
  725. // Copy USBKeys_KeysCLI to USBKeys_Keys
  726. for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
  727. {
  728. // TODO
  729. //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
  730. }
  731. USBKeys_Sent = USBKeys_SentCLI;
  732. // Set modifier byte
  733. USBKeys_Modifiers = USBKeys_ModifiersCLI;
  734. }
  735. void cliFunc_sendUART( char* args )
  736. {
  737. // Write all args to UART
  738. uart_serial_write( args, lenStr( args ) );
  739. }
  740. void cliFunc_setKeys( char* args )
  741. {
  742. char* curArgs;
  743. char* arg1Ptr;
  744. char* arg2Ptr = args;
  745. // Parse up to USBKeys_MaxSize args (whichever is least)
  746. for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
  747. {
  748. curArgs = arg2Ptr;
  749. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  750. // Stop processing args if no more are found
  751. if ( *arg1Ptr == '\0' )
  752. break;
  753. // Add the USB code to be sent
  754. // TODO
  755. //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
  756. }
  757. }
  758. void cliFunc_setMod( char* args )
  759. {
  760. // Parse number from argument
  761. // NOTE: Only first argument is used
  762. char* arg1Ptr;
  763. char* arg2Ptr;
  764. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  765. USBKeys_ModifiersCLI = numToInt( arg1Ptr );
  766. }