]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/usbMuxUart/output_com.c
mk20dx256vlh7 working!
[kiibohd-controller.git] / Output / usbMuxUart / output_com.c
1 /* Copyright (C) 2014-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 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
36 #include <arm/uart_serial.h>
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_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 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" );
83
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
93 };
94
95
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
101
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
105
106 // System Control and Consumer Control 1KRO containers
107         uint8_t  USBKeys_SysCtrl;
108         uint16_t USBKeys_ConsCtrl;
109
110 // The number of keys sent to the usb in the array
111         uint8_t  USBKeys_Sent    = 0;
112         uint8_t  USBKeys_SentCLI = 0;
113
114 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
115 volatile uint8_t  USBKeys_LEDs = 0;
116
117 // Protocol setting from the host.
118 // 0 - Boot Mode
119 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
120 volatile uint8_t  USBKeys_Protocol = 0;
121
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;
125
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;
129
130 // count until idle timeout
131         uint8_t  USBKeys_Idle_Count = 0;
132
133 // Indicates whether the Output module is fully functional
134 // 0 - Not fully functional, 1 - Fully functional
135 // 0 is often used to show that a USB cable is not plugged in (but has power)
136         uint8_t  Output_Available = 0;
137
138 // Debug control variable for Output modules
139 // 0 - Debug disabled (default)
140 // 1 - Debug enabled
141          uint8_t  Output_DebugMode = 0;
142
143
144
145 // ----- Capabilities -----
146
147 // Set Boot Keyboard Protocol
148 void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
149 {
150         // Display capability name
151         if ( stateType == 0xFF && state == 0xFF )
152         {
153                 print("Output_kbdProtocolBoot()");
154                 return;
155         }
156
157         // Only set if necessary
158         if ( USBKeys_Protocol == 0 )
159                 return;
160
161         // TODO Analog inputs
162         // Only set on key press
163         if ( stateType != 0x01 )
164                 return;
165
166         // Flush the key buffers
167         Output_flushBuffers();
168
169         // Set the keyboard protocol to Boot Mode
170         USBKeys_Protocol = 0;
171 }
172
173
174 // Set NKRO Keyboard Protocol
175 void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
176 {
177         // Display capability name
178         if ( stateType == 0xFF && state == 0xFF )
179         {
180                 print("Output_kbdProtocolNKRO()");
181                 return;
182         }
183
184         // Only set if necessary
185         if ( USBKeys_Protocol == 1 )
186                 return;
187
188         // TODO Analog inputs
189         // Only set on key press
190         if ( stateType != 0x01 )
191                 return;
192
193         // Flush the key buffers
194         Output_flushBuffers();
195
196         // Set the keyboard protocol to NKRO Mode
197         USBKeys_Protocol = 1;
198 }
199
200
201 // Sends a Consumer Control code to the USB Output buffer
202 void Output_consCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
203 {
204         // Display capability name
205         if ( stateType == 0xFF && state == 0xFF )
206         {
207                 print("Output_consCtrlSend(consCode)");
208                 return;
209         }
210
211         // Not implemented in Boot Mode
212         if ( USBKeys_Protocol == 0 )
213         {
214                 warn_print("Consumer Control is not implemented for Boot Mode");
215                 return;
216         }
217
218         // TODO Analog inputs
219         // Only indicate USB has changed if either a press or release has occured
220         if ( state == 0x01 || state == 0x03 )
221                 USBKeys_Changed |= USBKeyChangeState_Consumer;
222
223         // Only send keypresses if press or hold state
224         if ( stateType == 0x00 && state == 0x03 ) // Release state
225                 return;
226
227         // Set consumer control code
228         USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
229 }
230
231
232 // Ignores the given key status update
233 // Used to prevent fall-through, this is the None keyword in KLL
234 void Output_noneSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
235 {
236         // Display capability name
237         if ( stateType == 0xFF && state == 0xFF )
238         {
239                 print("Output_noneSend()");
240                 return;
241         }
242
243         // Nothing to do, because that's the point :P
244 }
245
246
247 // Sends a System Control code to the USB Output buffer
248 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
249 {
250         // Display capability name
251         if ( stateType == 0xFF && state == 0xFF )
252         {
253                 print("Output_sysCtrlSend(sysCode)");
254                 return;
255         }
256
257         // Not implemented in Boot Mode
258         if ( USBKeys_Protocol == 0 )
259         {
260                 warn_print("System Control is not implemented for Boot Mode");
261                 return;
262         }
263
264         // TODO Analog inputs
265         // Only indicate USB has changed if either a press or release has occured
266         if ( state == 0x01 || state == 0x03 )
267                 USBKeys_Changed |= USBKeyChangeState_System;
268
269         // Only send keypresses if press or hold state
270         if ( stateType == 0x00 && state == 0x03 ) // Release state
271                 return;
272
273         // Set system control code
274         USBKeys_SysCtrl = args[0];
275 }
276
277
278 // Adds a single USB Code to the USB Output buffer
279 // Argument #1: USB Code
280 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
281 {
282         // Display capability name
283         if ( stateType == 0xFF && state == 0xFF )
284         {
285                 print("Output_usbCodeSend(usbCode)");
286                 return;
287         }
288
289         // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
290         uint8_t keyPress = 0; // Default to key release, only used for NKRO
291         switch ( USBKeys_Protocol )
292         {
293         case 0: // Boot Mode
294                 // TODO Analog inputs
295                 // Only indicate USB has changed if either a press or release has occured
296                 if ( state == 0x01 || state == 0x03 )
297                         USBKeys_Changed = USBKeyChangeState_MainKeys;
298
299                 // Only send keypresses if press or hold state
300                 if ( stateType == 0x00 && state == 0x03 ) // Release state
301                         return;
302                 break;
303         case 1: // NKRO Mode
304                 // Only send press and release events
305                 if ( stateType == 0x00 && state == 0x02 ) // Hold state
306                         return;
307
308                 // Determine if setting or unsetting the bitfield (press == set)
309                 if ( stateType == 0x00 && state == 0x01 ) // Press state
310                         keyPress = 1;
311                 break;
312         }
313
314         // Get the keycode from arguments
315         uint8_t key = args[0];
316
317         // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
318         // Boot mode - Maximum of 6 byte codes
319         // NKRO mode - Each bit of the 26 byte corresponds to a key
320         //  Bits   0 - 160 (first 20 bytes) correspond to USB Codes 4   - 164
321         //  Bits 161 - 205 (last 6 bytes)   correspond to USB Codes 176 - 221
322         //  Bits 206 - 208 (last byte)      correspond to the 3 padded bits in USB (unused)
323         uint8_t bytePosition = 0;
324         uint8_t byteShift = 0;
325         switch ( USBKeys_Protocol )
326         {
327         case 0: // Boot Mode
328                 // Set the modifier bit if this key is a modifier
329                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
330                 {
331                         USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
332                 }
333                 // Normal USB Code
334                 else
335                 {
336                         // USB Key limit reached
337                         if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
338                         {
339                                 warn_print("USB Key limit reached");
340                                 return;
341                         }
342
343                         // Make sure key is within the USB HID range
344                         if ( key <= 104 )
345                         {
346                                 USBKeys_Keys[USBKeys_Sent++] = key;
347                         }
348                         // Invalid key
349                         else
350                         {
351                                 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
352                                 printHex( key );
353                                 print( NL );
354                         }
355                 }
356                 break;
357
358         case 1: // NKRO Mode
359                 // Set the modifier bit if this key is a modifier
360                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
361                 {
362                         if ( keyPress )
363                         {
364                                 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
365                         }
366                         else // Release
367                         {
368                                 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
369                         }
370
371                         USBKeys_Changed |= USBKeyChangeState_Modifiers;
372                         break;
373                 }
374                 // First 20 bytes
375                 else if ( key >= 4 && key <= 164 )
376                 {
377                         // Lookup (otherwise division or multiple checks are needed to do alignment)
378                         uint8_t keyPos = key - 4; // Starting position in array
379                         switch ( keyPos )
380                         {
381                                 byteLookup( 0 );
382                                 byteLookup( 1 );
383                                 byteLookup( 2 );
384                                 byteLookup( 3 );
385                                 byteLookup( 4 );
386                                 byteLookup( 5 );
387                                 byteLookup( 6 );
388                                 byteLookup( 7 );
389                                 byteLookup( 8 );
390                                 byteLookup( 9 );
391                                 byteLookup( 10 );
392                                 byteLookup( 11 );
393                                 byteLookup( 12 );
394                                 byteLookup( 13 );
395                                 byteLookup( 14 );
396                                 byteLookup( 15 );
397                                 byteLookup( 16 );
398                                 byteLookup( 17 );
399                                 byteLookup( 18 );
400                                 byteLookup( 19 );
401                         }
402
403                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
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 - 176; // Starting position in array
410                         switch ( keyPos )
411                         {
412                                 byteLookup( 20 );
413                                 byteLookup( 21 );
414                                 byteLookup( 22 );
415                                 byteLookup( 23 );
416                                 byteLookup( 24 );
417                                 byteLookup( 25 );
418                         }
419
420                         USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
421                 }
422                 // Invalid key
423                 else
424                 {
425                         warn_msg("USB Code not within 4-164 (0x4-0xA4) or 176-221 (0xB0-0xDD) NKRO Mode: ");
426                         printHex( key );
427                         print( NL );
428                         break;
429                 }
430
431                 // Set/Unset
432                 if ( keyPress )
433                 {
434                         USBKeys_Keys[bytePosition] |= (1 << byteShift);
435                         USBKeys_Sent++;
436                 }
437                 else // Release
438                 {
439                         USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
440                         USBKeys_Sent++;
441                 }
442
443                 break;
444         }
445 }
446
447
448
449 // ----- Functions -----
450
451 // Flush Key buffers
452 void Output_flushBuffers()
453 {
454         // Zero out USBKeys_Keys array
455         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
456                 USBKeys_Keys[ c ] = 0;
457
458         // Zero out other key buffers
459         USBKeys_ConsCtrl = 0;
460         USBKeys_Modifiers = 0;
461         USBKeys_SysCtrl = 0;
462 }
463
464
465 // USB Module Setup
466 inline void Output_setup()
467 {
468         // Setup UART
469         uart_serial_setup();
470         print("\033[2J"); // Clear screen
471
472         // Initialize the USB, and then wait for the host to set configuration.
473         // This will hang forever if USB does not initialize
474         usb_init();
475
476         while ( !usb_configured() );
477
478         // Register USB Output CLI dictionary
479         CLI_registerDictionary( outputCLIDict, outputCLIDictName );
480
481         // Zero out USBKeys_Keys array
482         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
483                 USBKeys_Keys[ c ] = 0;
484 }
485
486
487 // USB Data Send
488 inline void Output_send()
489 {
490         // Boot Mode Only, unset stale keys
491         if ( USBKeys_Protocol == 0 )
492                 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
493                         USBKeys_Keys[c] = 0;
494
495         // Send keypresses while there are pending changes
496         while ( USBKeys_Changed )
497                 usb_keyboard_send();
498
499         // Clear modifiers and keys
500         USBKeys_Modifiers = 0;
501         USBKeys_Sent      = 0;
502
503         // Signal Scan Module we are finished
504         switch ( USBKeys_Protocol )
505         {
506         case 0: // Boot Mode
507                 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
508                 break;
509         case 1: // NKRO Mode
510                 Scan_finishedWithOutput( USBKeys_Sent );
511                 break;
512         }
513 }
514
515
516 // Sets the device into firmware reload mode
517 inline void Output_firmwareReload()
518 {
519         uart_device_reload();
520 }
521
522
523 // USB Input buffer available
524 inline unsigned int Output_availablechar()
525 {
526         return usb_serial_available() + uart_serial_available();
527 }
528
529
530 // USB Get Character from input buffer
531 inline int Output_getchar()
532 {
533         // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
534         if ( usb_serial_available() > 0 )
535         {
536                 return (int)usb_serial_getchar();
537         }
538
539         if ( uart_serial_available() > 0 )
540         {
541                 return (int)uart_serial_getchar();
542         }
543
544         return -1;
545 }
546
547
548 // USB Send Character to output buffer
549 inline int Output_putchar( char c )
550 {
551         // First send to UART
552         uart_serial_putchar( c );
553
554         // Then send to USB
555         return usb_serial_putchar( c );
556 }
557
558
559 // USB Send String to output buffer, null terminated
560 inline int Output_putstr( char* str )
561 {
562 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
563         uint16_t count = 0;
564 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
565         uint32_t count = 0;
566 #endif
567         // Count characters until NULL character, then send the amount counted
568         while ( str[count] != '\0' )
569                 count++;
570
571         // First send to UART
572         uart_serial_write( str, count );
573
574         // Then send to USB
575         return usb_serial_write( str, count );
576 }
577
578
579 // Soft Chip Reset
580 inline void Output_softReset()
581 {
582         usb_device_software_reset();
583 }
584
585
586 // ----- CLI Command Functions -----
587
588 void cliFunc_kbdProtocol( char* args )
589 {
590         print( NL );
591         info_msg("Keyboard Protocol: ");
592         printInt8( USBKeys_Protocol );
593 }
594
595
596 void cliFunc_readLEDs( char* args )
597 {
598         print( NL );
599         info_msg("LED State: ");
600         printInt8( USBKeys_LEDs );
601 }
602
603
604 void cliFunc_readUART( char* args )
605 {
606         print( NL );
607
608         // Read UART buffer until empty
609         while ( uart_serial_available() > 0 )
610         {
611                 char out[] = { (char)uart_serial_getchar(), '\0' };
612                 dPrint( out );
613         }
614 }
615
616
617 void cliFunc_sendKeys( char* args )
618 {
619         // Copy USBKeys_KeysCLI to USBKeys_Keys
620         for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
621         {
622                 // TODO
623                 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
624         }
625         USBKeys_Sent = USBKeys_SentCLI;
626
627         // Set modifier byte
628         USBKeys_Modifiers = USBKeys_ModifiersCLI;
629 }
630
631
632 void cliFunc_sendUART( char* args )
633 {
634         // Write all args to UART
635         uart_serial_write( args, lenStr( args ) );
636 }
637
638
639 void cliFunc_setKeys( char* args )
640 {
641         char* curArgs;
642         char* arg1Ptr;
643         char* arg2Ptr = args;
644
645         // Parse up to USBKeys_MaxSize args (whichever is least)
646         for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
647         {
648                 curArgs = arg2Ptr;
649                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
650
651                 // Stop processing args if no more are found
652                 if ( *arg1Ptr == '\0' )
653                         break;
654
655                 // Add the USB code to be sent
656                 // TODO
657                 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
658         }
659 }
660
661
662 void cliFunc_setMod( char* args )
663 {
664         // Parse number from argument
665         //  NOTE: Only first argument is used
666         char* arg1Ptr;
667         char* arg2Ptr;
668         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
669
670         USBKeys_ModifiersCLI = numToInt( arg1Ptr );
671 }
672