]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Macro/PartialMap/macro.c
Added capabilities list debug option
[kiibohd-controller.git] / Macro / PartialMap / macro.c
1 /* Copyright (C) 2014 by Jacob Alexander
2  *
3  * This file is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This file is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this file.  If not, see <http://www.gnu.org/licenses/>.
15  */
16
17 // ----- Includes -----
18
19 // Compiler Includes
20 #include <Lib/MacroLib.h>
21
22 // Project Includes
23 #include <cli.h>
24 #include <led.h>
25 #include <print.h>
26 #include <scan_loop.h>
27 #include <output_com.h>
28
29 // Keymaps
30 #include "usb_hid.h"
31 #include <defaultMap.h>
32 #include "generatedKeymap.h" // TODO Use actual generated version
33
34 // Local Includes
35 #include "macro.h"
36
37
38
39 // ----- Function Declarations -----
40
41 void cliFunc_capList   ( char* args );
42 void cliFunc_capSelect ( char* args );
43 void cliFunc_keyPress  ( char* args );
44 void cliFunc_keyRelease( char* args );
45 void cliFunc_layerLatch( char* args );
46 void cliFunc_layerList ( char* args );
47 void cliFunc_layerLock ( char* args );
48 void cliFunc_macroDebug( char* args );
49 void cliFunc_macroList ( char* args );
50 void cliFunc_macroProc ( char* args );
51 void cliFunc_macroShow ( char* args );
52 void cliFunc_macroStep ( char* args );
53
54
55
56 // ----- Variables -----
57
58 // Macro Module command dictionary
59 char*       macroCLIDictName = "Macro Module Commands";
60 CLIDictItem macroCLIDict[] = {
61         { "capList",     "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
62         { "capSelect",   "Triggers the specified capability." NL "\t\t\033[35mU10\033[0m USB Code 0x0A, \033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
63         { "keyPress",    "Send key-presses to the macro module. Held until released. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyPress },
64         { "keyRelease",  "Release a key-press from the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
65         { "layerLatch",  "Latch the specified indexed layer." NL "\t\t\033[35mL15\033[0m Indexed Layer 0x0F", cliFunc_layerLatch },
66         { "layerList",   "List available layers.", cliFunc_layerList },
67         { "layerLock",   "Lock the specified indexed layer." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02", cliFunc_layerLock },
68         { "macroDebug",  "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
69         { "macroList",   "List the defined trigger and result macros.", cliFunc_macroList },
70         { "macroProc",   "Pause/Resume macro processing.", cliFunc_macroProc },
71         { "macroShow",   "Show the macro corresponding to the given index or scan-code." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C", cliFunc_macroShow },
72         { "macroStep",   "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
73         { 0, 0, 0 } // Null entry for dictionary end
74 };
75
76
77 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
78 uint8_t macroDebugMode = 0;
79
80 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
81 uint8_t macroPauseMode = 0;
82
83 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
84 unsigned int macroStepCounter = 0;
85
86
87 // Key Trigger List Buffer
88 //  * Item 1: scan code
89 //  * Item 2: state
90 //    ...
91 uint8_t macroTriggerListBuffer[MaxScanCode * 2] = { 0 }; // Each key has a state to be cached
92 uint8_t macroTriggerListBufferSize = 0;
93
94 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
95 //       Possibly could be calculated by the KLL compiler
96 // XXX It may be possible to calculate the worst case using the KLL compiler
97 TriggerMacro *triggerMacroPendingList[TriggerMacroNum];
98
99
100
101 // ----- Functions -----
102
103 // Looks up the trigger list for the given scan code (from the active layer)
104 unsigned int *Macro_layerLookup( uint8_t scanCode )
105 {
106         // TODO - No layer fallthrough lookup
107         return default_scanMap[ scanCode ];
108 }
109
110
111 // Update the scancode key state
112 // States:
113 //   * 0x00 - Reserved
114 //   * 0x01 - Pressed
115 //   * 0x02 - Held
116 //   * 0x03 - Released
117 //   * 0x04 - Unpressed (this is currently ignored)
118 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
119 {
120         // Only add to macro trigger list if one of three states
121         switch ( state )
122         {
123         case 0x01: // Pressed
124         case 0x02: // Held
125         case 0x03: // Released
126                 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = scanCode;
127                 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = state;
128                 break;
129         }
130 }
131
132
133 // Update the scancode analog state
134 // States:
135 //   * 0x00      - Reserved
136 //   * 0x01      - Released
137 //   * 0x02-0xFF - Analog value (low to high)
138 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
139 {
140         // TODO
141 }
142
143
144 // Update led state
145 // States:
146 //   * 0x00 - Reserved
147 //   * 0x01 - On
148 //   * 0x02 - Off
149 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
150 {
151         // TODO
152 }
153
154
155 // Evaluate/Update the TriggerMacro
156 void Macro_evalTriggerMacro( TriggerMacro *triggerMacro )
157 {
158         // Which combo in the sequence is being evaluated
159         unsigned int comboPos = triggerMacro->pos;
160
161         // If combo length is more than 1, cancel trigger macro if an incorrect key is found
162         uint8_t comboLength = triggerMacro->guide[ comboPos ];
163
164         // Iterate over list of keys currently pressed
165         for ( uint8_t keyPressed = 0; keyPressed < macroTriggerListBufferSize; keyPressed += 2 )
166         {
167                 // Compare with keys in combo
168                 for ( unsigned int comboKey = 0; comboKey < comboLength; comboKey++ )
169                 {
170                         // Lookup key in combo
171                         uint8_t guideKey = triggerMacro->guide[ comboPos + comboKey + 2 ]; // TODO Only Press/Hold/Release atm
172
173                         // Sequence Case
174                         if ( comboLength == 1 )
175                         {
176                                 // If key matches and only 1 key pressed, increment the TriggerMacro combo position
177                                 if ( guideKey == macroTriggerListBuffer[ keyPressed ] && macroTriggerListBufferSize == 1 )
178                                 {
179                                         triggerMacro->pos += comboLength * 2 + 1;
180                                         // TODO check if TriggerMacro is finished, register ResultMacro
181                                         return;
182                                 }
183
184                                 // If key does not match or more than 1 key pressed, reset the TriggerMacro combo position
185                                 triggerMacro->pos = 0;
186                                 return;
187                         }
188                         // Combo Case
189                         else
190                         {
191                                 // TODO
192                         }
193                 }
194         }
195 }
196
197
198
199
200 /*
201 inline void Macro_bufferAdd( uint8_t byte )
202 {
203         // Make sure we haven't overflowed the key buffer
204         // Default function for adding keys to the KeyIndex_Buffer, does a DefaultMap_Lookup
205         if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER )
206         {
207                 uint8_t key = DefaultMap_Lookup[byte];
208                 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
209                 {
210                         // Key already in the buffer
211                         if ( KeyIndex_Buffer[c] == key )
212                                 return;
213                 }
214
215                 // Add to the buffer
216                 KeyIndex_Buffer[KeyIndex_BufferUsed++] = key;
217         }
218 }
219
220 inline void Macro_bufferRemove( uint8_t byte )
221 {
222         uint8_t key = DefaultMap_Lookup[byte];
223
224         // Check for the released key, and shift the other keys lower on the buffer
225         for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
226         {
227                 // Key to release found
228                 if ( KeyIndex_Buffer[c] == key )
229                 {
230                         // Shift keys from c position
231                         for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
232                                 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
233
234                         // Decrement Buffer
235                         KeyIndex_BufferUsed--;
236
237                         return;
238                 }
239         }
240
241         // Error case (no key to release)
242         erro_msg("Could not find key to release: ");
243         printHex( key );
244 }
245 */
246
247 inline void Macro_finishWithUSBBuffer( uint8_t sentKeys )
248 {
249 }
250
251 inline void Macro_process()
252 {
253         // Only do one round of macro processing between Output Module timer sends
254         if ( USBKeys_Sent != 0 )
255                 return;
256
257         // If the pause flag is set, only process if the step counter is non-zero
258         if ( macroPauseMode && macroStepCounter == 0 )
259         {
260                 return;
261         }
262         // Proceed, decrementing the step counter
263         else
264         {
265                 macroStepCounter--;
266         }
267
268         // Loop through macro trigger buffer
269         for ( uint8_t index = 0; index < macroTriggerListBufferSize; index += 2 )
270         {
271                 // Get scanCode, first item of macroTriggerListBuffer pairs
272                 uint8_t scanCode = macroTriggerListBuffer[ index ];
273
274                 // Lookup trigger list for this key
275                 unsigned int *triggerList = Macro_layerLookup( scanCode );
276
277                 // The first element is the length of the trigger list
278                 unsigned int triggerListSize = triggerList[0];
279
280                 // Loop through the trigger list
281                 for ( unsigned int trigger = 0; trigger < triggerListSize; trigger++ )
282                 {
283                         // Lookup TriggerMacro
284                         TriggerMacro *triggerMacro = (TriggerMacro*)triggerList[ trigger + 1 ];
285
286                         // Get triggered state of scan code, second item of macroTriggerListBuffer pairs
287                         uint8_t state = macroTriggerListBuffer[ index + 1 ];
288
289                         // Evaluate Macro
290                         Macro_evalTriggerMacro( triggerMacro );
291                 }
292         }
293
294
295
296
297
298         /* TODO
299         // Loop through input buffer
300         for ( uint8_t index = 0; index < KeyIndex_BufferUsed && !macroDebugMode; index++ )
301         {
302                 //print(" KEYS: ");
303                 //printInt8( KeyIndex_BufferUsed );
304                 // Get the keycode from the buffer
305                 uint8_t key = KeyIndex_Buffer[index];
306
307                 // Set the modifier bit if this key is a modifier
308                 if ( (key & KEY_LCTRL) == KEY_LCTRL ) // AND with 0xE0
309                 {
310                         USBKeys_Modifiers |= 1 << (key ^ KEY_LCTRL); // Left shift 1 by key XOR 0xE0
311
312                         // Modifier processed, move on to the next key
313                         continue;
314                 }
315
316                 // Too many keys
317                 if ( USBKeys_Sent >= USBKeys_MaxSize )
318                 {
319                         warn_msg("USB Key limit reached");
320                         errorLED( 1 );
321                         break;
322                 }
323
324                 // Allow ignoring keys with 0's
325                 if ( key != 0 )
326                 {
327                         USBKeys_Array[USBKeys_Sent++] = key;
328                 }
329                 else
330                 {
331                         // Key was not mapped
332                         erro_msg( "Key not mapped... - " );
333                         printHex( key );
334                         errorLED( 1 );
335                 }
336         }
337         */
338
339         // Signal buffer that we've used it
340         Scan_finishedWithBuffer( KeyIndex_BufferUsed );
341
342         // If Macro debug mode is set, clear the USB Buffer
343         if ( macroDebugMode )
344         {
345                 USBKeys_Modifiers = 0;
346                 USBKeys_Sent = 0;
347         }
348 }
349
350 inline void Macro_setup()
351 {
352         // Register Macro CLI dictionary
353         CLI_registerDictionary( macroCLIDict, macroCLIDictName );
354
355         // Disable Macro debug mode
356         macroDebugMode = 0;
357
358         // Disable Macro pause flag
359         macroPauseMode = 0;
360
361         // Set Macro step counter to zero
362         macroStepCounter = 0;
363
364         // Make sure macro trigger buffer is empty
365         macroTriggerListBufferSize = 0;
366 }
367
368
369 // ----- CLI Command Functions -----
370
371 void cliFunc_capList( char* args )
372 {
373         print( NL );
374         info_msg("Capabilities List");
375
376         // Iterate through all of the capabilities and display them
377         for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
378         {
379                 print( NL "\t" );
380                 printHex( cap );
381                 print(" - ");
382
383                 // Display/Lookup Capability Name (utilize debug mode of capability)
384                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ]);
385                 capability( 0xFF, 0xFF, 0 );
386         }
387 }
388
389 void cliFunc_capSelect( char* args )
390 {
391         // Parse code from argument
392         //  NOTE: Only first argument is used
393         char* arg1Ptr;
394         char* arg2Ptr;
395         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
396
397         // Depending on the first character, the lookup changes
398         switch ( arg1Ptr[0] )
399         {
400         // Keyboard Capability
401         case 'K':
402                 // TODO
403                 break;
404
405         // USB Code
406         case 'U':
407                 // Just add the key to the USB Buffer
408                 if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER )
409                 {
410                         KeyIndex_Buffer[KeyIndex_BufferUsed++] = decToInt( &arg1Ptr[1] );
411                 }
412                 break;
413         }
414 }
415
416 void cliFunc_keyPress( char* args )
417 {
418         // Parse codes from arguments
419         char* curArgs;
420         char* arg1Ptr;
421         char* arg2Ptr = args;
422
423         // Process all args
424         for ( ;; )
425         {
426                 curArgs = arg2Ptr;
427                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
428
429                 // Stop processing args if no more are found
430                 if ( *arg1Ptr == '\0' )
431                         break;
432
433                 // Ignore non-Scancode numbers
434                 switch ( arg1Ptr[0] )
435                 {
436                 // Scancode
437                 case 'S':
438                         Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
439                         break;
440                 }
441         }
442 }
443
444 void cliFunc_keyRelease( char* args )
445 {
446         // Parse codes from arguments
447         char* curArgs;
448         char* arg1Ptr;
449         char* arg2Ptr = args;
450
451         // Process all args
452         for ( ;; )
453         {
454                 curArgs = arg2Ptr;
455                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
456
457                 // Stop processing args if no more are found
458                 if ( *arg1Ptr == '\0' )
459                         break;
460
461                 // Ignore non-Scancode numbers
462                 switch ( arg1Ptr[0] )
463                 {
464                 // Scancode
465                 case 'S':
466                         Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
467                         break;
468                 }
469         }
470 }
471
472 void cliFunc_layerLatch( char* args )
473 {
474         // TODO
475 }
476
477 void cliFunc_layerList( char* args )
478 {
479         // TODO
480 }
481
482 void cliFunc_layerLock( char* args )
483 {
484         // TODO
485 }
486
487 void cliFunc_macroDebug( char* args )
488 {
489         // Toggle macro debug mode
490         macroDebugMode = macroDebugMode ? 0 : 1;
491
492         print( NL );
493         info_msg("Macro Debug Mode: ");
494         printInt8( macroDebugMode );
495 }
496
497 void cliFunc_macroList( char* args )
498 {
499         // TODO
500 }
501
502 void cliFunc_macroProc( char* args )
503 {
504         // Toggle macro pause mode
505         macroPauseMode = macroPauseMode ? 0 : 1;
506
507         print( NL );
508         info_msg("Macro Processing Mode: ");
509         printInt8( macroPauseMode );
510 }
511
512 void macroDebugShowTrigger( unsigned int index )
513 {
514         // Only proceed if the macro exists
515         if ( index >= TriggerMacroNum )
516                 return;
517
518         // Trigger Macro Show
519         TriggerMacro *macro = &TriggerMacroList[ index ];
520
521         print( NL );
522         info_msg("Trigger Macro Index: ");
523         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
524         print( NL );
525
526         // Read the comboLength for combo in the sequence (sequence of combos)
527         unsigned int pos = 0;
528         uint8_t comboLength = macro->guide[ pos ];
529
530         // Iterate through and interpret the guide
531         while ( comboLength != 0 )
532         {
533                 // Initial position of the combo
534                 unsigned int comboPos = ++pos;
535
536                 // Iterate through the combo
537                 while ( pos < comboLength * TriggerGuideSize + comboPos )
538                 {
539                         // Assign TriggerGuide element (key type, state and scancode)
540                         TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
541
542                         // Display guide information about trigger key
543                         printHex( guide->scancode );
544                         print("|");
545                         printHex( guide->type );
546                         print("|");
547                         printHex( guide->state );
548
549                         // Increment position
550                         pos += TriggerGuideSize;
551
552                         // Only show combo separator if there are combos left in the sequence element
553                         if ( pos < comboLength * TriggerGuideSize + comboPos )
554                                 print("+");
555                 }
556
557                 // Read the next comboLength
558                 comboLength = macro->guide[ pos ];
559
560                 // Only show sequence separator if there is another combo to process
561                 if ( comboLength != 0 )
562                         print(";");
563         }
564
565         // Display current position
566         print( NL "Position: " );
567         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
568
569         // Display result macro index
570         print( NL "Result Macro Index: " );
571         printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
572 }
573
574 void macroDebugShowResult( unsigned int index )
575 {
576         // Only proceed if the macro exists
577         if ( index >= ResultMacroNum )
578                 return;
579
580         // Trigger Macro Show
581         ResultMacro *macro = &ResultMacroList[ index ];
582
583         print( NL );
584         info_msg("Result Macro Index: ");
585         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
586         print( NL );
587
588         // Read the comboLength for combo in the sequence (sequence of combos)
589         unsigned int pos = 0;
590         uint8_t comboLength = macro->guide[ pos++ ];
591
592         // Iterate through and interpret the guide
593         while ( comboLength != 0 )
594         {
595                 // Function Counter, used to keep track of the combos processed
596                 unsigned int funcCount = 0;
597
598                 // Iterate through the combo
599                 while ( funcCount < comboLength )
600                 {
601                         // Assign TriggerGuide element (key type, state and scancode)
602                         ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
603
604                         // Display Function Index
605                         printHex( guide->index );
606                         print("|");
607
608                         // Display Function Ptr Address
609                         printHex( (unsigned int)CapabilitiesList[ guide->index ] );
610                         print("|");
611
612                         // Display/Lookup Capability Name (utilize debug mode of capability)
613                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ]);
614                         capability( 0xFF, 0xFF, 0 );
615
616                         // Display Argument(s)
617                         print("(");
618                         for ( unsigned int arg = 0; arg < guide->argCount; arg++ )
619                         {
620                                 // Arguments are only 8 bit values
621                                 printHex( (&guide->args)[ arg ] );
622
623                                 // Only show arg separator if there are args left
624                                 if ( arg + 1 < guide->argCount )
625                                         print(",");
626                         }
627                         print(")");
628
629                         // Increment position
630                         pos += ResultGuideSize( guide );
631
632                         // Increment function count
633                         funcCount++;
634
635                         // Only show combo separator if there are combos left in the sequence element
636                         if ( funcCount < comboLength )
637                                 print("+");
638                 }
639
640                 // Read the next comboLength
641                 comboLength = macro->guide[ pos++ ];
642
643                 // Only show sequence separator if there is another combo to process
644                 if ( comboLength != 0 )
645                         print(";");
646         }
647
648         // Display current position
649         print( NL "Position: " );
650         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
651
652         // Display final trigger state/type
653         print( NL "Final Trigger State (State/Type): " );
654         printHex( macro->state );
655         print("/");
656         printHex( macro->stateType );
657 }
658
659 void cliFunc_macroShow( char* args )
660 {
661         // Parse codes from arguments
662         char* curArgs;
663         char* arg1Ptr;
664         char* arg2Ptr = args;
665
666         // Process all args
667         for ( ;; )
668         {
669                 curArgs = arg2Ptr;
670                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
671
672                 // Stop processing args if no more are found
673                 if ( *arg1Ptr == '\0' )
674                         break;
675
676                 // Ignore invalid codes
677                 switch ( arg1Ptr[0] )
678                 {
679                 // Indexed Trigger Macro
680                 case 'T':
681                         macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
682                         break;
683                 // Indexed Result Macro
684                 case 'R':
685                         macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
686                         break;
687                 }
688         }
689 }
690
691 void cliFunc_macroStep( char* args )
692 {
693         // Parse number from argument
694         //  NOTE: Only first argument is used
695         char* arg1Ptr;
696         char* arg2Ptr;
697         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
698
699         // Set the macro step counter, negative int's are cast to uint
700         macroStepCounter = (unsigned int)decToInt( arg1Ptr );
701 }
702