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