]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/usbMuxUart/output_com.c
Adding toggleKbdProtocol capability
[kiibohd-controller.git] / Output / usbMuxUart / output_com.c
1 /* Copyright (C) 2014-2016 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 // KLL
43 #include <kll_defs.h>
44
45 // Local Includes
46 #include "output_com.h"
47
48
49
50 // ----- Macros -----
51
52 // Used to build a bitmap lookup table from a byte addressable array
53 #define byteLookup( byte ) case (( byte ) * ( 8 )):         bytePosition = byte; byteShift = 0; break; \
54                            case (( byte ) * ( 8 ) + ( 1 )): bytePosition = byte; byteShift = 1; break; \
55                            case (( byte ) * ( 8 ) + ( 2 )): bytePosition = byte; byteShift = 2; break; \
56                            case (( byte ) * ( 8 ) + ( 3 )): bytePosition = byte; byteShift = 3; break; \
57                            case (( byte ) * ( 8 ) + ( 4 )): bytePosition = byte; byteShift = 4; break; \
58                            case (( byte ) * ( 8 ) + ( 5 )): bytePosition = byte; byteShift = 5; break; \
59                            case (( byte ) * ( 8 ) + ( 6 )): bytePosition = byte; byteShift = 6; break; \
60                            case (( byte ) * ( 8 ) + ( 7 )): bytePosition = byte; byteShift = 7; break
61
62
63
64 // ----- Function Declarations -----
65
66 void cliFunc_kbdProtocol( char* args );
67 void cliFunc_outputDebug( char* args );
68 void cliFunc_readLEDs   ( char* args );
69 void cliFunc_readUART   ( char* args );
70 void cliFunc_sendKeys   ( char* args );
71 void cliFunc_sendUART   ( char* args );
72 void cliFunc_setKeys    ( char* args );
73 void cliFunc_setMod     ( char* args );
74
75
76
77 // ----- Variables -----
78
79 // Output Module command dictionary
80 CLIDict_Entry( kbdProtocol, "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode" );
81 CLIDict_Entry( outputDebug, "Toggle Output Debug mode." );
82 CLIDict_Entry( readLEDs,    "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc." );
83 CLIDict_Entry( readUART,    "Read UART buffer until empty." );
84 CLIDict_Entry( sendKeys,    "Send the prepared list of USB codes and modifier byte." );
85 CLIDict_Entry( sendUART,    "Send characters over UART0." );
86 CLIDict_Entry( setKeys,     "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m." );
87 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" );
88
89 CLIDict_Def( outputCLIDict, "USB Module Commands" ) = {
90         CLIDict_Item( kbdProtocol ),
91         CLIDict_Item( outputDebug ),
92         CLIDict_Item( readLEDs ),
93         CLIDict_Item( readUART ),
94         CLIDict_Item( sendKeys ),
95         CLIDict_Item( sendUART ),
96         CLIDict_Item( setKeys ),
97         CLIDict_Item( setMod ),
98         { 0, 0, 0 } // Null entry for dictionary end
99 };
100
101
102 // Which modifier keys are currently pressed
103 // 1=left ctrl,    2=left shift,   4=left alt,    8=left gui
104 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
105 uint8_t  USBKeys_Modifiers    = 0;
106 uint8_t  USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
107
108 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
109 uint8_t  USBKeys_Keys   [USB_NKRO_BITFIELD_SIZE_KEYS];
110 uint8_t  USBKeys_KeysCLI[USB_NKRO_BITFIELD_SIZE_KEYS]; // Separate CLI send buffer
111
112 // System Control and Consumer Control 1KRO containers
113 uint8_t  USBKeys_SysCtrl;
114 uint16_t USBKeys_ConsCtrl;
115
116 // The number of keys sent to the usb in the array
117 uint8_t  USBKeys_Sent    = 0;
118 uint8_t  USBKeys_SentCLI = 0;
119
120 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
121 volatile uint8_t  USBKeys_LEDs = 0;
122
123 // Currently pressed mouse buttons, bitmask, 0 represents no buttons pressed
124 volatile uint16_t USBMouse_Buttons = 0;
125
126 // Relative mouse axis movement, stores pending movement
127 volatile uint16_t USBMouse_Relative_x = 0;
128 volatile uint16_t USBMouse_Relative_y = 0;
129
130 // Protocol setting from the host.
131 // 0 - Boot Mode
132 // 1 - NKRO Mode (Default, unless set by a BIOS or boot interface)
133 volatile uint8_t  USBKeys_Protocol = USBProtocol_define;
134
135 // Indicate if USB should send update
136 // OS only needs update if there has been a change in state
137 USBKeyChangeState USBKeys_Changed = USBKeyChangeState_None;
138
139 // Indicate if USB should send update
140 USBMouseChangeState USBMouse_Changed = 0;
141
142 // the idle configuration, how often we send the report to the
143 // host (ms * 4) even when it hasn't changed
144 uint8_t  USBKeys_Idle_Config = 125;
145
146 // count until idle timeout
147 uint8_t  USBKeys_Idle_Count = 0;
148
149 // Indicates whether the Output module is fully functional
150 // 0 - Not fully functional, 1 - Fully functional
151 // 0 is often used to show that a USB cable is not plugged in (but has power)
152 volatile uint8_t  Output_Available = 0;
153
154 // Debug control variable for Output modules
155 // 0 - Debug disabled (default)
156 // 1 - Debug enabled
157 uint8_t  Output_DebugMode = 0;
158
159 // mA - Set by outside module if not using USB (i.e. Interconnect)
160 // Generally set to 100 mA (low power) or 500 mA (high power)
161 uint16_t Output_ExtCurrent_Available = 0;
162
163 // mA - Set by USB module (if exists)
164 // Initially 100 mA, but may be negotiated higher (e.g. 500 mA)
165 uint16_t Output_USBCurrent_Available = 0;
166
167
168
169 // ----- Capabilities -----
170
171 // Set Boot Keyboard Protocol
172 void Output_kbdProtocolBoot_capability( uint8_t state, uint8_t stateType, uint8_t *args )
173 {
174         // Display capability name
175         if ( stateType == 0xFF && state == 0xFF )
176         {
177                 print("Output_kbdProtocolBoot()");
178                 return;
179         }
180
181         // Only set if necessary
182         if ( USBKeys_Protocol == 0 )
183                 return;
184
185         // TODO Analog inputs
186         // Only set on key press
187         if ( stateType != 0x01 )
188                 return;
189
190         // Flush the key buffers
191         Output_flushBuffers();
192
193         // Set the keyboard protocol to Boot Mode
194         USBKeys_Protocol = 0;
195 }
196
197
198 // Set NKRO Keyboard Protocol
199 void Output_kbdProtocolNKRO_capability( uint8_t state, uint8_t stateType, uint8_t *args )
200 {
201         // Display capability name
202         if ( stateType == 0xFF && state == 0xFF )
203         {
204                 print("Output_kbdProtocolNKRO()");
205                 return;
206         }
207
208         // Only set if necessary
209         if ( USBKeys_Protocol == 1 )
210                 return;
211
212         // TODO Analog inputs
213         // Only set on key press
214         if ( stateType != 0x01 )
215                 return;
216
217         // Flush the key buffers
218         Output_flushBuffers();
219
220         // Set the keyboard protocol to NKRO Mode
221         USBKeys_Protocol = 1;
222 }
223
224
225 // Toggle Keyboard Protocol
226 void Output_toggleKbdProtocol_capability( uint8_t state, uint8_t stateType, uint8_t *args )
227 {
228         // Display capability name
229         if ( stateType == 0xFF && state == 0xFF )
230         {
231                 print("Output_toggleKbdProtocol()");
232                 return;
233         }
234
235         // Only toggle protocol if release state
236         if ( stateType == 0x00 && state == 0x03 )
237         {
238                 // Flush the key buffers
239                 Output_flushBuffers();
240
241                 // Toggle the keyboard protocol Mode
242                 USBKeys_Protocol = !USBKeys_Protocol;
243         }
244 }
245
246
247 // Sends a Consumer Control code to the USB Output buffer
248 void Output_consCtrlSend_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_consCtrlSend(consCode)");
254                 return;
255         }
256
257         // Not implemented in Boot Mode
258         if ( USBKeys_Protocol == 0 )
259         {
260                 warn_print("Consumer 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_Consumer;
268
269         // Only send keypresses if press or hold state
270         if ( stateType == 0x00 && state == 0x03 ) // Release state
271         {
272                 USBKeys_ConsCtrl = 0;
273                 return;
274         }
275
276         // Set consumer control code
277         USBKeys_ConsCtrl = *(uint16_t*)(&args[0]);
278 }
279
280
281 // Ignores the given key status update
282 // Used to prevent fall-through, this is the None keyword in KLL
283 void Output_noneSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
284 {
285         // Display capability name
286         if ( stateType == 0xFF && state == 0xFF )
287         {
288                 print("Output_noneSend()");
289                 return;
290         }
291
292         // Nothing to do, because that's the point :P
293 }
294
295
296 // Sends a System Control code to the USB Output buffer
297 void Output_sysCtrlSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
298 {
299         // Display capability name
300         if ( stateType == 0xFF && state == 0xFF )
301         {
302                 print("Output_sysCtrlSend(sysCode)");
303                 return;
304         }
305
306         // Not implemented in Boot Mode
307         if ( USBKeys_Protocol == 0 )
308         {
309                 warn_print("System Control is not implemented for Boot Mode");
310                 return;
311         }
312
313         // TODO Analog inputs
314         // Only indicate USB has changed if either a press or release has occured
315         if ( state == 0x01 || state == 0x03 )
316                 USBKeys_Changed |= USBKeyChangeState_System;
317
318         // Only send keypresses if press or hold state
319         if ( stateType == 0x00 && state == 0x03 ) // Release state
320         {
321                 USBKeys_SysCtrl = 0;
322                 return;
323         }
324
325         // Set system control code
326         USBKeys_SysCtrl = args[0];
327 }
328
329
330 // Adds a single USB Code to the USB Output buffer
331 // Argument #1: USB Code
332 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
333 {
334         // Display capability name
335         if ( stateType == 0xFF && state == 0xFF )
336         {
337                 print("Output_usbCodeSend(usbCode)");
338                 return;
339         }
340
341         // Depending on which mode the keyboard is in the USB needs Press/Hold/Release events
342         uint8_t keyPress = 0; // Default to key release, only used for NKRO
343         switch ( USBKeys_Protocol )
344         {
345         case 0: // Boot Mode
346                 // TODO Analog inputs
347                 // Only indicate USB has changed if either a press or release has occured
348                 if ( state == 0x01 || state == 0x03 )
349                         USBKeys_Changed = USBKeyChangeState_MainKeys;
350
351                 // Only send keypresses if press or hold state
352                 if ( stateType == 0x00 && state == 0x03 ) // Release state
353                         return;
354                 break;
355         case 1: // NKRO Mode
356                 // Only send press and release events
357                 if ( stateType == 0x00 && state == 0x02 ) // Hold state
358                         return;
359
360                 // Determine if setting or unsetting the bitfield (press == set)
361                 if ( stateType == 0x00 && state == 0x01 ) // Press state
362                         keyPress = 1;
363                 break;
364         }
365
366         // Get the keycode from arguments
367         uint8_t key = args[0];
368
369         // Depending on which mode the keyboard is in, USBKeys_Keys array is used differently
370         // Boot mode - Maximum of 6 byte codes
371         // NKRO mode - Each bit of the 26 byte corresponds to a key
372         //  Bits   0 -  45 (bytes  0 -  5) correspond to USB Codes   4 -  49 (Main)
373         //  Bits  48 - 161 (bytes  6 - 20) correspond to USB Codes  51 - 164 (Secondary)
374         //  Bits 168 - 213 (bytes 21 - 26) correspond to USB Codes 176 - 221 (Tertiary)
375         //  Bits 214 - 216                 unused
376         uint8_t bytePosition = 0;
377         uint8_t byteShift = 0;
378         switch ( USBKeys_Protocol )
379         {
380         case 0: // Boot Mode
381                 // Set the modifier bit if this key is a modifier
382                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
383                 {
384                         USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
385                 }
386                 // Normal USB Code
387                 else
388                 {
389                         // USB Key limit reached
390                         if ( USBKeys_Sent >= USB_BOOT_MAX_KEYS )
391                         {
392                                 warn_print("USB Key limit reached");
393                                 return;
394                         }
395
396                         // Make sure key is within the USB HID range
397                         if ( key <= 104 )
398                         {
399                                 USBKeys_Keys[USBKeys_Sent++] = key;
400                         }
401                         // Invalid key
402                         else
403                         {
404                                 warn_msg("USB Code above 104/0x68 in Boot Mode: ");
405                                 printHex( key );
406                                 print( NL );
407                         }
408                 }
409                 break;
410
411         case 1: // NKRO Mode
412                 // Set the modifier bit if this key is a modifier
413                 if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
414                 {
415                         if ( keyPress )
416                         {
417                                 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
418                         }
419                         else // Release
420                         {
421                                 USBKeys_Modifiers &= ~(1 << (key ^ 0xE0)); // Left shift 1 by key XOR 0xE0
422                         }
423
424                         USBKeys_Changed |= USBKeyChangeState_Modifiers;
425                         break;
426                 }
427                 // First 6 bytes
428                 else if ( key >= 4 && key <= 49 )
429                 {
430                         // Lookup (otherwise division or multiple checks are needed to do alignment)
431                         // Starting at 0th position, each byte has 8 bits, starting at 4th bit
432                         uint8_t keyPos = key + (0 * 8 - 4); // Starting position in array, Ignoring 4 keys
433                         switch ( keyPos )
434                         {
435                                 byteLookup( 0 );
436                                 byteLookup( 1 );
437                                 byteLookup( 2 );
438                                 byteLookup( 3 );
439                                 byteLookup( 4 );
440                                 byteLookup( 5 );
441                         }
442
443                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
444                 }
445                 // Next 14 bytes
446                 else if ( key >= 51 && key <= 155 )
447                 {
448                         // Lookup (otherwise division or multiple checks are needed to do alignment)
449                         // Starting at 6th byte position, each byte has 8 bits, starting at 51st bit
450                         uint8_t keyPos = key + (6 * 8 - 51); // Starting position in array
451                         switch ( keyPos )
452                         {
453                                 byteLookup( 6 );
454                                 byteLookup( 7 );
455                                 byteLookup( 8 );
456                                 byteLookup( 9 );
457                                 byteLookup( 10 );
458                                 byteLookup( 11 );
459                                 byteLookup( 12 );
460                                 byteLookup( 13 );
461                                 byteLookup( 14 );
462                                 byteLookup( 15 );
463                                 byteLookup( 16 );
464                                 byteLookup( 17 );
465                                 byteLookup( 18 );
466                                 byteLookup( 19 );
467                         }
468
469                         USBKeys_Changed |= USBKeyChangeState_SecondaryKeys;
470                 }
471                 // Next byte
472                 else if ( key >= 157 && key <= 164 )
473                 {
474                         // Lookup (otherwise division or multiple checks are needed to do alignment)
475                         uint8_t keyPos = key + (20 * 8 - 157); // Starting position in array, Ignoring 6 keys
476                         switch ( keyPos )
477                         {
478                                 byteLookup( 20 );
479                         }
480
481                         USBKeys_Changed |= USBKeyChangeState_TertiaryKeys;
482                 }
483                 // Last 6 bytes
484                 else if ( key >= 176 && key <= 221 )
485                 {
486                         // Lookup (otherwise division or multiple checks are needed to do alignment)
487                         uint8_t keyPos = key + (21 * 8 - 176); // Starting position in array
488                         switch ( keyPos )
489                         {
490                                 byteLookup( 21 );
491                                 byteLookup( 22 );
492                                 byteLookup( 23 );
493                                 byteLookup( 24 );
494                                 byteLookup( 25 );
495                                 byteLookup( 26 );
496                         }
497
498                         USBKeys_Changed |= USBKeyChangeState_QuartiaryKeys;
499                 }
500                 // Received 0x00
501                 // This is a special USB Code that internally indicates a "break"
502                 // It is used to send "nothing" in order to break up sequences of USB Codes
503                 else if ( key == 0x00 )
504                 {
505                         USBKeys_Changed |= USBKeyChangeState_MainKeys;
506
507                         // Also flush out buffers just in case
508                         Output_flushBuffers();
509                         break;
510                 }
511                 // Invalid key
512                 else
513                 {
514                         warn_msg("USB Code not within 4-49 (0x4-0x31), 51-155 (0x33-0x9B), 157-164 (0x9D-0xA4), 176-221 (0xB0-0xDD) or 224-231 (0xE0-0xE7) NKRO Mode: ");
515                         printHex( key );
516                         print( NL );
517                         break;
518                 }
519
520                 // Set/Unset
521                 if ( keyPress )
522                 {
523                         USBKeys_Keys[bytePosition] |= (1 << byteShift);
524                         USBKeys_Sent++;
525                 }
526                 else // Release
527                 {
528                         USBKeys_Keys[bytePosition] &= ~(1 << byteShift);
529                         USBKeys_Sent++;
530                 }
531
532                 break;
533         }
534 }
535
536 void Output_flashMode_capability( uint8_t state, uint8_t stateType, uint8_t *args )
537 {
538         // Display capability name
539         if ( stateType == 0xFF && state == 0xFF )
540         {
541                 print("Output_flashMode()");
542                 return;
543         }
544
545         // Start flash mode
546         Output_firmwareReload();
547 }
548
549 // Sends a mouse command over the USB Output buffer
550 // XXX This function *will* be changing in the future
551 //     If you use it, be prepared that your .kll files will break in the future (post KLL 0.5)
552 // Argument #1: USB Mouse Button (16 bit)
553 // Argument #2: USB X Axis (16 bit) relative
554 // Argument #3: USB Y Axis (16 bit) relative
555 void Output_usbMouse_capability( uint8_t state, uint8_t stateType, uint8_t *args )
556 {
557         // Display capability name
558         if ( stateType == 0xFF && state == 0xFF )
559         {
560                 print("Output_usbMouse(mouseButton,relX,relY)");
561                 return;
562         }
563
564         // Determine which mouse button was sent
565         // The USB spec defines up to a max of 0xFFFF buttons
566         // The usual are:
567         // 1 - Button 1 - (Primary)
568         // 2 - Button 2 - (Secondary)
569         // 3 - Button 3 - (Tertiary)
570         uint16_t mouse_button = *(uint16_t*)(&args[0]);
571
572         // X/Y Relative Axis
573         uint16_t mouse_x = *(uint16_t*)(&args[2]);
574         uint16_t mouse_y = *(uint16_t*)(&args[4]);
575
576         // Adjust for bit shift
577         uint16_t mouse_button_shift = mouse_button - 1;
578
579         // Only send mouse button if in press or hold state
580         if ( stateType == 0x00 && state == 0x03 ) // Release state
581         {
582                 // Release
583                 if ( mouse_button )
584                         USBMouse_Buttons &= ~(1 << mouse_button_shift);
585         }
586         else
587         {
588                 // Press or hold
589                 if ( mouse_button )
590                         USBMouse_Buttons |= (1 << mouse_button_shift);
591
592                 if ( mouse_x )
593                         USBMouse_Relative_x = mouse_x;
594                 if ( mouse_y )
595                         USBMouse_Relative_y = mouse_y;
596         }
597
598         // Trigger updates
599         if ( mouse_button )
600                 USBMouse_Changed |= USBMouseChangeState_Buttons;
601
602         if ( mouse_x || mouse_y )
603                 USBMouse_Changed |= USBMouseChangeState_Relative;
604 }
605
606
607
608 // ----- Functions -----
609
610 // Flush Key buffers
611 void Output_flushBuffers()
612 {
613         // Zero out USBKeys_Keys array
614         for ( uint8_t c = 0; c < USB_NKRO_BITFIELD_SIZE_KEYS; c++ )
615                 USBKeys_Keys[ c ] = 0;
616
617         // Zero out other key buffers
618         USBKeys_ConsCtrl = 0;
619         USBKeys_Modifiers = 0;
620         USBKeys_SysCtrl = 0;
621 }
622
623
624 // USB Module Setup
625 inline void Output_setup()
626 {
627         // Setup UART
628         uart_serial_setup();
629
630         // Initialize the USB
631         // If a USB connection does not exist, just ignore it
632         // All usb related functions will non-fatally fail if called
633         // If the USB initialization is delayed, then functionality will just be delayed
634         usb_init();
635
636         // Register USB Output CLI dictionary
637         CLI_registerDictionary( outputCLIDict, outputCLIDictName );
638
639         // Flush key buffers
640         Output_flushBuffers();
641 }
642
643
644 // USB Data Send
645 inline void Output_send()
646 {
647         // USB status checks
648         // Non-standard USB state manipulation, usually does nothing
649         usb_device_check();
650
651         // Boot Mode Only, unset stale keys
652         if ( USBKeys_Protocol == 0 )
653                 for ( uint8_t c = USBKeys_Sent; c < USB_BOOT_MAX_KEYS; c++ )
654                         USBKeys_Keys[c] = 0;
655
656         // Send keypresses while there are pending changes
657         while ( USBKeys_Changed )
658                 usb_keyboard_send();
659
660         // Clear keys sent
661         USBKeys_Sent = 0;
662
663         // Signal Scan Module we are finished
664         switch ( USBKeys_Protocol )
665         {
666         case 0: // Boot Mode
667                 // Clear modifiers only in boot mode
668                 USBKeys_Modifiers = 0;
669                 Scan_finishedWithOutput( USBKeys_Sent <= USB_BOOT_MAX_KEYS ? USBKeys_Sent : USB_BOOT_MAX_KEYS );
670                 break;
671         case 1: // NKRO Mode
672                 Scan_finishedWithOutput( USBKeys_Sent );
673                 break;
674         }
675 }
676
677
678 // Sets the device into firmware reload mode
679 void Output_firmwareReload()
680 {
681         usb_device_reload();
682 }
683
684
685 // USB Input buffer available
686 inline unsigned int Output_availablechar()
687 {
688         return usb_serial_available() + uart_serial_available();
689 }
690
691
692 // USB Get Character from input buffer
693 inline int Output_getchar()
694 {
695         // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
696         if ( usb_serial_available() > 0 )
697         {
698                 return (int)usb_serial_getchar();
699         }
700
701         if ( uart_serial_available() > 0 )
702         {
703                 return (int)uart_serial_getchar();
704         }
705
706         return -1;
707 }
708
709
710 // USB Send Character to output buffer
711 inline int Output_putchar( char c )
712 {
713         // First send to UART
714         uart_serial_putchar( c );
715
716         // Then send to USB
717         return usb_serial_putchar( c );
718 }
719
720
721 // USB Send String to output buffer, null terminated
722 inline int Output_putstr( char* str )
723 {
724 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
725         uint16_t count = 0;
726 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_) // ARM
727         uint32_t count = 0;
728 #endif
729         // Count characters until NULL character, then send the amount counted
730         while ( str[count] != '\0' )
731                 count++;
732
733         // First send to UART
734         uart_serial_write( str, count );
735
736         // Then send to USB
737         return usb_serial_write( str, count );
738 }
739
740
741 // Soft Chip Reset
742 inline void Output_softReset()
743 {
744         usb_device_software_reset();
745 }
746
747
748 // Update USB current (mA)
749 // Triggers power change event
750 void Output_update_usb_current( unsigned int current )
751 {
752         // Only signal if changed
753         if ( current == Output_USBCurrent_Available )
754                 return;
755
756         // Update USB current
757         Output_USBCurrent_Available = current;
758
759         /* XXX Affects sleep states due to USB messages
760         unsigned int total_current = Output_current_available();
761         info_msg("USB Available Current Changed. Total Available: ");
762         printInt32( total_current );
763         print(" mA" NL);
764         */
765
766         // Send new total current to the Scan Modules
767         Scan_currentChange( Output_current_available() );
768 }
769
770
771 // Update external current (mA)
772 // Triggers power change event
773 void Output_update_external_current( unsigned int current )
774 {
775         // Only signal if changed
776         if ( current == Output_ExtCurrent_Available )
777                 return;
778
779         // Update external current
780         Output_ExtCurrent_Available = current;
781
782         unsigned int total_current = Output_current_available();
783         info_msg("External Available Current Changed. Total Available: ");
784         printInt32( total_current );
785         print(" mA" NL);
786
787         // Send new total current to the Scan Modules
788         Scan_currentChange( Output_current_available() );
789 }
790
791
792 // Power/Current Available
793 unsigned int Output_current_available()
794 {
795         unsigned int total_current = 0;
796
797         // Check for USB current source
798         total_current += Output_USBCurrent_Available;
799
800         // Check for external current source
801         total_current += Output_ExtCurrent_Available;
802
803         // XXX If the total available current is still 0
804         // Set to 100 mA, which is generally a safe assumption at startup
805         // before we've been able to determine actual available current
806         if ( total_current == 0 )
807         {
808                 total_current = 100;
809         }
810
811         return total_current;
812 }
813
814
815
816 // ----- CLI Command Functions -----
817
818 void cliFunc_kbdProtocol( char* args )
819 {
820         print( NL );
821         info_msg("Keyboard Protocol: ");
822         printInt8( USBKeys_Protocol );
823 }
824
825
826 void cliFunc_outputDebug( char* args )
827 {
828         // Parse number from argument
829         //  NOTE: Only first argument is used
830         char* arg1Ptr;
831         char* arg2Ptr;
832         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
833
834         // Default to 1 if no argument is given
835         Output_DebugMode = 1;
836
837         if ( arg1Ptr[0] != '\0' )
838         {
839                 Output_DebugMode = (uint16_t)numToInt( arg1Ptr );
840         }
841 }
842
843
844 void cliFunc_readLEDs( char* args )
845 {
846         print( NL );
847         info_msg("LED State: ");
848         printInt8( USBKeys_LEDs );
849 }
850
851
852 void cliFunc_readUART( char* args )
853 {
854         print( NL );
855
856         // Read UART buffer until empty
857         while ( uart_serial_available() > 0 )
858         {
859                 char out[] = { (char)uart_serial_getchar(), '\0' };
860                 dPrint( out );
861         }
862 }
863
864
865 void cliFunc_sendKeys( char* args )
866 {
867         // Copy USBKeys_KeysCLI to USBKeys_Keys
868         for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
869         {
870                 // TODO
871                 //USBKeys_Keys[key] = USBKeys_KeysCLI[key];
872         }
873         USBKeys_Sent = USBKeys_SentCLI;
874
875         // Set modifier byte
876         USBKeys_Modifiers = USBKeys_ModifiersCLI;
877 }
878
879
880 void cliFunc_sendUART( char* args )
881 {
882         // Write all args to UART
883         uart_serial_write( args, lenStr( args ) );
884 }
885
886
887 void cliFunc_setKeys( char* args )
888 {
889         char* curArgs;
890         char* arg1Ptr;
891         char* arg2Ptr = args;
892
893         // Parse up to USBKeys_MaxSize args (whichever is least)
894         for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USB_BOOT_MAX_KEYS; ++USBKeys_SentCLI )
895         {
896                 curArgs = arg2Ptr;
897                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
898
899                 // Stop processing args if no more are found
900                 if ( *arg1Ptr == '\0' )
901                         break;
902
903                 // Add the USB code to be sent
904                 // TODO
905                 //USBKeys_KeysCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
906         }
907 }
908
909
910 void cliFunc_setMod( char* args )
911 {
912         // Parse number from argument
913         //  NOTE: Only first argument is used
914         char* arg1Ptr;
915         char* arg2Ptr;
916         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
917
918         USBKeys_ModifiersCLI = numToInt( arg1Ptr );
919 }
920