]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/usbMuxUart/output_com.c
Fixing compiler errors for usbMuxUart Output module
[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 // Sends a System Control code to the USB Output buffer
233 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
234 {
235         // Display capability name
236         if ( stateType == 0xFF && state == 0xFF )
237         {
238                 print("Output_sysCtrlSend(sysCode)");
239                 return;
240         }
241
242         // Not implemented in Boot Mode
243         if ( USBKeys_Protocol == 0 )
244         {
245                 warn_print("System Control is not implemented for Boot Mode");
246                 return;
247         }
248
249         // TODO Analog inputs
250         // Only indicate USB has changed if either a press or release has occured
251         if ( state == 0x01 || state == 0x03 )
252                 USBKeys_Changed |= USBKeyChangeState_System;
253
254         // Only send keypresses if press or hold state
255         if ( stateType == 0x00 && state == 0x03 ) // Release state
256                 return;
257
258         // Set system control code
259         USBKeys_SysCtrl = args[0];
260 }
261
262
263 // Adds a single USB Code to the USB Output buffer
264 // Argument #1: USB Code
265 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
266 {
267         // Display capability name
268         if ( stateType == 0xFF && state == 0xFF )
269         {
270                 print("Output_usbCodeSend(usbCode)");
271                 return;
272         }
273
274         // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
275         uint8_t keyPress = 0; // Default to key release, only used for NKRO
276         switch ( USBKeys_Protocol )
277         {
278         case 0: // Boot Mode
279                 // TODO Analog inputs
280                 // Only indicate USB has changed if either a press or release has occured
281                 if ( state == 0x01 || state == 0x03 )
282                         USBKeys_Changed = USBKeyChangeState_MainKeys;
283
284                 // Only send keypresses if press or hold state
285                 if ( stateType == 0x00 && state == 0x03 ) // Release state
286                         return;
287                 break;
288         case 1: // NKRO Mode
289                 // Only send press and release events
290                 if ( stateType == 0x00 && state == 0x02 ) // Hold state
291                         return;
292
293                 // Determine if setting or unsetting the bitfield (press == set)
294                 if ( stateType == 0x00 && state == 0x01 ) // Press state
295                         keyPress = 1;
296                 break;
297         }
298
299         // Get the keycode from arguments
300         uint8_t key = args[0];
301
302         // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
303         // Boot mode - Maximum of 6 byte codes
304         // NKRO mode - Each bit of the 26 byte corresponds to a key
305         //  Bits   0 - 160 (first 20 bytes) correspond to USB Codes 4   - 164
306         //  Bits 161 - 205 (last 6 bytes)   correspond to USB Codes 176 - 221
307         //  Bits 206 - 208 (last byte)      correspond to the 3 padded bits in USB (unused)
308         uint8_t bytePosition = 0;
309         uint8_t byteShift = 0;
310         switch ( USBKeys_Protocol )
311         {
312         case 0: // Boot Mode
313                 // Set the modifier bit if this key is a modifier
314                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
315                 {
316                         USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
317                 }
318                 // Normal USB Code
319                 else
320                 {
321                         // USB Key limit reached
322                         if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
323                         {
324                                 warn_print("USB Key limit reached");
325                                 return;
326                         }
327
328                         // Make sure key is within the USB HID range
329                         if ( key <= 104 )
330                         {
331                                 USBKeys_Keys[USBKeys_Sent++] = key;
332                         }
333                         // Invalid key
334                         else
335                         {
336                                 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
337                                 printHex( key );
338                                 print( NL );
339                         }
340                 }
341                 break;
342
343         case 1: // NKRO Mode
344                 // Set the modifier bit if this key is a modifier
345                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
346                 {
347                         if ( keyPress )
348                         {
349                                 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
350                         }
351                         else // Release
352                         {
353                                 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
354                         }
355
356                         USBKeys_Changed |= USBKeyChangeState_Modifiers;
357                         break;
358                 }
359                 // First 20 bytes
360                 else if ( key >= 4 && key <= 164 )
361                 {
362                         // Lookup (otherwise division or multiple checks are needed to do alignment)
363                         uint8_t keyPos = key - 4; // Starting position in array
364                         switch ( keyPos )
365                         {
366                                 byteLookup( 0 );
367                                 byteLookup( 1 );
368                                 byteLookup( 2 );
369                                 byteLookup( 3 );
370                                 byteLookup( 4 );
371                                 byteLookup( 5 );
372                                 byteLookup( 6 );
373                                 byteLookup( 7 );
374                                 byteLookup( 8 );
375                                 byteLookup( 9 );
376                                 byteLookup( 10 );
377                                 byteLookup( 11 );
378                                 byteLookup( 12 );
379                                 byteLookup( 13 );
380                                 byteLookup( 14 );
381                                 byteLookup( 15 );
382                                 byteLookup( 16 );
383                                 byteLookup( 17 );
384                                 byteLookup( 18 );
385                                 byteLookup( 19 );
386                         }
387
388                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
389                 }
390                 // Last 6 bytes
391                 else if ( key >= 176 && key <= 221 )
392                 {
393                         // Lookup (otherwise division or multiple checks are needed to do alignment)
394                         uint8_t keyPos = key - 176; // Starting position in array
395                         switch ( keyPos )
396                         {
397                                 byteLookup( 20 );
398                                 byteLookup( 21 );
399                                 byteLookup( 22 );
400                                 byteLookup( 23 );
401                                 byteLookup( 24 );
402                                 byteLookup( 25 );
403                         }
404
405                         USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
406                 }
407                 // Invalid key
408                 else
409                 {
410                         warn_msg("USB Code not within 4-164 (0x4-0xA4) or 176-221 (0xB0-0xDD) NKRO Mode: ");
411                         printHex( key );
412                         print( NL );
413                         break;
414                 }
415
416                 // Set/Unset
417                 if ( keyPress )
418                 {
419                         USBKeys_Keys[bytePosition] |= (1 << byteShift);
420                         USBKeys_Sent++;
421                 }
422                 else // Release
423                 {
424                         USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
425                         USBKeys_Sent++;
426                 }
427
428                 break;
429         }
430 }
431
432
433
434 // ----- Functions -----
435
436 // Flush Key buffers
437 void Output_flushBuffers()
438 {
439         // Zero out USBKeys_Keys array
440         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
441                 USBKeys_Keys[ c ] = 0;
442
443         // Zero out other key buffers
444         USBKeys_ConsCtrl = 0;
445         USBKeys_Modifiers = 0;
446         USBKeys_SysCtrl = 0;
447 }
448
449
450 // USB Module Setup
451 inline void Output_setup()
452 {
453         // Setup UART
454         uart_serial_setup();
455         print("\033[2J"); // Clear screen
456
457         // Initialize the USB, and then wait for the host to set configuration.
458         // This will hang forever if USB does not initialize
459         usb_init();
460
461         while ( !usb_configured() );
462
463         // Register USB Output CLI dictionary
464         CLI_registerDictionary( outputCLIDict, outputCLIDictName );
465
466         // Zero out USBKeys_Keys array
467         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
468                 USBKeys_Keys[ c ] = 0;
469 }
470
471
472 // USB Data Send
473 inline void Output_send()
474 {
475         // Boot Mode Only, unset stale keys
476         if ( USBKeys_Protocol == 0 )
477                 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
478                         USBKeys_Keys[c] = 0;
479
480         // Send keypresses while there are pending changes
481         while ( USBKeys_Changed )
482                 usb_keyboard_send();
483
484         // Clear modifiers and keys
485         USBKeys_Modifiers = 0;
486         USBKeys_Sent      = 0;
487
488         // Signal Scan Module we are finished
489         switch ( USBKeys_Protocol )
490         {
491         case 0: // Boot Mode
492                 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
493                 break;
494         case 1: // NKRO Mode
495                 Scan_finishedWithOutput( USBKeys_Sent );
496                 break;
497         }
498 }
499
500
501 // Sets the device into firmware reload mode
502 inline void Output_firmwareReload()
503 {
504         uart_device_reload();
505 }
506
507
508 // USB Input buffer available
509 inline unsigned int Output_availablechar()
510 {
511         return usb_serial_available() + uart_serial_available();
512 }
513
514
515 // USB Get Character from input buffer
516 inline int Output_getchar()
517 {
518         // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
519         if ( usb_serial_available() > 0 )
520         {
521                 return (int)usb_serial_getchar();
522         }
523
524         if ( uart_serial_available() > 0 )
525         {
526                 return (int)uart_serial_getchar();
527         }
528
529         return -1;
530 }
531
532
533 // USB Send Character to output buffer
534 inline int Output_putchar( char c )
535 {
536         // First send to UART
537         uart_serial_putchar( c );
538
539         // Then send to USB
540         return usb_serial_putchar( c );
541 }
542
543
544 // USB Send String to output buffer, null terminated
545 inline int Output_putstr( char* str )
546 {
547 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
548         uint16_t count = 0;
549 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
550         uint32_t count = 0;
551 #endif
552         // Count characters until NULL character, then send the amount counted
553         while ( str[count] != '\0' )
554                 count++;
555
556         // First send to UART
557         uart_serial_write( str, count );
558
559         // Then send to USB
560         return usb_serial_write( str, count );
561 }
562
563
564 // Soft Chip Reset
565 inline void Output_softReset()
566 {
567         usb_device_software_reset();
568 }
569
570
571 // ----- CLI Command Functions -----
572
573 void cliFunc_kbdProtocol( char* args )
574 {
575         print( NL );
576         info_msg("Keyboard Protocol: ");
577         printInt8( USBKeys_Protocol );
578 }
579
580
581 void cliFunc_readLEDs( char* args )
582 {
583         print( NL );
584         info_msg("LED State: ");
585         printInt8( USBKeys_LEDs );
586 }
587
588
589 void cliFunc_readUART( char* args )
590 {
591         print( NL );
592
593         // Read UART buffer until empty
594         while ( uart_serial_available() > 0 )
595         {
596                 char out[] = { (char)uart_serial_getchar(), '\0' };
597                 dPrint( out );
598         }
599 }
600
601
602 void cliFunc_sendKeys( char* args )
603 {
604         // Copy USBKeys_KeysCLI to USBKeys_Keys
605         for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
606         {
607                 // TODO
608                 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
609         }
610         USBKeys_Sent = USBKeys_SentCLI;
611
612         // Set modifier byte
613         USBKeys_Modifiers = USBKeys_ModifiersCLI;
614 }
615
616
617 void cliFunc_sendUART( char* args )
618 {
619         // Write all args to UART
620         uart_serial_write( args, lenStr( args ) );
621 }
622
623
624 void cliFunc_setKeys( char* args )
625 {
626         char* curArgs;
627         char* arg1Ptr;
628         char* arg2Ptr = args;
629
630         // Parse up to USBKeys_MaxSize args (whichever is least)
631         for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
632         {
633                 curArgs = arg2Ptr;
634                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
635
636                 // Stop processing args if no more are found
637                 if ( *arg1Ptr == '\0' )
638                         break;
639
640                 // Add the USB code to be sent
641                 // TODO
642                 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
643         }
644 }
645
646
647 void cliFunc_setMod( char* args )
648 {
649         // Parse number from argument
650         //  NOTE: Only first argument is used
651         char* arg1Ptr;
652         char* arg2Ptr;
653         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
654
655         USBKeys_ModifiersCLI = numToInt( arg1Ptr );
656 }
657