1 /* Copyright (C) 2011-2015 by Jacob Alexander
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:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
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
22 // ----- Includes -----
25 #include <Lib/OutputLib.h>
31 #include <scan_loop.h>
34 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_)
35 #include "avr/usb_keyboard_serial.h"
36 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
37 #include "arm/usb_dev.h"
38 #include "arm/usb_keyboard.h"
39 #include "arm/usb_serial.h"
43 #include "output_com.h"
49 // Used to build a bitmap lookup table from a byte addressable array
50 #define byteLookup( byte ) case (( byte ) * ( 8 )): bytePosition = byte; byteShift = 0; break; \
51 case (( byte ) * ( 8 ) + ( 1 )): bytePosition = byte; byteShift = 1; break; \
52 case (( byte ) * ( 8 ) + ( 2 )): bytePosition = byte; byteShift = 2; break; \
53 case (( byte ) * ( 8 ) + ( 3 )): bytePosition = byte; byteShift = 3; break; \
54 case (( byte ) * ( 8 ) + ( 4 )): bytePosition = byte; byteShift = 4; break; \
55 case (( byte ) * ( 8 ) + ( 5 )): bytePosition = byte; byteShift = 5; break; \
56 case (( byte ) * ( 8 ) + ( 6 )): bytePosition = byte; byteShift = 6; break; \
57 case (( byte ) * ( 8 ) + ( 7 )): bytePosition = byte; byteShift = 7; break
61 // ----- Function Declarations -----
63 void cliFunc_kbdProtocol( char* args );
64 void cliFunc_outputDebug( char* args );
65 void cliFunc_readLEDs ( char* args );
66 void cliFunc_sendKeys ( char* args );
67 void cliFunc_setKeys ( char* args );
68 void cliFunc_setMod ( char* args );
72 // ----- Variables -----
74 // Output Module command dictionary
75 CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
76 CLIDict_Entry( outputDebug, "Toggle Output Debug mode." );
77 CLIDict_Entry( readLEDs, "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
78 CLIDict_Entry( sendKeys, "Send the prepared list of USB codes and modifier byte." );
79 CLIDict_Entry( setKeys, "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
80 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" );
82 CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
83 CLIDict_Item( kbdProtocol ),
84 CLIDict_Item( outputDebug ),
85 CLIDict_Item( readLEDs ),
86 CLIDict_Item( sendKeys ),
87 CLIDict_Item( setKeys ),
88 CLIDict_Item( setMod ),
89 { 0, 0, 0 } // Null entry for dictionary end
93 // Which modifier keys are currently pressed
94 // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
95 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
96 uint8_t USBKeys_Modifiers = 0;
97 uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
99 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
100 uint8_t USBKeys_Keys [USB_NKRO_BITFIELD_SIZE_KEYS];
101 uint8_t USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
103 // System Control and Consumer Control 1KRO containers
104 uint8_t USBKeys_SysCtrl;
105 uint16_t USBKeys_ConsCtrl;
107 // The number of keys sent to the usb in the array
108 uint8_t USBKeys_Sent = 0;
109 uint8_t USBKeys_SentCLI = 0;
111 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
112 volatile uint8_t USBKeys_LEDs = 0;
114 // Protocol setting from the host.
116 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
117 volatile uint8_t USBKeys_Protocol = 1;
119 // Indicate if USB should send update
120 // OS only needs update if there has been a change in state
121 USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
123 // the idle configuration, how often we send the report to the
124 // host (ms * 4) even when it hasn't changed
125 uint8_t USBKeys_Idle_Config = 125;
127 // count until idle timeout
128 uint8_t USBKeys_Idle_Count = 0;
130 // Indicates whether the Output module is fully functional
131 // 0 - Not fully functional, 1 - Fully functional
132 // 0 is often used to show that a USB cable is not plugged in (but has power)
133 uint8_t Output_Available = 0;
135 // Debug control variable for Output modules
136 // 0 - Debug disabled (default)
138 uint8_t Output_DebugMode = 0;
142 // ----- Capabilities -----
144 // Set Boot Keyboard Protocol
145 void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
147 // Display capability name
148 if ( stateType == 0xFF && state == 0xFF )
150 print("Output_kbdProtocolBoot()");
154 // Only set if necessary
155 if ( USBKeys_Protocol == 0 )
158 // TODO Analog inputs
159 // Only set on key press
160 if ( stateType != 0x01 )
163 // Flush the key buffers
164 Output_flushBuffers();
166 // Set the keyboard protocol to Boot Mode
167 USBKeys_Protocol = 0;
171 // Set NKRO Keyboard Protocol
172 void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
174 // Display capability name
175 if ( stateType == 0xFF && state == 0xFF )
177 print("Output_kbdProtocolNKRO()");
181 // Only set if necessary
182 if ( USBKeys_Protocol == 1 )
185 // TODO Analog inputs
186 // Only set on key press
187 if ( stateType != 0x01 )
190 // Flush the key buffers
191 Output_flushBuffers();
193 // Set the keyboard protocol to NKRO Mode
194 USBKeys_Protocol = 1;
198 // Sends a Consumer Control code to the USB Output buffer
199 void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
201 // Display capability name
202 if ( stateType == 0xFF && state == 0xFF )
204 print("Output_consCtrlSend(consCode)");
208 // Not implemented in Boot Mode
209 if ( USBKeys_Protocol == 0 )
211 warn_print("Consumer Control is not implemented for Boot Mode");
215 // TODO Analog inputs
216 // Only indicate USB has changed if either a press or release has occured
217 if ( state == 0x01 || state == 0x03 )
218 USBKeys_Changed |= USBKeyChangeState_Consumer;
220 // Only send keypresses if press or hold state
221 if ( stateType == 0x00 && state == 0x03 ) // Release state
223 USBKeys_ConsCtrl = 0;
227 // Set consumer control code
228 USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
232 // Ignores the given key status update
233 // Used to prevent fall-through, this is the None keyword in KLL
234 void Output_noneSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
236 // Display capability name
237 if ( stateType == 0xFF && state == 0xFF )
239 print("Output_noneSend()");
243 // Nothing to do, because that's the point :P
247 // Sends a System Control code to the USB Output buffer
248 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
250 // Display capability name
251 if ( stateType == 0xFF && state == 0xFF )
253 print("Output_sysCtrlSend(sysCode)");
257 // Not implemented in Boot Mode
258 if ( USBKeys_Protocol == 0 )
260 warn_print("System Control is not implemented for Boot Mode");
264 // TODO Analog inputs
265 // Only indicate USB has changed if either a press or release has occured
266 if ( state == 0x01 || state == 0x03 )
267 USBKeys_Changed |= USBKeyChangeState_System;
269 // Only send keypresses if press or hold state
270 if ( stateType == 0x00 && state == 0x03 ) // Release state
276 // Set system control code
277 USBKeys_SysCtrl = args[0];
281 // Adds a single USB Code to the USB Output buffer
282 // Argument #1: USB Code
283 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
285 // Display capability name
286 if ( stateType == 0xFF && state == 0xFF )
288 print("Output_usbCodeSend(usbCode)");
292 // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
293 uint8_t keyPress = 0; // Default to key release, only used for NKRO
294 switch ( USBKeys_Protocol )
297 // TODO Analog inputs
298 // Only indicate USB has changed if either a press or release has occured
299 if ( state == 0x01 || state == 0x03 )
300 USBKeys_Changed = USBKeyChangeState_MainKeys;
302 // Only send keypresses if press or hold state
303 if ( stateType == 0x00 && state == 0x03 ) // Release state
307 // Only send press and release events
308 if ( stateType == 0x00 && state == 0x02 ) // Hold state
311 // Determine if setting or unsetting the bitfield (press == set)
312 if ( stateType == 0x00 && state == 0x01 ) // Press state
317 // Get the keycode from arguments
318 uint8_t key = args[0];
320 // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
321 // Boot mode - Maximum of 6 byte codes
322 // NKRO mode - Each bit of the 26 byte corresponds to a key
323 // Bits 0 - 45 (bytes 0 - 5) correspond to USB Codes 4 - 49 (Main)
324 // Bits 48 - 161 (bytes 6 - 20) correspond to USB Codes 51 - 164 (Secondary)
325 // Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
326 // Bits 214 - 216 unused
327 uint8_t bytePosition = 0;
328 uint8_t byteShift = 0;
329 switch ( USBKeys_Protocol )
332 // Set the modifier bit if this key is a modifier
333 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
335 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
340 // USB Key limit reached
341 if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
343 warn_print("USB Key limit reached");
347 // Make sure key is within the USB HID range
350 USBKeys_Keys[USBKeys_Sent++] = key;
355 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
363 // Set the modifier bit if this key is a modifier
364 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
368 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
372 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
375 USBKeys_Changed |= USBKeyChangeState_Modifiers;
379 else if ( key >= 4 && key <= 49 )
381 // Lookup (otherwise division or multiple checks are needed to do alignment)
382 // Starting at 0th position, each byte has 8 bits, starting at 4th bit
383 uint8_t keyPos = key + (0 * 8 - 4); // Starting position in array, Ignoring 4 keys
394 USBKeys_Changed |= USBKeyChangeState_MainKeys;
397 else if ( key >= 51 && key <= 155 )
399 // Lookup (otherwise division or multiple checks are needed to do alignment)
400 // Starting at 6th byte position, each byte has 8 bits, starting at 51st bit
401 uint8_t keyPos = key + (6 * 8 - 51); // Starting position in array
420 USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
423 else if ( key >= 157 && key <= 164 )
425 // Lookup (otherwise division or multiple checks are needed to do alignment)
426 uint8_t keyPos = key + (20 * 8 - 157); // Starting position in array, Ignoring 6 keys
432 USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
435 else if ( key >= 176 && key <= 221 )
437 // Lookup (otherwise division or multiple checks are needed to do alignment)
438 uint8_t keyPos = key + (21 * 8 - 176); // Starting position in array
449 USBKeys_Changed |= USBKeyChangeState_QuartiaryKeys;
452 // This is a special USB Code that internally indicates a "break"
453 // It is used to send "nothing" in order to break up sequences of USB Codes
454 else if ( key == 0x00 )
456 USBKeys_Changed |= USBKeyChangeState_MainKeys;
458 // Also flush out buffers just in case
459 Output_flushBuffers();
465 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: ");
474 USBKeys_Keys[bytePosition] |= (1 << byteShift);
479 USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
489 // ----- Functions -----
492 void Output_flushBuffers()
494 // Zero out USBKeys_Keys array
495 for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
496 USBKeys_Keys[ c ] = 0;
498 // Zero out other key buffers
499 USBKeys_ConsCtrl = 0;
500 USBKeys_Modifiers = 0;
506 inline void Output_setup()
508 // Initialize the USB, and then wait for the host to set configuration.
509 // This will hang forever if USB does not initialize
510 // If no USB cable is attached, does not try and initialize USB
513 while ( !usb_configured() );
516 // Register USB Output CLI dictionary
517 CLI_registerDictionary( outputCLIDict, outputCLIDictName );
520 Output_flushBuffers();
525 inline void Output_send()
527 // Boot Mode Only, unset stale keys
528 if ( USBKeys_Protocol == 0 )
529 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
532 // Send keypresses while there are pending changes
533 while ( USBKeys_Changed )
539 // Signal Scan Module we are finished
540 switch ( USBKeys_Protocol )
543 // Clear modifiers only in boot mode
544 USBKeys_Modifiers = 0;
545 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
548 Scan_finishedWithOutput( USBKeys_Sent );
554 // Sets the device into firmware reload mode
555 inline void Output_firmwareReload()
561 // USB Input buffer available
562 inline unsigned int Output_availablechar()
564 return usb_serial_available();
568 // USB Get Character from input buffer
569 inline int Output_getchar()
571 // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
572 return (int)usb_serial_getchar();
576 // USB Send Character to output buffer
577 inline int Output_putchar( char c )
579 return usb_serial_putchar( c );
583 // USB Send String to output buffer, null terminated
584 inline int Output_putstr( char* str )
586 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
588 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
591 // Count characters until NULL character, then send the amount counted
592 while ( str[count] != '\0' )
595 return usb_serial_write( str, count );
600 inline void Output_softReset()
602 usb_device_software_reset();
606 // ----- CLI Command Functions -----
608 void cliFunc_kbdProtocol( char* args )
611 info_msg("Keyboard Protocol: ");
612 printInt8( USBKeys_Protocol );
616 void cliFunc_outputDebug( char* args )
618 // Parse number from argument
619 // NOTE: Only first argument is used
622 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
624 // Default to 1 if no argument is given
625 Output_DebugMode = 1;
627 if ( arg1Ptr[0] != '\0' )
629 Output_DebugMode = (uint16_t)numToInt( arg1Ptr );
634 void cliFunc_readLEDs( char* args )
637 info_msg("LED State: ");
638 printInt8( USBKeys_LEDs );
642 void cliFunc_sendKeys( char* args )
644 // Copy USBKeys_KeysCLI to USBKeys_Keys
645 for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
648 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
650 USBKeys_Sent = USBKeys_SentCLI;
653 USBKeys_Modifiers = USBKeys_ModifiersCLI;
657 void cliFunc_setKeys( char* args )
661 char* arg2Ptr = args;
663 // Parse up to USBKeys_MaxSize args (whichever is least)
664 for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
667 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
669 // Stop processing args if no more are found
670 if ( *arg1Ptr == '\0' )
673 // Add the USB code to be sent
675 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
680 void cliFunc_setMod( char* args )
682 // Parse number from argument
683 // NOTE: Only first argument is used
686 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
688 USBKeys_ModifiersCLI = numToInt( arg1Ptr );