]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Macro/buffer/macro.c
Adding test macros and basic "clicker" choose support
[kiibohd-controller.git] / Macro / buffer / macro.c
1 /* Copyright (C) 2011 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 // AVR Includes
25 #include <util/delay.h>
26 #include <avr/interrupt.h>
27
28 // Project Includes
29 #include <led.h>
30 #include <print.h>
31 #include <scan_loop.h>
32 #include <usb_com.h>
33
34 // Keymaps
35 #include <keymap.h>
36 #include <usb_keys.h>
37
38 // Local Includes
39 #include "macro.h"
40
41
42
43 // ----- Variables -----
44
45 // Keeps track of the sequence used to reflash the teensy in software
46 static uint8_t Bootloader_ConditionSequence[] = {1,16,6,11};
47        uint8_t Bootloader_ConditionState      = 0;
48        uint8_t Bootloader_NextPositionReady   = 1;
49        uint8_t Bootloader_KeyDetected         = 0;
50
51
52
53 // ----- Functions -----
54
55 inline void macro_finishedWithBuffer(void)
56 {
57         /* BudKeypad
58         // Boot loader sequence state handler
59         switch ( KeyIndex_BufferUsed )
60         {
61         // The next bootloader key can now be pressed, if there were no keys processed
62         case 0:
63                 Bootloader_NextPositionReady = 1;
64                 break;
65         // If keys were detected, and it wasn't in the sequence (or there was multiple keys detected), start bootloader sequence over
66         // This case purposely falls through
67         case 1:
68                 if ( Bootloader_KeyDetected )
69                         break;
70         default:
71                 Bootloader_ConditionState = 0;
72                 break;
73         }
74
75         Bootloader_KeyDetected = 0;
76         */
77 }
78
79 void jumpToBootloader(void)
80 {
81         cli();
82         // disable watchdog, if enabled
83         // disable all peripherals
84         UDCON = 1;
85         USBCON = (1<<FRZCLK);  // disable USB
86         UCSR1B = 0;
87         _delay_ms(5);
88
89 #if defined(__AVR_AT90USB162__)                // Teensy 1.0
90         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0;
91         TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0;
92         DDRB = 0; DDRC = 0; DDRD = 0;
93         PORTB = 0; PORTC = 0; PORTD = 0;
94         asm volatile("jmp 0x3E00");
95 #elif defined(__AVR_ATmega32U4__)              // Teensy 2.0
96         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
97         TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0;
98         DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0;
99         PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
100         asm volatile("jmp 0x7E00");
101 #elif defined(__AVR_AT90USB646__)              // Teensy++ 1.0
102         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
103         TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
104         DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
105         PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
106         asm volatile("jmp 0xFC00");
107 #elif defined(__AVR_AT90USB1286__)             // Teensy++ 2.0
108         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
109         TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
110         DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
111         PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
112         asm volatile("jmp 0x1FC00");
113 #endif
114 }
115
116 // Given a sampling array, and the current number of detected keypress
117 // Add as many keypresses from the sampling array to the USB key send array as possible.
118 /*
119 inline void keyPressDetection( uint8_t *keys, uint8_t numberOfKeys, uint8_t *modifiers, uint8_t numberOfModifiers, uint8_t *map )
120 {
121         uint8_t Bootloader_KeyDetected = 0;
122         uint8_t processed_keys         = 0;
123
124         // Parse the detection array starting from 1 (all keys are purposefully mapped from 1 -> total as per typical PCB labels)
125         for ( uint8_t key = 0; key < numberOfKeys + 1; key++ )
126         {
127                 if ( keys[key] & (1 << 7) )
128                 {
129                         processed_keys++;
130
131                         // Display the detected scancode
132                         char tmpStr[4];
133                         int8ToStr( key, tmpStr );
134                         dPrintStrs( tmpStr, " " );
135
136                         // Is this a bootloader sequence key?
137                         if ( !Bootloader_KeyDetected
138                            && Bootloader_NextPositionReady
139                            && key == Bootloader_ConditionSequence[Bootloader_ConditionState] )
140                         {
141                                 Bootloader_KeyDetected = 1;
142                                 Bootloader_NextPositionReady = 0;
143                                 Bootloader_ConditionState++;
144                         }
145                         else if ( Bootloader_ConditionState > 0 && key == Bootloader_ConditionSequence[Bootloader_ConditionState - 1] )
146                         {
147                                 Bootloader_KeyDetected = 1;
148                         }
149
150                         // Determine if the key is a modifier
151                         uint8_t modFound = 0;
152                         for ( uint8_t mod = 0; mod < numberOfModifiers; mod++ ) {
153                                 // Modifier found
154                                 if ( modifiers[mod] == key ) {
155                                         USBKeys_Modifiers |= map[key];
156                                         modFound = 1;
157                                         break;
158                                 }
159                         }
160
161                         // Modifier, already done this loop
162                         if ( modFound )
163                                 continue;
164
165                         // Too many keys
166                         if ( USBKeys_Sent >= USBKeys_MaxSize )
167                         {
168                                 info_print("USB Key limit reached");
169                                 errorLED( 1 );
170                                 break;
171                         }
172
173                         // Allow ignoring keys with 0's
174                         if ( map[key] != 0 )
175                                 USBKeys_Array[USBKeys_Sent++] = map[key];
176                 }
177         }
178
179         // Boot loader sequence state handler
180         switch ( processed_keys )
181         {
182         // The next bootloader key can now be pressed, if there were no keys processed
183         case 0:
184                 Bootloader_NextPositionReady = 1;
185                 break;
186         // If keys were detected, and it wasn't in the sequence (or there was multiple keys detected), start bootloader sequence over
187         // This case purposely falls through
188         case 1:
189                 if ( Bootloader_KeyDetected )
190                         break;
191         default:
192                 Bootloader_ConditionState = 0;
193                 break;
194         }
195
196         // Add debug separator if keys sent via USB
197         if ( USBKeys_Sent > 0 )
198                 print("\033[1;32m|\033[0m\n");
199 }
200 */
201
202 // Scancode Macro Detection
203 int scancodeMacro( uint8_t scanCode )
204 {
205         /*
206         if ( scanCode == 0x7A )
207         {
208                 scan_resetKeyboard();
209         }
210         else
211         {
212                 scan_sendData( scanCode );
213                 _delay_ms( 200 );
214                 scan_sendData( 0x80 | scanCode );
215         }
216         return 1;
217         */
218         /*
219         // BudKeypad
220         // Is this a bootloader sequence key?
221         if ( !Bootloader_KeyDetected
222            && Bootloader_NextPositionReady
223            && scanCode == Bootloader_ConditionSequence[Bootloader_ConditionState] )
224         {
225                 Bootloader_KeyDetected = 1;
226                 Bootloader_NextPositionReady = 0;
227                 Bootloader_ConditionState++;
228                 erro_dPrint("detect");
229         }
230         else if ( Bootloader_ConditionState > 0 && scanCode == Bootloader_ConditionSequence[Bootloader_ConditionState - 1] )
231         {
232                 Bootloader_KeyDetected = 0;
233                 Bootloader_NextPositionReady = 1;
234                 erro_dPrint("detect-again!");
235         }
236         // Cancel sequence
237         else
238         {
239                 Bootloader_KeyDetected = 0;
240                 Bootloader_NextPositionReady = 1;
241                 Bootloader_ConditionState = 0;
242                 erro_dPrint("Arg");
243         }
244         */
245
246         return 0;
247 }
248
249 uint8_t sendCode = 0;
250
251 // USBCode Macro Detection
252 int usbcodeMacro( uint8_t usbCode )
253 {
254         // Keyboard Input Test Macro
255         switch ( usbCode )
256         {
257         case KEY_F1:
258                 sendCode--;
259                 //scan_sendData( 0x90 );
260                 scan_sendData( sendCode );
261                 _delay_ms( 200 );
262                 break;
263
264         case KEY_F2:
265                 //scan_sendData( 0x90 );
266                 scan_sendData( sendCode );
267                 _delay_ms( 200 );
268                 break;
269
270         case KEY_F3:
271                 sendCode++;
272                 //scan_sendData( 0x90 );
273                 scan_sendData( sendCode );
274                 _delay_ms( 200 );
275                 break;
276
277         case KEY_F4:
278                 sendCode += 0x10;
279                 //scan_sendData( 0x90 );
280                 scan_sendData( sendCode );
281                 _delay_ms( 200 );
282                 break;
283
284         case KEY_F5:
285                 // Set 9th bit to 0
286                 UCSR1B &= ~(1 << 0);
287                 _delay_ms( 200 );
288                 break;
289
290         case KEY_F6:
291                 // Set 9th bit to 1
292                 UCSR1B |=  (1 << 0);
293                 _delay_ms( 200 );
294                 break;
295
296         case KEY_F11:
297                 // Set click code
298                 KeyIndex_Add_InputSignal = sendCode;
299                 _delay_ms( 200 );
300                 break;
301
302         default:
303                 return 0;
304         }
305         
306         return 1;
307         //return 0;
308 }
309
310
311 // Given a list of keypresses, translate into the USB key codes
312 // The buffer is cleared after running
313 // If the buffer doesn't fit into the USB send array, the extra keys are dropped
314 void keyPressBufferRead( uint8_t *modifiers, uint8_t numberOfModifiers, uint8_t *map )
315 {
316         // Loop through input buffer
317         for ( uint8_t index = 0; index < KeyIndex_BufferUsed; index++ )
318         {
319                 // Get the keycode from the buffer
320                 uint8_t key = KeyIndex_Buffer[index];
321
322                 // Check key for special usages using the scancode
323                 // If non-zero return, ignore normal processing of the scancode
324                 if ( scancodeMacro( key ) )
325                         continue;
326
327                 // Check key for special usages using the usbcode
328                 // If non-zero return, ignore normal processing of the usbcode
329                 if ( usbcodeMacro( map[key] ) )
330                         continue;
331
332                 // Determine if the key is a modifier
333                 uint8_t modFound = 0;
334                 for ( uint8_t mod = 0; mod < numberOfModifiers; mod++ ) {
335                         // Modifier found
336                         if ( modifiers[mod] == key ) {
337                                 USBKeys_Modifiers |= map[key];
338                                 modFound = 1;
339                                 break;
340                         }
341                 }
342
343                 // Modifier, already done this loop
344                 if ( modFound )
345                         continue;
346
347                 // Too many keys
348                 if ( USBKeys_Sent >= USBKeys_MaxSize )
349                 {
350                         info_print("USB Key limit reached");
351                         errorLED( 1 );
352                         break;
353                 }
354
355                 // Allow ignoring keys with 0's
356                 if ( map[key] != 0 )
357                 {
358                         USBKeys_Array[USBKeys_Sent++] = map[key];
359                 }
360                 else
361                 {
362                         // Key was not mapped
363                         // TODO Add dead key map
364                         char tmpStr[6];
365                         hexToStr( key, tmpStr );
366                         erro_dPrint( "Key not mapped... - ", tmpStr );
367                         errorLED( 1 );
368                 }
369         }
370
371         // Signal Macro processor that all of the buffered keys have been processed
372         macro_finishedWithBuffer();
373
374         // Signal buffer that we've used it
375         scan_finishedWithBuffer();
376 }
377
378 inline void process_macros(void)
379 {
380         // Online process macros once (if some were found), until the next USB send
381         if ( USBKeys_Sent != 0 )
382                 return;
383
384         // Query the input buffer for keypresses
385         keyPressBufferRead( MODIFIER_MASK, sizeof(MODIFIER_MASK), KEYINDEX_MASK );
386
387         // Check for bootloader condition
388         if ( Bootloader_ConditionState == sizeof( Bootloader_ConditionSequence ) )
389                 jumpToBootloader();
390 }
391