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