]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/output_com.c
Fixing USB send rate.
[kiibohd-controller.git] / Output / pjrcUSB / output_com.c
1 /* Copyright (C) 2011-2014 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_)
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 // ----- Function Declarations -----
48
49 void cliFunc_kbdProtocol( char* args );
50 void cliFunc_readLEDs   ( char* args );
51 void cliFunc_sendKeys   ( char* args );
52 void cliFunc_setKeys    ( char* args );
53 void cliFunc_setMod     ( char* args );
54
55
56 // ----- Variables -----
57
58 // Output Module command dictionary
59 const char outputCLIDictName[] = "USB Module Commands";
60 const CLIDictItem outputCLIDict[] = {
61         { "kbdProtocol", "Keyboard Protocol Mode: 0 - Boot, 1 - OS/NKRO Mode", cliFunc_kbdProtocol },
62         { "readLEDs",    "Read LED byte:" NL "\t\t1 NumLck, 2 CapsLck, 4 ScrlLck, 16 Kana, etc.", cliFunc_readLEDs },
63         { "sendKeys",    "Send the prepared list of USB codes and modifier byte.", cliFunc_sendKeys },
64         { "setKeys",     "Prepare a space separated list of USB codes (decimal). Waits until \033[35msendKeys\033[0m.", cliFunc_setKeys },
65         { "setMod",      "Set the modfier byte:" NL "\t\t1 LCtrl, 2 LShft, 4 LAlt, 8 LGUI, 16 RCtrl, 32 RShft, 64 RAlt, 128 RGUI", cliFunc_setMod },
66         { 0, 0, 0 } // Null entry for dictionary end
67 };
68
69
70 // Which modifier keys are currently pressed
71 // 1=left ctrl,    2=left shift,   4=left alt,    8=left gui
72 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
73          uint8_t USBKeys_Modifiers    = 0;
74          uint8_t USBKeys_ModifiersCLI = 0; // Separate CLI send buffer
75
76 // Currently pressed keys, max is defined by USB_MAX_KEY_SEND
77          uint8_t USBKeys_Array   [USB_MAX_KEY_SEND];
78          uint8_t USBKeys_ArrayCLI[USB_MAX_KEY_SEND]; // Separate CLI send buffer
79
80 // The number of keys sent to the usb in the array
81          uint8_t USBKeys_Sent    = 0;
82          uint8_t USBKeys_SentCLI = 0;
83
84 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
85 volatile uint8_t USBKeys_LEDs = 0;
86
87 // Protocol setting from the host.
88 // 0 - Boot Mode (Default, until set by the host)
89 // 1 - NKRO Mode
90 volatile uint8_t USBKeys_Protocol = 1;
91
92 // Indicate if USB should send update
93 // OS only needs update if there has been a change in state
94          uint8_t USBKeys_Changed = 0;
95
96 // the idle configuration, how often we send the report to the
97 // host (ms * 4) even when it hasn't changed
98          uint8_t USBKeys_Idle_Config = 125;
99
100 // count until idle timeout
101          uint8_t USBKeys_Idle_Count = 0;
102
103
104 // ----- Capabilities -----
105
106 // Adds a single USB Code to the USB Output buffer
107 // Argument #1: USB Code
108 void Output_usbCodeSend_capability( uint8_t state, uint8_t stateType, uint8_t *args )
109 {
110         // Display capability name
111         if ( stateType == 0xFF && state == 0xFF )
112         {
113                 print("Output_usbCodeSend(usbCode)");
114                 return;
115         }
116
117         // TODO Analog inputs
118         // Only indicate USB has changed if either a press or release has occured
119         if ( state == 0x01 || state == 0x03 )
120                 USBKeys_Changed = 1;
121
122         // Only send keypresses if press or hold state
123         if ( stateType == 0x00 && state == 0x03 ) // Release state
124                 return;
125
126         // Get the keycode from arguments
127         uint8_t key = args[0];
128
129         // Set the modifier bit if this key is a modifier
130         if ( (key & 0xE0) == 0xE0 ) // AND with 0xE0 (Left Ctrl, first modifier)
131         {
132                 USBKeys_Modifiers |= 1 << (key ^ 0xE0); // Left shift 1 by key XOR 0xE0
133         }
134         // Normal USB Code
135         else
136         {
137                 // USB Key limit reached (important for Boot Mode)
138                 if ( USBKeys_Sent >= USBKeys_MaxSize )
139                 {
140                         warn_msg("USB Key limit reached");
141                         errorLED( 1 );
142                         return;
143                 }
144
145                 USBKeys_Array[USBKeys_Sent++] = key;
146         }
147 }
148
149
150
151 // ----- Functions -----
152
153 // USB Module Setup
154 inline void Output_setup()
155 {
156         // Initialize the USB, and then wait for the host to set configuration.
157         // If the Teensy is powered without a PC connected to the USB port,
158         // this will wait forever.
159         usb_init();
160
161         while ( !usb_configured() ) /* wait */ ;
162
163         // Register USB Output CLI dictionary
164         CLI_registerDictionary( outputCLIDict, outputCLIDictName );
165
166         // Wait an extra second for the PC's operating system to load drivers
167         // and do whatever it does to actually be ready for input
168         //_delay_ms(1000); // TODO (is this actually necessary?)
169 }
170
171
172 // USB Data Send
173 inline void Output_send(void)
174 {
175         // Don't send update if USB has not changed
176         if ( !USBKeys_Changed )
177         {
178                 // Clear modifiers and keys
179                 USBKeys_Modifiers = 0;
180                 USBKeys_Sent      = 0;
181
182                 return;
183         }
184         USBKeys_Changed = 0;
185
186         // TODO undo potentially old keys
187         for ( uint8_t c = USBKeys_Sent; c < USBKeys_MaxSize; c++ )
188                 USBKeys_Array[c] = 0;
189
190         // Send keypresses
191         usb_keyboard_send();
192
193         // Clear modifiers and keys
194         USBKeys_Modifiers = 0;
195         USBKeys_Sent      = 0;
196
197         // Signal Scan Module we are finished
198         Scan_finishedWithOutput( USBKeys_Sent <= USBKeys_MaxSize ? USBKeys_Sent : USBKeys_MaxSize );
199 }
200
201
202 // Sets the device into firmware reload mode
203 inline void Output_firmwareReload()
204 {
205         usb_device_reload();
206 }
207
208
209 // USB Input buffer available
210 inline unsigned int Output_availablechar()
211 {
212         return usb_serial_available();
213 }
214
215
216 // USB Get Character from input buffer
217 inline int Output_getchar()
218 {
219         // XXX Make sure to check output_availablechar() first! Information is lost with the cast (error codes) (AVR)
220         return (int)usb_serial_getchar();
221 }
222
223
224 // USB Send Character to output buffer
225 inline int Output_putchar( char c )
226 {
227         return usb_serial_putchar( c );
228 }
229
230
231 // USB Send String to output buffer, null terminated
232 inline int Output_putstr( char* str )
233 {
234 #if defined(_at90usb162_) || defined(_atmega32u4_) || defined(_at90usb646_) || defined(_at90usb1286_) // AVR
235         uint16_t count = 0;
236 #elif defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) // ARM
237         uint32_t count = 0;
238 #endif
239         // Count characters until NULL character, then send the amount counted
240         while ( str[count] != '\0' )
241                 count++;
242
243         return usb_serial_write( str, count );
244 }
245
246
247 // Soft Chip Reset
248 inline void Output_softReset()
249 {
250         usb_device_software_reset();
251 }
252
253
254 // ----- CLI Command Functions -----
255
256 void cliFunc_kbdProtocol( char* args )
257 {
258         print( NL );
259         info_msg("Keyboard Protocol: ");
260         printInt8( USBKeys_Protocol );
261 }
262
263
264 void cliFunc_readLEDs( char* args )
265 {
266         print( NL );
267         info_msg("LED State: ");
268         printInt8( USBKeys_LEDs );
269 }
270
271
272 void cliFunc_sendKeys( char* args )
273 {
274         // Copy USBKeys_ArrayCLI to USBKeys_Array
275         for ( uint8_t key = 0; key < USBKeys_SentCLI; ++key )
276         {
277                 USBKeys_Array[key] = USBKeys_ArrayCLI[key];
278         }
279         USBKeys_Sent = USBKeys_SentCLI;
280
281         // Set modifier byte
282         USBKeys_Modifiers = USBKeys_ModifiersCLI;
283 }
284
285
286 void cliFunc_setKeys( char* args )
287 {
288         char* curArgs;
289         char* arg1Ptr;
290         char* arg2Ptr = args;
291
292         // Parse up to USBKeys_MaxSize args (whichever is least)
293         for ( USBKeys_SentCLI = 0; USBKeys_SentCLI < USBKeys_MaxSize; ++USBKeys_SentCLI )
294         {
295                 curArgs = arg2Ptr;
296                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
297
298                 // Stop processing args if no more are found
299                 if ( *arg1Ptr == '\0' )
300                         break;
301
302                 // Add the USB code to be sent
303                 USBKeys_ArrayCLI[USBKeys_SentCLI] = numToInt( arg1Ptr );
304         }
305 }
306
307
308 void cliFunc_setMod( char* args )
309 {
310         // Parse number from argument
311         //  NOTE: Only first argument is used
312         char* arg1Ptr;
313         char* arg2Ptr;
314         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
315
316         USBKeys_ModifiersCLI = numToInt( arg1Ptr );
317 }
318