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