1 /* Copyright (C) 2014 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 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
36 #include "../uartOut/arm/uart_serial.h"
37 #include "../pjrcUSB/arm/usb_dev.h"
38 #include "../pjrcUSB/arm/usb_keyboard.h"
39 #include "../pjrcUSB/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_readLEDs ( char* args );
65 void cliFunc_readUART ( char* args );
66 void cliFunc_sendKeys ( char* args );
67 void cliFunc_sendUART ( char* args );
68 void cliFunc_setKeys ( char* args );
69 void cliFunc_setMod ( char* args );
73 // ----- Variables -----
75 // Output Module command dictionary
76 CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
77 CLIDict_Entry( readLEDs, "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
78 CLIDict_Entry( readUART, "Read UART buffer until empty." );
79 CLIDict_Entry( sendKeys, "Send the prepared list of USB codes and modifier byte." );
80 CLIDict_Entry( sendUART, "Send characters over UART0." );
81 CLIDict_Entry( setKeys, "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
82 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" );
84 CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
85 CLIDict_Item( kbdProtocol ),
86 CLIDict_Item( readLEDs ),
87 CLIDict_Item( readUART ),
88 CLIDict_Item( sendKeys ),
89 CLIDict_Item( sendUART ),
90 CLIDict_Item( setKeys ),
91 CLIDict_Item( setMod ),
92 { 0, 0, 0 } // Null entry for dictionary end
96 // Which modifier keys are currently pressed
97 // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
98 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
99 uint8_t USBKeys_Modifiers = 0;
100 uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
102 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
103 uint8_t USBKeys_Keys [USB_NKRO_BITFIELD_SIZE_KEYS];
104 uint8_t USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
106 // System Control and Consumer Control 1KRO containers
107 uint8_t USBKeys_SysCtrl;
108 uint16_t USBKeys_ConsCtrl;
110 // The number of keys sent to the usb in the array
111 uint8_t USBKeys_Sent = 0;
112 uint8_t USBKeys_SentCLI = 0;
114 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
115 volatile uint8_t USBKeys_LEDs = 0;
117 // Protocol setting from the host.
119 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
120 volatile uint8_t USBKeys_Protocol = 0;
122 // Indicate if USB should send update
123 // OS only needs update if there has been a change in state
124 USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
126 // the idle configuration, how often we send the report to the
127 // host (ms * 4) even when it hasn't changed
128 uint8_t USBKeys_Idle_Config = 125;
130 // count until idle timeout
131 uint8_t USBKeys_Idle_Count = 0;
135 // ----- Capabilities -----
137 // Sends a Consumer Control code to the USB Output buffer
138 void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
140 // Display capability name
141 if ( stateType == 0xFF && state == 0xFF )
143 print("Output_consCtrlSend(consCode)");
147 // Not implemented in Boot Mode
148 if ( USBKeys_Protocol == 0 )
150 warn_print("Consumer Control is not implemented for Boot Mode");
154 // TODO Analog inputs
155 // Only indicate USB has changed if either a press or release has occured
156 if ( state == 0x01 || state == 0x03 )
157 USBKeys_Changed |= USBKeyChangeState_Consumer;
159 // Only send keypresses if press or hold state
160 if ( stateType == 0x00 && state == 0x03 ) // Release state
163 // Set consumer control code
164 USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
168 // Sends a System Control code to the USB Output buffer
169 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
171 // Display capability name
172 if ( stateType == 0xFF && state == 0xFF )
174 print("Output_sysCtrlSend(sysCode)");
178 // Not implemented in Boot Mode
179 if ( USBKeys_Protocol == 0 )
181 warn_print("System Control is not implemented for Boot Mode");
185 // TODO Analog inputs
186 // Only indicate USB has changed if either a press or release has occured
187 if ( state == 0x01 || state == 0x03 )
188 USBKeys_Changed |= USBKeyChangeState_System;
190 // Only send keypresses if press or hold state
191 if ( stateType == 0x00 && state == 0x03 ) // Release state
194 // Set system control code
195 USBKeys_SysCtrl = args[0];
199 // Adds a single USB Code to the USB Output buffer
200 // Argument #1: USB Code
201 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
203 // Display capability name
204 if ( stateType == 0xFF && state == 0xFF )
206 print("Output_usbCodeSend(usbCode)");
210 // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
211 uint8_t keyPress = 0; // Default to key release, only used for NKRO
212 switch ( USBKeys_Protocol )
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_MainKeys;
220 // Only send keypresses if press or hold state
221 if ( stateType == 0x00 && state == 0x03 ) // Release state
225 // Only send press and release events
226 if ( stateType == 0x00 && state == 0x02 ) // Hold state
229 // Determine if setting or unsetting the bitfield (press == set)
230 if ( stateType == 0x00 && state == 0x01 ) // Press state
235 // Get the keycode from arguments
236 uint8_t key = args[0];
238 // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
239 // Boot mode - Maximum of 6 byte codes
240 // NKRO mode - Each bit of the 26 byte corresponds to a key
241 // Bits 0 - 160 (first 20 bytes) correspond to USB Codes 4 - 164
242 // Bits 161 - 205 (last 6 bytes) correspond to USB Codes 176 - 221
243 // Bits 206 - 208 (last byte) correspond to the 3 padded bits in USB (unused)
244 uint8_t bytePosition = 0;
245 uint8_t byteShift = 0;
246 switch ( USBKeys_Protocol )
249 // Set the modifier bit if this key is a modifier
250 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
252 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
257 // USB Key limit reached
258 if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
260 warn_print("USB Key limit reached");
264 // Make sure key is within the USB HID range
267 USBKeys_Keys[USBKeys_Sent++] = key;
272 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
280 // Set the modifier bit if this key is a modifier
281 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
285 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
289 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
292 USBKeys_Changed |= USBKeyChangeState_Modifiers;
296 else if ( key >= 4 && key <= 164 )
298 // Lookup (otherwise division or multiple checks are needed to do alignment)
299 uint8_t keyPos = key - 4; // Starting position in array
324 USBKeys_Changed |= USBKeyChangeState_MainKeys;
327 else if ( key >= 176 && key <= 221 )
329 // Lookup (otherwise division or multiple checks are needed to do alignment)
330 uint8_t keyPos = key - 176; // Starting position in array
341 USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
346 warn_msg("USB Code not within 4-164 (0x4-0xA4) or 176-221 (0xB0-0xDD) NKRO Mode: ");
355 USBKeys_Keys[bytePosition] |= (1 << byteShift);
360 USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
370 // ----- Functions -----
373 inline void Output_setup()
377 print("\033[2J"); // Clear screen
379 // Initialize the USB, and then wait for the host to set configuration.
380 // This will hang forever if USB does not initialize
383 while ( !usb_configured() );
385 // Register USB Output CLI dictionary
386 CLI_registerDictionary( outputCLIDict, outputCLIDictName );
388 // Zero out USBKeys_Keys array
389 for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
390 USBKeys_Keys[ c ] = 0;
395 inline void Output_send()
397 // Boot Mode Only, unset stale keys
398 if ( USBKeys_Protocol == 0 )
399 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
402 // Send keypresses while there are pending changes
403 while ( USBKeys_Changed )
406 // Clear modifiers and keys
407 USBKeys_Modifiers = 0;
410 // Signal Scan Module we are finished
411 switch ( USBKeys_Protocol )
414 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
417 Scan_finishedWithOutput( USBKeys_Sent );
423 // Sets the device into firmware reload mode
424 inline void Output_firmwareReload()
426 uart_device_reload();
430 // USB Input buffer available
431 inline unsigned int Output_availablechar()
433 return usb_serial_available() + uart_serial_available();
437 // USB Get Character from input buffer
438 inline int Output_getchar()
440 // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
441 if ( usb_serial_available() > 0 )
443 return (int)usb_serial_getchar();
446 if ( uart_serial_available() > 0 )
448 return (int)uart_serial_getchar();
455 // USB Send Character to output buffer
456 inline int Output_putchar( char c )
458 // First send to UART
459 uart_serial_putchar( c );
462 return usb_serial_putchar( c );
466 // USB Send String to output buffer, null terminated
467 inline int Output_putstr( char* str )
469 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
471 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
474 // Count characters until NULL character, then send the amount counted
475 while ( str[count] != '\0' )
478 // First send to UART
479 uart_serial_write( str, count );
482 return usb_serial_write( str, count );
487 inline void Output_softReset()
489 usb_device_software_reset();
493 // ----- CLI Command Functions -----
495 void cliFunc_kbdProtocol( char* args )
498 info_msg("Keyboard Protocol: ");
499 printInt8( USBKeys_Protocol );
503 void cliFunc_readLEDs( char* args )
506 info_msg("LED State: ");
507 printInt8( USBKeys_LEDs );
511 void cliFunc_readUART( char* args )
515 // Read UART buffer until empty
516 while ( uart_serial_available() > 0 )
518 char out[] = { (char)uart_serial_getchar(), '\0' };
524 void cliFunc_sendKeys( char* args )
526 // Copy USBKeys_KeysCLI to USBKeys_Keys
527 for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
530 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
532 USBKeys_Sent = USBKeys_SentCLI;
535 USBKeys_Modifiers = USBKeys_ModifiersCLI;
539 void cliFunc_sendUART( char* args )
541 // Write all args to UART
542 uart_serial_write( args, lenStr( args ) );
546 void cliFunc_setKeys( char* args )
550 char* arg2Ptr = args;
552 // Parse up to USBKeys_MaxSize args (whichever is least)
553 for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
556 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
558 // Stop processing args if no more are found
559 if ( *arg1Ptr == '\0' )
562 // Add the USB code to be sent
564 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
569 void cliFunc_setMod( char* args )
571 // Parse number from argument
572 // NOTE: Only first argument is used
575 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
577 USBKeys_ModifiersCLI = numToInt( arg1Ptr );