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