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