1 /* Copyright (C) 2011-2016 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"
40 #include "arm/usb_mouse.h"
47 #include "output_com.h"
53 // Used to build a bitmap lookup table from a byte addressable array
54 #define byteLookup( byte ) \
55 case (( byte ) * ( 8 )): bytePosition = byte; byteShift = 0; break; \
56 case (( byte ) * ( 8 ) + ( 1 )): bytePosition = byte; byteShift = 1; break; \
57 case (( byte ) * ( 8 ) + ( 2 )): bytePosition = byte; byteShift = 2; break; \
58 case (( byte ) * ( 8 ) + ( 3 )): bytePosition = byte; byteShift = 3; break; \
59 case (( byte ) * ( 8 ) + ( 4 )): bytePosition = byte; byteShift = 4; break; \
60 case (( byte ) * ( 8 ) + ( 5 )): bytePosition = byte; byteShift = 5; break; \
61 case (( byte ) * ( 8 ) + ( 6 )): bytePosition = byte; byteShift = 6; break; \
62 case (( byte ) * ( 8 ) + ( 7 )): bytePosition = byte; byteShift = 7; break
66 // ----- Function Declarations -----
68 void cliFunc_kbdProtocol( char* args );
69 void cliFunc_outputDebug( char* args );
70 void cliFunc_readLEDs ( char* args );
71 void cliFunc_sendKeys ( char* args );
72 void cliFunc_setKeys ( char* args );
73 void cliFunc_setMod ( char* args );
77 // ----- Variables -----
79 // Output Module command dictionary
80 CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
81 CLIDict_Entry( outputDebug, "Toggle Output Debug mode." );
82 CLIDict_Entry( readLEDs, "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
83 CLIDict_Entry( sendKeys, "Send the prepared list of USB codes and modifier byte." );
84 CLIDict_Entry( setKeys, "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
85 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" );
87 CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
88 CLIDict_Item( kbdProtocol ),
89 CLIDict_Item( outputDebug ),
90 CLIDict_Item( readLEDs ),
91 CLIDict_Item( sendKeys ),
92 CLIDict_Item( setKeys ),
93 CLIDict_Item( setMod ),
94 { 0, 0, 0 } // Null entry for dictionary end
98 // Which modifier keys are currently pressed
99 // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
100 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
101 uint8_t USBKeys_Modifiers = 0;
102 uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
104 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
105 uint8_t USBKeys_Keys [USB_NKRO_BITFIELD_SIZE_KEYS];
106 uint8_t USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
108 // System Control and Consumer Control 1KRO containers
109 uint8_t USBKeys_SysCtrl;
110 uint16_t USBKeys_ConsCtrl;
112 // The number of keys sent to the usb in the array
113 uint8_t USBKeys_Sent = 0;
114 uint8_t USBKeys_SentCLI = 0;
116 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
117 volatile uint8_t USBKeys_LEDs = 0;
119 // Currently pressed mouse buttons, bitmask, 0 represents no buttons pressed
120 volatile uint16_t USBMouse_Buttons = 0;
122 // Relative mouse axis movement, stores pending movement
123 volatile uint16_t USBMouse_Relative_x = 0;
124 volatile uint16_t USBMouse_Relative_y = 0;
126 // Protocol setting from the host.
128 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
129 volatile uint8_t USBKeys_Protocol = USBProtocol_define;
131 // Indicate if USB should send update
132 // OS only needs update if there has been a change in state
133 USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
135 // Indicate if USB should send update
136 USBMouseChangeState USBMouse_Changed = 0;
138 // the idle configuration, how often we send the report to the
139 // host (ms * 4) even when it hasn't changed
140 uint8_t USBKeys_Idle_Config = 125;
142 // count until idle timeout
143 uint8_t USBKeys_Idle_Count = 0;
145 // Indicates whether the Output module is fully functional
146 // 0 - Not fully functional, 1 - Fully functional
147 // 0 is often used to show that a USB cable is not plugged in (but has power)
148 volatile uint8_t Output_Available = 0;
150 // Debug control variable for Output modules
151 // 0 - Debug disabled (default)
153 uint8_t Output_DebugMode = 0;
155 // mA - Set by outside module if not using USB (i.e. Interconnect)
156 // Generally set to 100 mA (low power) or 500 mA (high power)
157 uint16_t Output_ExtCurrent_Available = 0;
159 // mA - Set by USB module (if exists)
160 // Initially 100 mA, but may be negotiated higher (e.g. 500 mA)
161 uint16_t Output_USBCurrent_Available = 0;
165 // ----- Capabilities -----
167 // Set Boot Keyboard Protocol
168 void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
170 // Display capability name
171 if ( stateType == 0xFF && state == 0xFF )
173 print("Output_kbdProtocolBoot()");
177 // Only set if necessary
178 if ( USBKeys_Protocol == 0 )
181 // TODO Analog inputs
182 // Only set on key press
183 if ( stateType != 0x01 )
186 // Flush the key buffers
187 Output_flushBuffers();
189 // Set the keyboard protocol to Boot Mode
190 USBKeys_Protocol = 0;
194 // Set NKRO Keyboard Protocol
195 void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
197 // Display capability name
198 if ( stateType == 0xFF && state == 0xFF )
200 print("Output_kbdProtocolNKRO()");
204 // Only set if necessary
205 if ( USBKeys_Protocol == 1 )
208 // TODO Analog inputs
209 // Only set on key press
210 if ( stateType != 0x01 )
213 // Flush the key buffers
214 Output_flushBuffers();
216 // Set the keyboard protocol to NKRO Mode
217 USBKeys_Protocol = 1;
221 // Sends a Consumer Control code to the USB Output buffer
222 void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
224 // Display capability name
225 if ( stateType == 0xFF && state == 0xFF )
227 print("Output_consCtrlSend(consCode)");
231 // Not implemented in Boot Mode
232 if ( USBKeys_Protocol == 0 )
234 warn_print("Consumer Control is not implemented for Boot Mode");
238 // TODO Analog inputs
239 // Only indicate USB has changed if either a press or release has occured
240 if ( state == 0x01 || state == 0x03 )
241 USBKeys_Changed |= USBKeyChangeState_Consumer;
243 // Only send keypresses if press or hold state
244 if ( stateType == 0x00 && state == 0x03 ) // Release state
246 USBKeys_ConsCtrl = 0;
250 // Set consumer control code
251 USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
255 // Ignores the given key status update
256 // Used to prevent fall-through, this is the None keyword in KLL
257 void Output_noneSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
259 // Display capability name
260 if ( stateType == 0xFF && state == 0xFF )
262 print("Output_noneSend()");
266 // Nothing to do, because that's the point :P
270 // Sends a System Control code to the USB Output buffer
271 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
273 // Display capability name
274 if ( stateType == 0xFF && state == 0xFF )
276 print("Output_sysCtrlSend(sysCode)");
280 // Not implemented in Boot Mode
281 if ( USBKeys_Protocol == 0 )
283 warn_print("System Control is not implemented for Boot Mode");
287 // TODO Analog inputs
288 // Only indicate USB has changed if either a press or release has occured
289 if ( state == 0x01 || state == 0x03 )
290 USBKeys_Changed |= USBKeyChangeState_System;
292 // Only send keypresses if press or hold state
293 if ( stateType == 0x00 && state == 0x03 ) // Release state
299 // Set system control code
300 USBKeys_SysCtrl = args[0];
304 // Adds a single USB Code to the USB Output buffer
305 // Argument #1: USB Code
306 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
308 // Display capability name
309 if ( stateType == 0xFF && state == 0xFF )
311 print("Output_usbCodeSend(usbCode)");
315 // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
316 uint8_t keyPress = 0; // Default to key release, only used for NKRO
317 switch ( USBKeys_Protocol )
320 // TODO Analog inputs
321 // Only indicate USB has changed if either a press or release has occured
322 if ( state == 0x01 || state == 0x03 )
323 USBKeys_Changed = USBKeyChangeState_MainKeys;
325 // Only send keypresses if press or hold state
326 if ( stateType == 0x00 && state == 0x03 ) // Release state
330 // Only send press and release events
331 if ( stateType == 0x00 && state == 0x02 ) // Hold state
334 // Determine if setting or unsetting the bitfield (press == set)
335 if ( stateType == 0x00 && state == 0x01 ) // Press state
340 // Get the keycode from arguments
341 uint8_t key = args[0];
343 // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
344 // Boot mode - Maximum of 6 byte codes
345 // NKRO mode - Each bit of the 26 byte corresponds to a key
346 // Bits 0 - 45 (bytes 0 - 5) correspond to USB Codes 4 - 49 (Main)
347 // Bits 48 - 161 (bytes 6 - 20) correspond to USB Codes 51 - 164 (Secondary)
348 // Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
349 // Bits 214 - 216 unused
350 uint8_t bytePosition = 0;
351 uint8_t byteShift = 0;
352 switch ( USBKeys_Protocol )
355 // Set the modifier bit if this key is a modifier
356 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
358 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
363 // USB Key limit reached
364 if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
366 warn_print("USB Key limit reached");
370 // Make sure key is within the USB HID range
373 USBKeys_Keys[USBKeys_Sent++] = key;
378 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
386 // Set the modifier bit if this key is a modifier
387 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
391 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
395 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
398 USBKeys_Changed |= USBKeyChangeState_Modifiers;
402 else if ( key >= 4 && key <= 49 )
404 // Lookup (otherwise division or multiple checks are needed to do alignment)
405 // Starting at 0th position, each byte has 8 bits, starting at 4th bit
406 uint8_t keyPos = key + (0 * 8 - 4); // Starting position in array, Ignoring 4 keys
417 USBKeys_Changed |= USBKeyChangeState_MainKeys;
420 else if ( key >= 51 && key <= 155 )
422 // Lookup (otherwise division or multiple checks are needed to do alignment)
423 // Starting at 6th byte position, each byte has 8 bits, starting at 51st bit
424 uint8_t keyPos = key + (6 * 8 - 51); // Starting position in array
443 USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
446 else if ( key >= 157 && key <= 164 )
448 // Lookup (otherwise division or multiple checks are needed to do alignment)
449 uint8_t keyPos = key + (20 * 8 - 157); // Starting position in array, Ignoring 6 keys
455 USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
458 else if ( key >= 176 && key <= 221 )
460 // Lookup (otherwise division or multiple checks are needed to do alignment)
461 uint8_t keyPos = key + (21 * 8 - 176); // Starting position in array
472 USBKeys_Changed |= USBKeyChangeState_QuartiaryKeys;
475 // This is a special USB Code that internally indicates a "break"
476 // It is used to send "nothing" in order to break up sequences of USB Codes
477 else if ( key == 0x00 )
479 USBKeys_Changed |= USBKeyChangeState_MainKeys;
481 // Also flush out buffers just in case
482 Output_flushBuffers();
488 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: ");
497 USBKeys_Keys[bytePosition] |= (1 << byteShift);
502 USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
510 void Output_flashMode_capability( uint8_t state, uint8_t stateType, uint8_t *args )
512 // Display capability name
513 if ( stateType == 0xFF && state == 0xFF )
515 print("Output_flashMode()");
520 Output_firmwareReload();
523 // Sends a mouse command over the USB Output buffer
524 // XXX This function *will* be changing in the future
525 // If you use it, be prepared that your .kll files will break in the future (post KLL 0.5)
526 // Argument #1: USB Mouse Button (16 bit)
527 // Argument #2: USB X Axis (16 bit) relative
528 // Argument #3: USB Y Axis (16 bit) relative
529 void Output_usbMouse_capability( uint8_t state, uint8_t stateType, uint8_t *args )
531 // Display capability name
532 if ( stateType == 0xFF && state == 0xFF )
534 print("Output_usbMouse(mouseButton,relX,relY)");
538 // Determine which mouse button was sent
539 // The USB spec defines up to a max of 0xFFFF buttons
541 // 1 - Button 1 - (Primary)
542 // 2 - Button 2 - (Secondary)
543 // 3 - Button 3 - (Tertiary)
544 uint16_t mouse_button = *(uint16_t*)(&args[0]);
547 uint16_t mouse_x = *(uint16_t*)(&args[2]);
548 uint16_t mouse_y = *(uint16_t*)(&args[4]);
550 // Adjust for bit shift
551 uint16_t mouse_button_shift = mouse_button - 1;
553 // Only send mouse button if in press or hold state
554 if ( stateType == 0x00 && state == 0x03 ) // Release state
558 USBMouse_Buttons &= ~(1 << mouse_button_shift);
564 USBMouse_Buttons |= (1 << mouse_button_shift);
567 USBMouse_Relative_x = mouse_x;
569 USBMouse_Relative_y = mouse_y;
574 USBMouse_Changed |= USBMouseChangeState_Buttons;
576 if ( mouse_x || mouse_y )
577 USBMouse_Changed |= USBMouseChangeState_Relative;
582 // ----- Functions -----
585 void Output_flushBuffers()
587 // Zero out USBKeys_Keys array
588 for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
589 USBKeys_Keys[ c ] = 0;
591 // Zero out other key buffers
592 USBKeys_ConsCtrl = 0;
593 USBKeys_Modifiers = 0;
599 inline void Output_setup()
601 // Initialize the USB
602 // If a USB connection does not exist, just ignore it
603 // All usb related functions will non-fatally fail if called
604 // If the USB initialization is delayed, then functionality will just be delayed
607 // Register USB Output CLI dictionary
608 CLI_registerDictionary( outputCLIDict, outputCLIDictName );
611 Output_flushBuffers();
616 inline void Output_send()
619 // Non-standard USB state manipulation, usually does nothing
622 // Boot Mode Only, unset stale keys
623 if ( USBKeys_Protocol == 0 )
624 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
627 // Process mouse actions
628 while ( USBMouse_Changed )
631 // Send keypresses while there are pending changes
632 while ( USBKeys_Changed )
638 // Signal Scan Module we are finished
639 switch ( USBKeys_Protocol )
642 // Clear modifiers only in boot mode
643 USBKeys_Modifiers = 0;
644 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
647 Scan_finishedWithOutput( USBKeys_Sent );
653 // Sets the device into firmware reload mode
654 inline void Output_firmwareReload()
660 // USB Input buffer available
661 inline unsigned int Output_availablechar()
663 return usb_serial_available();
667 // USB Get Character from input buffer
668 inline int Output_getchar()
670 // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
671 return (int)usb_serial_getchar();
675 // USB Send Character to output buffer
676 inline int Output_putchar( char c )
678 return usb_serial_putchar( c );
682 // USB Send String to output buffer, null terminated
683 inline int Output_putstr( char* str )
685 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
687 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
690 // Count characters until NULL character, then send the amount counted
691 while ( str[count] != '\0' )
694 return usb_serial_write( str, count );
699 inline void Output_softReset()
701 usb_device_software_reset();
705 // Update USB current (mA)
706 // Triggers power change event
707 void Output_update_usb_current( unsigned int current )
709 // Only signal if changed
710 if ( current == Output_USBCurrent_Available )
713 // Update USB current
714 Output_USBCurrent_Available = current;
716 unsigned int total_current = Output_current_available();
717 info_msg("USB Available Current Changed. Total Available: ");
718 printInt32( total_current );
721 // Send new total current to the Scan Modules
722 Scan_currentChange( Output_current_available() );
726 // Update external current (mA)
727 // Triggers power change event
728 void Output_update_external_current( unsigned int current )
730 // Only signal if changed
731 if ( current == Output_ExtCurrent_Available )
734 // Update external current
735 Output_ExtCurrent_Available = current;
737 unsigned int total_current = Output_current_available();
738 info_msg("External Available Current Changed. Total Available: ");
739 printInt32( total_current );
742 // Send new total current to the Scan Modules
743 Scan_currentChange( Output_current_available() );
747 // Power/Current Available
748 unsigned int Output_current_available()
750 unsigned int total_current = 0;
752 // Check for USB current source
753 total_current += Output_USBCurrent_Available;
755 // Check for external current source
756 total_current += Output_ExtCurrent_Available;
758 // XXX If the total available current is still 0
759 // Set to 100 mA, which is generally a safe assumption at startup
760 // before we've been able to determine actual available current
761 if ( total_current == 0 )
766 return total_current;
771 // ----- CLI Command Functions -----
773 void cliFunc_kbdProtocol( char* args )
776 info_msg("Keyboard Protocol: ");
777 printInt8( USBKeys_Protocol );
781 void cliFunc_outputDebug( char* args )
783 // Parse number from argument
784 // NOTE: Only first argument is used
787 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
789 // Default to 1 if no argument is given
790 Output_DebugMode = 1;
792 if ( arg1Ptr[0] != '\0' )
794 Output_DebugMode = (uint16_t)numToInt( arg1Ptr );
799 void cliFunc_readLEDs( char* args )
802 info_msg("LED State: ");
803 printInt8( USBKeys_LEDs );
807 void cliFunc_sendKeys( char* args )
809 // Copy USBKeys_KeysCLI to USBKeys_Keys
810 for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
813 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
815 USBKeys_Sent = USBKeys_SentCLI;
818 USBKeys_Modifiers = USBKeys_ModifiersCLI;
822 void cliFunc_setKeys( char* args )
826 char* arg2Ptr = args;
828 // Parse up to USBKeys_MaxSize args (whichever is least)
829 for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
832 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
834 // Stop processing args if no more are found
835 if ( *arg1Ptr == '\0' )
838 // Add the USB code to be sent
840 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
845 void cliFunc_setMod( char* args )
847 // Parse number from argument
848 // NOTE: Only first argument is used
851 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
853 USBKeys_ModifiersCLI = numToInt( arg1Ptr );