]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/output_com.c
Initial code for USB cable detection
[kiibohd-controller.git] / Output / pjrcUSB / output_com.c
1 /* Copyright (C) 2011-2015 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
22 // ----- Includes -----
23
24 // Compiler Includes
25 #include <Lib/OutputLib.h>
26
27 // Project Includes
28 #include <cli.h>
29 #include <led.h>
30 #include <print.h>
31 #include <scan_loop.h>
32
33 // USB Includes
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 #endif
41
42 // Local Includes
43 #include "output_com.h"
44
45
46
47 // ----- Macros -----
48
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
58
59
60
61 // ----- Function Declarations -----
62
63 void cliFunc_kbdProtocol( char* args );
64 void cliFunc_readLEDs   ( char* args );
65 void cliFunc_sendKeys   ( char* args );
66 void cliFunc_setKeys    ( char* args );
67 void cliFunc_setMod     ( char* args );
68
69
70
71 // ----- Variables -----
72
73 // Output Module command dictionary
74 CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
75 CLIDict_Entry( readLEDs,    "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
76 CLIDict_Entry( sendKeys,    "Send the prepared list of USB codes and modifier byte." );
77 CLIDict_Entry( setKeys,     "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
78 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" );
79
80 CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
81         CLIDict_Item( kbdProtocol ),
82         CLIDict_Item( readLEDs ),
83         CLIDict_Item( sendKeys ),
84         CLIDict_Item( setKeys ),
85         CLIDict_Item( setMod ),
86         { 0, 0, 0 } // Null entry for dictionary end
87 };
88
89
90 // Which modifier keys are currently pressed
91 // 1=left ctrl,    2=left shift,   4=left alt,    8=left gui
92 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
93          uint8_t  USBKeys_Modifiers    = 0;
94          uint8_t  USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
95
96 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
97          uint8_t  USBKeys_Keys   [USB_NKRO_BITFIELD_SIZE_KEYS];
98          uint8_t  USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
99
100 // System Control and Consumer Control 1KRO containers
101          uint8_t  USBKeys_SysCtrl;
102          uint16_t USBKeys_ConsCtrl;
103
104 // The number of keys sent to the usb in the array
105          uint8_t  USBKeys_Sent    = 0;
106          uint8_t  USBKeys_SentCLI = 0;
107
108 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
109 volatile uint8_t  USBKeys_LEDs = 0;
110
111 // Protocol setting from the host.
112 // 0 - Boot Mode
113 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
114 volatile uint8_t  USBKeys_Protocol = 1;
115
116 // Indicate if USB should send update
117 // OS only needs update if there has been a change in state
118 USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
119
120 // the idle configuration, how often we send the report to the
121 // host (ms * 4) even when it hasn't changed
122          uint8_t  USBKeys_Idle_Config = 125;
123
124 // count until idle timeout
125          uint8_t  USBKeys_Idle_Count = 0;
126
127 // Indicates whether the Output module is fully functional
128 // 0 - Not fully functional, 1 - Fully functional
129 // 0 is often used to show that a USB cable is not plugged in (but has power)
130          uint8_t  Output_Available = 0;
131
132
133
134 // ----- Capabilities -----
135
136 // Set Boot Keyboard Protocol
137 void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
138 {
139         // Display capability name
140         if ( stateType == 0xFF && state == 0xFF )
141         {
142                 print("Output_kbdProtocolBoot()");
143                 return;
144         }
145
146         // Only set if necessary
147         if ( USBKeys_Protocol == 0 )
148                 return;
149
150         // TODO Analog inputs
151         // Only set on key press
152         if ( stateType != 0x01 )
153                 return;
154
155         // Flush the key buffers
156         Output_flushBuffers();
157
158         // Set the keyboard protocol to Boot Mode
159         USBKeys_Protocol = 0;
160 }
161
162
163 // Set NKRO Keyboard Protocol
164 void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
165 {
166         // Display capability name
167         if ( stateType == 0xFF && state == 0xFF )
168         {
169                 print("Output_kbdProtocolNKRO()");
170                 return;
171         }
172
173         // Only set if necessary
174         if ( USBKeys_Protocol == 1 )
175                 return;
176
177         // TODO Analog inputs
178         // Only set on key press
179         if ( stateType != 0x01 )
180                 return;
181
182         // Flush the key buffers
183         Output_flushBuffers();
184
185         // Set the keyboard protocol to NKRO Mode
186         USBKeys_Protocol = 1;
187 }
188
189
190 // Sends a Consumer Control code to the USB Output buffer
191 void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
192 {
193         // Display capability name
194         if ( stateType == 0xFF && state == 0xFF )
195         {
196                 print("Output_consCtrlSend(consCode)");
197                 return;
198         }
199
200         // Not implemented in Boot Mode
201         if ( USBKeys_Protocol == 0 )
202         {
203                 warn_print("Consumer Control is not implemented for Boot Mode");
204                 return;
205         }
206
207         // TODO Analog inputs
208         // Only indicate USB has changed if either a press or release has occured
209         if ( state == 0x01 || state == 0x03 )
210                 USBKeys_Changed |= USBKeyChangeState_Consumer;
211
212         // Only send keypresses if press or hold state
213         if ( stateType == 0x00 && state == 0x03 ) // Release state
214                 return;
215
216         // Set consumer control code
217         USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
218 }
219
220
221 // Sends a System Control code to the USB Output buffer
222 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
223 {
224         // Display capability name
225         if ( stateType == 0xFF && state == 0xFF )
226         {
227                 print("Output_sysCtrlSend(sysCode)");
228                 return;
229         }
230
231         // Not implemented in Boot Mode
232         if ( USBKeys_Protocol == 0 )
233         {
234                 warn_print("System Control is not implemented for Boot Mode");
235                 return;
236         }
237
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_System;
242
243         // Only send keypresses if press or hold state
244         if ( stateType == 0x00 && state == 0x03 ) // Release state
245                 return;
246
247         // Set system control code
248         USBKeys_SysCtrl = args[0];
249 }
250
251
252 // Adds a single USB Code to the USB Output buffer
253 // Argument #1: USB Code
254 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
255 {
256         // Display capability name
257         if ( stateType == 0xFF && state == 0xFF )
258         {
259                 print("Output_usbCodeSend(usbCode)");
260                 return;
261         }
262
263         // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
264         uint8_t keyPress = 0; // Default to key release, only used for NKRO
265         switch ( USBKeys_Protocol )
266         {
267         case 0: // Boot Mode
268                 // TODO Analog inputs
269                 // Only indicate USB has changed if either a press or release has occured
270                 if ( state == 0x01 || state == 0x03 )
271                         USBKeys_Changed = USBKeyChangeState_MainKeys;
272
273                 // Only send keypresses if press or hold state
274                 if ( stateType == 0x00 && state == 0x03 ) // Release state
275                         return;
276                 break;
277         case 1: // NKRO Mode
278                 // Only send press and release events
279                 if ( stateType == 0x00 && state == 0x02 ) // Hold state
280                         return;
281
282                 // Determine if setting or unsetting the bitfield (press == set)
283                 if ( stateType == 0x00 && state == 0x01 ) // Press state
284                         keyPress = 1;
285                 break;
286         }
287
288         // Get the keycode from arguments
289         uint8_t key = args[0];
290
291         // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
292         // Boot mode - Maximum of 6 byte codes
293         // NKRO mode - Each bit of the 26 byte corresponds to a key
294         //  Bits   0 -  45 (bytes  0 -  5) correspond to USB Codes   4 -  49 (Main)
295         //  Bits  48 - 161 (bytes  6 - 20) correspond to USB Codes  51 - 164 (Secondary)
296         //  Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
297         //  Bits 214 - 216                 unused
298         uint8_t bytePosition = 0;
299         uint8_t byteShift = 0;
300         switch ( USBKeys_Protocol )
301         {
302         case 0: // Boot Mode
303                 // Set the modifier bit if this key is a modifier
304                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
305                 {
306                         USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
307                 }
308                 // Normal USB Code
309                 else
310                 {
311                         // USB Key limit reached
312                         if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
313                         {
314                                 warn_print("USB Key limit reached");
315                                 return;
316                         }
317
318                         // Make sure key is within the USB HID range
319                         if ( key <= 104 )
320                         {
321                                 USBKeys_Keys[USBKeys_Sent++] = key;
322                         }
323                         // Invalid key
324                         else
325                         {
326                                 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
327                                 printHex( key );
328                                 print( NL );
329                         }
330                 }
331                 break;
332
333         case 1: // NKRO Mode
334                 // Set the modifier bit if this key is a modifier
335                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
336                 {
337                         if ( keyPress )
338                         {
339                                 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
340                         }
341                         else // Release
342                         {
343                                 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
344                         }
345
346                         USBKeys_Changed |= USBKeyChangeState_Modifiers;
347                         break;
348                 }
349                 // First 6 bytes
350                 else if ( key >= 4 && key <= 49 )
351                 {
352                         // Lookup (otherwise division or multiple checks are needed to do alignment)
353                         // Starting at 0th position, each byte has 8 bits, starting at 4th bit
354                         uint8_t keyPos = key + (0 * 8 - 4); // Starting position in array, Ignoring 4 keys
355                         switch ( keyPos )
356                         {
357                                 byteLookup( 0 );
358                                 byteLookup( 1 );
359                                 byteLookup( 2 );
360                                 byteLookup( 3 );
361                                 byteLookup( 4 );
362                                 byteLookup( 5 );
363                         }
364
365                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
366                 }
367                 // Next 14 bytes
368                 else if ( key >= 51 && key <= 155 )
369                 {
370                         // Lookup (otherwise division or multiple checks are needed to do alignment)
371                         // Starting at 6th byte position, each byte has 8 bits, starting at 51st bit
372                         uint8_t keyPos = key + (6 * 8 - 51); // Starting position in array
373                         switch ( keyPos )
374                         {
375                                 byteLookup( 6 );
376                                 byteLookup( 7 );
377                                 byteLookup( 8 );
378                                 byteLookup( 9 );
379                                 byteLookup( 10 );
380                                 byteLookup( 11 );
381                                 byteLookup( 12 );
382                                 byteLookup( 13 );
383                                 byteLookup( 14 );
384                                 byteLookup( 15 );
385                                 byteLookup( 16 );
386                                 byteLookup( 17 );
387                                 byteLookup( 18 );
388                                 byteLookup( 19 );
389                         }
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
403                         USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
404                 }
405                 // Last 6 bytes
406                 else if ( key >= 176 && key <= 221 )
407                 {
408                         // Lookup (otherwise division or multiple checks are needed to do alignment)
409                         uint8_t keyPos = key + (21 * 8 - 176); // Starting position in array
410                         switch ( keyPos )
411                         {
412                                 byteLookup( 21 );
413                                 byteLookup( 22 );
414                                 byteLookup( 23 );
415                                 byteLookup( 24 );
416                                 byteLookup( 25 );
417                                 byteLookup( 26 );
418                         }
419
420                         USBKeys_Changed |= USBKeyChangeState_QuartiaryKeys;
421                 }
422                 // Received 0x00
423                 // This is a special USB Code that internally indicates a "break"
424                 // It is used to send "nothing" in order to break up sequences of USB Codes
425                 else if ( key == 0x00 )
426                 {
427                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
428
429                         // Also flush out buffers just in case
430                         Output_flushBuffers();
431                         break;
432                 }
433                 // Invalid key
434                 else
435                 {
436                         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: ");
437                         printHex( key );
438                         print( NL );
439                         break;
440                 }
441
442                 // Set/Unset
443                 if ( keyPress )
444                 {
445                         USBKeys_Keys[bytePosition] |= (1 << byteShift);
446                         USBKeys_Sent++;
447                 }
448                 else // Release
449                 {
450                         USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
451                         USBKeys_Sent++;
452                 }
453
454                 break;
455         }
456 }
457
458
459
460 // ----- Functions -----
461
462 // Flush Key buffers
463 void Output_flushBuffers()
464 {
465         // Zero out USBKeys_Keys array
466         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
467                 USBKeys_Keys[ c ] = 0;
468
469         // Zero out other key buffers
470         USBKeys_ConsCtrl = 0;
471         USBKeys_Modifiers = 0;
472         USBKeys_SysCtrl = 0;
473 }
474
475
476 // USB Module Setup
477 inline void Output_setup()
478 {
479         // Initialize the USB, and then wait for the host to set configuration.
480         // This will hang forever if USB does not initialize
481         // If no USB cable is attached, does not try and initialize USB
482         if ( usb_init() )
483         {
484                 while ( !usb_configured() );
485         }
486
487         // Register USB Output CLI dictionary
488         CLI_registerDictionary( outputCLIDict, outputCLIDictName );
489
490         // Flush key buffers
491         Output_flushBuffers();
492 }
493
494
495 // USB Data Send
496 inline void Output_send()
497 {
498         // Boot Mode Only, unset stale keys
499         if ( USBKeys_Protocol == 0 )
500                 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
501                         USBKeys_Keys[c] = 0;
502
503         // Send keypresses while there are pending changes
504         while ( USBKeys_Changed )
505                 usb_keyboard_send();
506
507         // Clear keys sent
508         USBKeys_Sent = 0;
509
510         // Signal Scan Module we are finished
511         switch ( USBKeys_Protocol )
512         {
513         case 0: // Boot Mode
514                 // Clear modifiers only in boot mode
515                 USBKeys_Modifiers = 0;
516                 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
517                 break;
518         case 1: // NKRO Mode
519                 Scan_finishedWithOutput( USBKeys_Sent );
520                 break;
521         }
522 }
523
524
525 // Sets the device into firmware reload mode
526 inline void Output_firmwareReload()
527 {
528         usb_device_reload();
529 }
530
531
532 // USB Input buffer available
533 inline unsigned int Output_availablechar()
534 {
535         return usb_serial_available();
536 }
537
538
539 // USB Get Character from input buffer
540 inline int Output_getchar()
541 {
542         // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
543         return (int)usb_serial_getchar();
544 }
545
546
547 // USB Send Character to output buffer
548 inline int Output_putchar( char c )
549 {
550         return usb_serial_putchar( c );
551 }
552
553
554 // USB Send String to output buffer, null terminated
555 inline int Output_putstr( char* str )
556 {
557 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
558         uint16_t count = 0;
559 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
560         uint32_t count = 0;
561 #endif
562         // Count characters until NULL character, then send the amount counted
563         while ( str[count] != '\0' )
564                 count++;
565
566         return usb_serial_write( str, count );
567 }
568
569
570 // Soft Chip Reset
571 inline void Output_softReset()
572 {
573         usb_device_software_reset();
574 }
575
576
577 // ----- CLI Command Functions -----
578
579 void cliFunc_kbdProtocol( char* args )
580 {
581         print( NL );
582         info_msg("Keyboard Protocol: ");
583         printInt8( USBKeys_Protocol );
584 }
585
586
587 void cliFunc_readLEDs( char* args )
588 {
589         print( NL );
590         info_msg("LED State: ");
591         printInt8( USBKeys_LEDs );
592 }
593
594
595 void cliFunc_sendKeys( char* args )
596 {
597         // Copy USBKeys_KeysCLI to USBKeys_Keys
598         for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
599         {
600                 // TODO
601                 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
602         }
603         USBKeys_Sent = USBKeys_SentCLI;
604
605         // Set modifier byte
606         USBKeys_Modifiers = USBKeys_ModifiersCLI;
607 }
608
609
610 void cliFunc_setKeys( char* args )
611 {
612         char* curArgs;
613         char* arg1Ptr;
614         char* arg2Ptr = args;
615
616         // Parse up to USBKeys_MaxSize args (whichever is least)
617         for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
618         {
619                 curArgs = arg2Ptr;
620                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
621
622                 // Stop processing args if no more are found
623                 if ( *arg1Ptr == '\0' )
624                         break;
625
626                 // Add the USB code to be sent
627                 // TODO
628                 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
629         }
630 }
631
632
633 void cliFunc_setMod( char* args )
634 {
635         // Parse number from argument
636         //  NOTE: Only first argument is used
637         char* arg1Ptr;
638         char* arg2Ptr;
639         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
640
641         USBKeys_ModifiersCLI = numToInt( arg1Ptr );
642 }
643