Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

macro.c 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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. // ----- Includes -----
  17. // Compiler Includes
  18. #include <Lib/MacroLib.h>
  19. // Project Includes
  20. #include <cli.h>
  21. #include <led.h>
  22. #include <print.h>
  23. #include <scan_loop.h>
  24. // Keymaps
  25. #include "usb_hid.h"
  26. #include <defaultMap.h>
  27. #include "generatedKeymap.h" // TODO Use actual generated version
  28. // Local Includes
  29. #include "macro.h"
  30. // ----- Function Declarations -----
  31. void cliFunc_capList ( char* args );
  32. void cliFunc_capSelect ( char* args );
  33. void cliFunc_keyHold ( char* args );
  34. void cliFunc_keyPress ( char* args );
  35. void cliFunc_keyRelease( char* args );
  36. void cliFunc_layerList ( char* args );
  37. void cliFunc_layerState( char* args );
  38. void cliFunc_macroDebug( char* args );
  39. void cliFunc_macroList ( char* args );
  40. void cliFunc_macroProc ( char* args );
  41. void cliFunc_macroShow ( char* args );
  42. void cliFunc_macroStep ( char* args );
  43. // ----- Enums -----
  44. // Bit positions are important, passes (correct key) always trump incorrect key votes
  45. typedef enum TriggerMacroVote {
  46. TriggerMacroVote_Release = 0x8, // Correct key
  47. TriggerMacroVote_PassRelease = 0xC, // Correct key (both pass and release)
  48. TriggerMacroVote_Pass = 0x4, // Correct key
  49. TriggerMacroVote_DoNothing = 0x2, // Incorrect key
  50. TriggerMacroVote_Fail = 0x1, // Incorrect key
  51. TriggerMacroVote_Invalid = 0x0, // Invalid state
  52. } TriggerMacroVote;
  53. typedef enum TriggerMacroEval {
  54. TriggerMacroEval_DoNothing,
  55. TriggerMacroEval_DoResult,
  56. TriggerMacroEval_DoResultAndRemove,
  57. TriggerMacroEval_Remove,
  58. } TriggerMacroEval;
  59. typedef enum ResultMacroEval {
  60. ResultMacroEval_DoNothing,
  61. ResultMacroEval_Remove,
  62. } ResultMacroEval;
  63. // ----- Variables -----
  64. // Macro Module command dictionary
  65. const char macroCLIDictName[] = "Macro Module Commands";
  66. const CLIDictItem macroCLIDict[] = {
  67. { "capList", "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
  68. { "capSelect", "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
  69. { "keyHold", "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyHold },
  70. { "keyPress", "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyPress },
  71. { "keyRelease", "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
  72. { "layerList", "List available layers.", cliFunc_layerList },
  73. { "layerState", "Modify specified indexed layer state <layer> <state byte>." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02" NL "\t\t0 Off, 1 Shift, 2 Latch, 4 Lock States", cliFunc_layerState },
  74. { "macroDebug", "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
  75. { "macroList", "List the defined trigger and result macros.", cliFunc_macroList },
  76. { "macroProc", "Pause/Resume macro processing.", cliFunc_macroProc },
  77. { "macroShow", "Show the macro corresponding to the given index." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C", cliFunc_macroShow },
  78. { "macroStep", "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
  79. { 0, 0, 0 } // Null entry for dictionary end
  80. };
  81. // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
  82. uint8_t macroDebugMode = 0;
  83. // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
  84. uint8_t macroPauseMode = 0;
  85. // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
  86. unsigned int macroStepCounter = 0;
  87. // Key Trigger List Buffer
  88. TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
  89. uint8_t macroTriggerListBufferSize = 0;
  90. // Pending Trigger Macro Index List
  91. // * Any trigger macros that need processing from a previous macro processing loop
  92. // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
  93. // Possibly could be calculated by the KLL compiler
  94. // XXX It may be possible to calculate the worst case using the KLL compiler
  95. unsigned int macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
  96. unsigned int macroTriggerMacroPendingListSize = 0;
  97. // Layer Index Stack
  98. // * When modifying layer state and the state is non-0x0, the stack must be adjusted
  99. unsigned int macroLayerIndexStack[ LayerNum ] = { 0 };
  100. unsigned int macroLayerIndexStackSize = 0;
  101. // Pending Result Macro Index List
  102. // * Any result macro that needs processing from a previous macro processing loop
  103. unsigned int macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
  104. unsigned int macroResultMacroPendingListSize = 0;
  105. // ----- Capabilities -----
  106. // Modifies the specified Layer control byte
  107. // Argument #1: Layer Index -> unsigned int
  108. // Argument #2: Toggle byte -> uint8_t
  109. void Macro_layerStateToggle_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  110. {
  111. // Display capability name
  112. if ( stateType == 0xFF && state == 0xFF )
  113. {
  114. print("Macro_layerState(layerIndex,toggleByte)");
  115. return;
  116. }
  117. // Get layer index from arguments
  118. // Cast pointer to uint8_t to unsigned int then access that memory location
  119. unsigned int layer = *(unsigned int*)(&args[0]);
  120. // Get layer toggle byte
  121. uint8_t toggleByte = args[ sizeof(unsigned int) ];
  122. // Is layer in the LayerIndexStack?
  123. uint8_t inLayerIndexStack = 0;
  124. unsigned int stackItem = 0;
  125. while ( stackItem < macroLayerIndexStackSize )
  126. {
  127. // Flag if layer is already in the LayerIndexStack
  128. if ( macroLayerIndexStack[ stackItem ] == layer )
  129. {
  130. inLayerIndexStack = 1;
  131. break;
  132. }
  133. // Increment to next item
  134. stackItem++;
  135. }
  136. // Toggle Layer State Byte
  137. if ( LayerIndex[ layer ].state & toggleByte )
  138. {
  139. // Unset
  140. LayerIndex[ layer ].state &= ~toggleByte;
  141. }
  142. else
  143. {
  144. // Set
  145. LayerIndex[ layer ].state |= toggleByte;
  146. }
  147. // If the layer was not in the LayerIndexStack add it
  148. if ( !inLayerIndexStack )
  149. {
  150. macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
  151. }
  152. // If the layer is in the LayerIndexStack and the state is 0x00, remove
  153. if ( LayerIndex[ layer ].state == 0x00 && inLayerIndexStack )
  154. {
  155. // Remove the layer from the LayerIndexStack
  156. // Using the already positioned stackItem variable from the loop above
  157. while ( stackItem < macroLayerIndexStackSize )
  158. {
  159. macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
  160. stackItem++;
  161. }
  162. // Reduce LayerIndexStack size
  163. macroLayerIndexStackSize--;
  164. }
  165. }
  166. // ----- Functions -----
  167. // Looks up the trigger list for the given scan code (from the active layer)
  168. // NOTE: Calling function must handle the NULL pointer case
  169. unsigned int *Macro_layerLookup( uint8_t scanCode )
  170. {
  171. // If no trigger macro is defined at the given layer, fallthrough to the next layer
  172. for ( unsigned int layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
  173. {
  174. // Lookup Layer
  175. Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
  176. // Check if latch has been pressed for this layer
  177. // XXX Regardless of whether a key is found, the latch is removed on first lookup
  178. uint8_t latch = layer->state & 0x02;
  179. if ( latch )
  180. {
  181. layer->state &= ~0x02;
  182. }
  183. // Only use layer, if state is valid
  184. // XOR each of the state bits
  185. // If only two are enabled, do not use this state
  186. if ( (layer->state & 0x01) ^ (latch>>1) ^ ((layer->state & 0x04)>>2) )
  187. {
  188. // Lookup layer
  189. unsigned int **map = (unsigned int**)layer->triggerMap;
  190. // Determine if layer has key defined
  191. if ( map != 0 && *map[ scanCode ] != 0 )
  192. return map[ scanCode ];
  193. }
  194. }
  195. // Do lookup on default layer
  196. unsigned int **map = (unsigned int**)LayerIndex[0].triggerMap;
  197. // Determine if layer has key defined
  198. if ( map == 0 && *map[ scanCode ] == 0 )
  199. {
  200. erro_msg("Scan Code has no defined Trigger Macro: ");
  201. printHex( scanCode );
  202. return 0;
  203. }
  204. // Return lookup result
  205. return map[ scanCode ];
  206. }
  207. // Update the scancode key state
  208. // States:
  209. // * 0x00 - Off
  210. // * 0x01 - Pressed
  211. // * 0x02 - Held
  212. // * 0x03 - Released
  213. // * 0x04 - Unpressed (this is currently ignored)
  214. inline void Macro_keyState( uint8_t scanCode, uint8_t state )
  215. {
  216. // Only add to macro trigger list if one of three states
  217. switch ( state )
  218. {
  219. case 0x01: // Pressed
  220. case 0x02: // Held
  221. case 0x03: // Released
  222. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  223. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  224. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
  225. macroTriggerListBufferSize++;
  226. break;
  227. }
  228. }
  229. // Update the scancode analog state
  230. // States:
  231. // * 0x00 - Off
  232. // * 0x01 - Released
  233. // * 0x02-0xFF - Analog value (low to high)
  234. inline void Macro_analogState( uint8_t scanCode, uint8_t state )
  235. {
  236. // Only add to macro trigger list if non-off
  237. if ( state != 0x00 )
  238. {
  239. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  240. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  241. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
  242. macroTriggerListBufferSize++;
  243. }
  244. }
  245. // Update led state
  246. // States:
  247. // * 0x00 - Off
  248. // * 0x01 - On
  249. inline void Macro_ledState( uint8_t ledCode, uint8_t state )
  250. {
  251. // Only add to macro trigger list if non-off
  252. if ( state != 0x00 )
  253. {
  254. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
  255. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  256. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
  257. macroTriggerListBufferSize++;
  258. }
  259. }
  260. // Append result macro to pending list, checking for duplicates
  261. // Do nothing if duplicate
  262. inline void Macro_appendResultMacroToPendingList( unsigned int resultMacroIndex )
  263. {
  264. // Iterate through result macro pending list, making sure this macro hasn't been added yet
  265. for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  266. {
  267. // If duplicate found, do nothing
  268. if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
  269. return;
  270. }
  271. // No duplicates found, add to pending list
  272. macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
  273. }
  274. // Determine if long ResultMacro (more than 1 seqence element)
  275. inline uint8_t Macro_isLongResultMacro( ResultMacro *macro )
  276. {
  277. // Check the second sequence combo length
  278. // If non-zero return 1 (long sequence)
  279. // 0 otherwise (short sequence)
  280. return macro->guide[ macro->guide[0] * ResultGuideSize( (ResultGuide*)macro->guide ) ] > 0 ? 1 : 0;
  281. }
  282. // Votes on the given key vs. guide
  283. inline TriggerMacroVote Macro_evalTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  284. {
  285. // Depending on key type
  286. switch ( guide->type )
  287. {
  288. // Normal State Type
  289. case 0x00:
  290. // Depending on the state of the buffered key, make voting decision
  291. // Incorrect key
  292. if ( guide->scanCode != key->scanCode )
  293. {
  294. switch ( key->state )
  295. {
  296. // Wrong key, pressed, fail
  297. case 0x01:
  298. return TriggerMacroVote_Fail;
  299. // Wrong key, held or released, do not pass (no effect)
  300. case 0x02:
  301. case 0x03:
  302. return TriggerMacroVote_DoNothing;
  303. }
  304. }
  305. // Correct key
  306. else
  307. {
  308. switch ( key->state )
  309. {
  310. // Correct key, pressed, possible passing
  311. case 0x01:
  312. return TriggerMacroVote_Pass;
  313. // Correct key, held, possible passing or release
  314. case 0x02:
  315. return TriggerMacroVote_PassRelease;
  316. // Correct key, released, possible release
  317. case 0x03:
  318. return TriggerMacroVote_Release;
  319. }
  320. }
  321. break;
  322. // LED State Type
  323. case 0x01:
  324. erro_print("LED State Type - Not implemented...");
  325. break;
  326. // Analog State Type
  327. case 0x02:
  328. erro_print("Analog State Type - Not implemented...");
  329. break;
  330. // Invalid State Type
  331. default:
  332. erro_print("Invalid State Type. This is a bug.");
  333. break;
  334. }
  335. // XXX Shouldn't reach here
  336. return TriggerMacroVote_Invalid;
  337. }
  338. // Evaluate/Update TriggerMacro
  339. inline TriggerMacroEval Macro_evalTriggerMacro( unsigned int triggerMacroIndex )
  340. {
  341. // Lookup TriggerMacro
  342. TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
  343. // Check if macro has finished and should be incremented sequence elements
  344. if ( macro->state == TriggerMacro_Release )
  345. {
  346. macro->state = TriggerMacro_Waiting;
  347. macro->pos = macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize;
  348. }
  349. // Current Macro position
  350. unsigned int pos = macro->pos;
  351. // Length of the combo being processed
  352. uint8_t comboLength = macro->guide[ pos ];
  353. // If no combo items are left, remove the TriggerMacro from the pending list
  354. if ( comboLength == 0 )
  355. {
  356. return TriggerMacroEval_Remove;
  357. }
  358. // Iterate through the key buffer, comparing to each key in the combo
  359. // If any of the pressed keys do not match, fail the macro
  360. //
  361. // The macro is waiting for input when in the TriggerMacro_Waiting state
  362. // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
  363. // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
  364. // On scan after position increment, change to TriggerMacro_Waiting state
  365. // TODO Add support for system LED states (NumLock, CapsLock, etc.)
  366. // TODO Add support for analog key states
  367. // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
  368. // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
  369. TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
  370. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  371. {
  372. // Lookup key information
  373. TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
  374. // Iterate through the items in the combo, voting the on the key state
  375. TriggerMacroVote vote = TriggerMacroVote_Invalid;
  376. for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
  377. {
  378. // Assign TriggerGuide element (key type, state and scancode)
  379. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
  380. // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
  381. // Also mask all of the non-passing votes
  382. vote |= Macro_evalTriggerMacroVote( keyInfo, guide );
  383. if ( vote >= TriggerMacroVote_Pass )
  384. {
  385. vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
  386. break;
  387. }
  388. }
  389. // After voting, append to overall vote
  390. overallVote |= vote;
  391. }
  392. // Decide new state of macro after voting
  393. // Fail macro, remove from pending list
  394. if ( overallVote & TriggerMacroVote_Fail )
  395. {
  396. return TriggerMacroEval_Remove;
  397. }
  398. // Do nothing, incorrect key is being held or released
  399. else if ( overallVote & TriggerMacroVote_DoNothing )
  400. {
  401. // Just doing nothing :)
  402. }
  403. // If passing and in Waiting state, set macro state to Press
  404. else if ( overallVote & TriggerMacroVote_Pass && macro->state == TriggerMacro_Waiting )
  405. {
  406. macro->state = TriggerMacro_Press;
  407. // If in press state, and this is the final combo, send request for ResultMacro
  408. // Check to see if the result macro only has a single element
  409. // If this result macro has more than 1 key, only send once
  410. // TODO Add option to have macro repeat rate
  411. if ( macro->guide[ pos + comboLength ] == 0 )
  412. {
  413. // Long Macro, only send once (more than 1 sequence item)
  414. // Short Macro (only 1 sequence item)
  415. return Macro_isLongResultMacro( &ResultMacroList[ macro->result ] )
  416. ? TriggerMacroEval_DoResult
  417. : TriggerMacroEval_DoResultAndRemove;
  418. }
  419. }
  420. // If ready for transition and in Press state, set to Waiting and increment combo position
  421. // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
  422. else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
  423. {
  424. macro->state = TriggerMacro_Release;
  425. }
  426. return TriggerMacroEval_DoNothing;
  427. }
  428. // Evaluate/Update ResultMacro
  429. inline ResultMacroEval Macro_evalResultMacro( unsigned int resultMacroIndex )
  430. {
  431. // Lookup ResultMacro
  432. ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
  433. // Current Macro position
  434. unsigned int pos = macro->pos;
  435. // Length of combo being processed
  436. uint8_t comboLength = macro->guide[ pos ];
  437. // If no combo items are left, remove the ResultMacro from the pending list
  438. if ( comboLength == 0 )
  439. {
  440. return ResultMacroEval_Remove;
  441. }
  442. // Function Counter, used to keep track of the combo items processed
  443. unsigned int funcCount = 0;
  444. // Combo Item Position within the guide
  445. unsigned int comboItem = pos + 1;
  446. // Iterate through the Result Combo
  447. while ( funcCount < comboLength )
  448. {
  449. // Assign TriggerGuide element (key type, state and scancode)
  450. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  451. // Do lookup on capability function
  452. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  453. // Call capability
  454. capability( macro->state, macro->stateType, &guide->args );
  455. // Increment counters
  456. funcCount++;
  457. comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
  458. }
  459. // Move to next item in the sequence
  460. macro->pos = comboItem;
  461. // If the ResultMacro is finished, it will be removed on the next iteration
  462. return ResultMacroEval_DoNothing;
  463. }
  464. // Update pending trigger list
  465. void Macro_updateTriggerMacroPendingList()
  466. {
  467. // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
  468. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  469. {
  470. // Lookup Trigger List
  471. unsigned int *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
  472. // Number of Triggers in list
  473. unsigned int triggerListSize = triggerList[0];
  474. // Iterate over triggerList to see if any TriggerMacros need to be added
  475. // First item is the number of items in the TriggerList
  476. for ( unsigned int macro = 1; macro < triggerListSize + 1; macro++ )
  477. {
  478. // Lookup trigger macro index
  479. unsigned int triggerMacroIndex = triggerList[ macro ];
  480. // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
  481. // triggerList needs to be added
  482. unsigned int pending = 0;
  483. for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
  484. {
  485. // Stop scanning if the trigger macro index is found in the pending list
  486. if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
  487. break;
  488. }
  489. // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
  490. // Add it to the list
  491. if ( pending == macroTriggerMacroPendingListSize )
  492. {
  493. macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
  494. }
  495. }
  496. }
  497. }
  498. // Macro Procesing Loop
  499. // Called once per USB buffer send
  500. inline void Macro_process()
  501. {
  502. // Only do one round of macro processing between Output Module timer sends
  503. if ( USBKeys_Sent != 0 )
  504. return;
  505. // If the pause flag is set, only process if the step counter is non-zero
  506. if ( macroPauseMode )
  507. {
  508. if ( macroStepCounter == 0 )
  509. return;
  510. // Proceed, decrementing the step counter
  511. macroStepCounter--;
  512. dbug_print("Macro Step");
  513. }
  514. // Update pending trigger list, before processing TriggerMacros
  515. Macro_updateTriggerMacroPendingList();
  516. // Tail pointer for macroTriggerMacroPendingList
  517. // Macros must be explicitly re-added
  518. unsigned int macroTriggerMacroPendingListTail = 0;
  519. // Iterate through the pending TriggerMacros, processing each of them
  520. for ( unsigned int macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  521. {
  522. switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
  523. {
  524. // Trigger Result Macro (purposely falling through)
  525. case TriggerMacroEval_DoResult:
  526. // Append ResultMacro to PendingList
  527. Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
  528. // Otherwise, just re-add
  529. default:
  530. macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
  531. break;
  532. // Trigger Result Macro and Remove (purposely falling through)
  533. case TriggerMacroEval_DoResultAndRemove:
  534. // Append ResultMacro to PendingList
  535. Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
  536. // Remove Macro from Pending List, nothing to do, removing by default
  537. case TriggerMacroEval_Remove:
  538. break;
  539. }
  540. }
  541. // Update the macroTriggerMacroPendingListSize with the tail pointer
  542. macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
  543. // Tail pointer for macroResultMacroPendingList
  544. // Macros must be explicitly re-added
  545. unsigned int macroResultMacroPendingListTail = 0;
  546. // Iterate through the pending ResultMacros, processing each of them
  547. for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  548. {
  549. switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
  550. {
  551. // Re-add macros to pending list
  552. case ResultMacroEval_DoNothing:
  553. default:
  554. macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
  555. break;
  556. // Remove Macro from Pending List, nothing to do, removing by default
  557. case ResultMacroEval_Remove:
  558. break;
  559. }
  560. }
  561. // Update the macroResultMacroPendingListSize with the tail pointer
  562. macroResultMacroPendingListSize = macroResultMacroPendingListTail;
  563. // Signal buffer that we've used it
  564. Scan_finishedWithMacro( macroTriggerListBufferSize );
  565. // Reset TriggerList buffer
  566. macroTriggerListBufferSize = 0;
  567. // If Macro debug mode is set, clear the USB Buffer
  568. if ( macroDebugMode )
  569. {
  570. USBKeys_Modifiers = 0;
  571. USBKeys_Sent = 0;
  572. }
  573. }
  574. inline void Macro_setup()
  575. {
  576. // Register Macro CLI dictionary
  577. CLI_registerDictionary( macroCLIDict, macroCLIDictName );
  578. // Disable Macro debug mode
  579. macroDebugMode = 0;
  580. // Disable Macro pause flag
  581. macroPauseMode = 0;
  582. // Set Macro step counter to zero
  583. macroStepCounter = 0;
  584. // Make sure macro trigger buffer is empty
  585. macroTriggerListBufferSize = 0;
  586. // Initialize TriggerMacro states
  587. for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
  588. {
  589. TriggerMacroList[ macro ].pos = 0;
  590. TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
  591. }
  592. // Initialize ResultMacro states
  593. for ( unsigned int macro = 0; macro < ResultMacroNum; macro++ )
  594. {
  595. ResultMacroList[ macro ].pos = 0;
  596. ResultMacroList[ macro ].state = 0;
  597. ResultMacroList[ macro ].stateType = 0;
  598. }
  599. }
  600. // ----- CLI Command Functions -----
  601. void cliFunc_capList( char* args )
  602. {
  603. print( NL );
  604. info_msg("Capabilities List");
  605. printHex( CapabilitiesNum );
  606. // Iterate through all of the capabilities and display them
  607. for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
  608. {
  609. print( NL "\t" );
  610. printHex( cap );
  611. print(" - ");
  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[ cap ].func);
  614. capability( 0xFF, 0xFF, 0 );
  615. }
  616. }
  617. void cliFunc_capSelect( char* args )
  618. {
  619. // Parse code from argument
  620. char* curArgs;
  621. char* arg1Ptr;
  622. char* arg2Ptr = args;
  623. // Total number of args to scan (must do a lookup if a keyboard capability is selected)
  624. unsigned int totalArgs = 2; // Always at least two args
  625. unsigned int cap = 0;
  626. // Arguments used for keyboard capability function
  627. unsigned int argSetCount = 0;
  628. uint8_t *argSet = (uint8_t*)args;
  629. // Process all args
  630. for ( unsigned int c = 0; argSetCount < totalArgs; c++ )
  631. {
  632. curArgs = arg2Ptr;
  633. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  634. // Stop processing args if no more are found
  635. // Extra arguments are ignored
  636. if ( *arg1Ptr == '\0' )
  637. break;
  638. // For the first argument, choose the capability
  639. if ( c == 0 ) switch ( arg1Ptr[0] )
  640. {
  641. // Keyboard Capability
  642. case 'K':
  643. // Determine capability index
  644. cap = decToInt( &arg1Ptr[1] );
  645. // Lookup the number of args
  646. totalArgs += CapabilitiesList[ cap ].argCount;
  647. continue;
  648. }
  649. // Because allocating memory isn't doable, and the argument count is arbitrary
  650. // The argument pointer is repurposed as the argument list (much smaller anyways)
  651. argSet[ argSetCount++ ] = (uint8_t)decToInt( arg1Ptr );
  652. // Once all the arguments are prepared, call the keyboard capability function
  653. if ( argSetCount == totalArgs )
  654. {
  655. // Indicate that the capability was called
  656. print( NL );
  657. info_msg("K");
  658. printInt8( cap );
  659. print(" - ");
  660. printHex( argSet[0] );
  661. print(" - ");
  662. printHex( argSet[1] );
  663. print(" - ");
  664. printHex( argSet[2] );
  665. print( "..." NL );
  666. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  667. capability( argSet[0], argSet[1], &argSet[2] );
  668. }
  669. }
  670. }
  671. void cliFunc_keyHold( char* args )
  672. {
  673. // Parse codes from arguments
  674. char* curArgs;
  675. char* arg1Ptr;
  676. char* arg2Ptr = args;
  677. // Process all args
  678. for ( ;; )
  679. {
  680. curArgs = arg2Ptr;
  681. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  682. // Stop processing args if no more are found
  683. if ( *arg1Ptr == '\0' )
  684. break;
  685. // Ignore non-Scancode numbers
  686. switch ( arg1Ptr[0] )
  687. {
  688. // Scancode
  689. case 'S':
  690. Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
  691. break;
  692. }
  693. }
  694. }
  695. void cliFunc_keyPress( char* args )
  696. {
  697. // Parse codes from arguments
  698. char* curArgs;
  699. char* arg1Ptr;
  700. char* arg2Ptr = args;
  701. // Process all args
  702. for ( ;; )
  703. {
  704. curArgs = arg2Ptr;
  705. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  706. // Stop processing args if no more are found
  707. if ( *arg1Ptr == '\0' )
  708. break;
  709. // Ignore non-Scancode numbers
  710. switch ( arg1Ptr[0] )
  711. {
  712. // Scancode
  713. case 'S':
  714. Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  715. break;
  716. }
  717. }
  718. }
  719. void cliFunc_keyRelease( char* args )
  720. {
  721. // Parse codes from arguments
  722. char* curArgs;
  723. char* arg1Ptr;
  724. char* arg2Ptr = args;
  725. // Process all args
  726. for ( ;; )
  727. {
  728. curArgs = arg2Ptr;
  729. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  730. // Stop processing args if no more are found
  731. if ( *arg1Ptr == '\0' )
  732. break;
  733. // Ignore non-Scancode numbers
  734. switch ( arg1Ptr[0] )
  735. {
  736. // Scancode
  737. case 'S':
  738. Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  739. break;
  740. }
  741. }
  742. }
  743. void cliFunc_layerList( char* args )
  744. {
  745. print( NL );
  746. info_msg("Layer List");
  747. // Iterate through all of the layers and display them
  748. for ( unsigned int layer = 0; layer < LayerNum; layer++ )
  749. {
  750. print( NL "\t" );
  751. printHex( layer );
  752. print(" - ");
  753. // Display layer name
  754. dPrint( (char*)LayerIndex[ layer ].name );
  755. // Default map
  756. if ( layer == 0 )
  757. print(" \033[1m(default)\033[0m");
  758. // Layer State
  759. print( NL "\t\t Layer State: " );
  760. printHex( LayerIndex[ layer ].state );
  761. // Max Index
  762. print(" Max Index: ");
  763. printHex( LayerIndex[ layer ].max );
  764. }
  765. }
  766. void cliFunc_layerState( char* args )
  767. {
  768. // Parse codes from arguments
  769. char* curArgs;
  770. char* arg1Ptr;
  771. char* arg2Ptr = args;
  772. uint8_t arg1 = 0;
  773. uint8_t arg2 = 0;
  774. // Process first two args
  775. for ( uint8_t c = 0; c < 2; c++ )
  776. {
  777. curArgs = arg2Ptr;
  778. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  779. // Stop processing args if no more are found
  780. if ( *arg1Ptr == '\0' )
  781. break;
  782. switch ( c )
  783. {
  784. // First argument (e.g. L1)
  785. case 0:
  786. if ( arg1Ptr[0] != 'L' )
  787. return;
  788. arg1 = (uint8_t)decToInt( &arg1Ptr[1] );
  789. break;
  790. // Second argument (e.g. 4)
  791. case 1:
  792. arg2 = (uint8_t)decToInt( arg1Ptr );
  793. // Display operation (to indicate that it worked)
  794. print( NL );
  795. info_msg("Setting Layer L");
  796. printInt8( arg1 );
  797. print(" to - ");
  798. printHex( arg2 );
  799. // Set the layer state
  800. LayerIndex[ arg1 ].state = arg2;
  801. break;
  802. }
  803. }
  804. }
  805. void cliFunc_macroDebug( char* args )
  806. {
  807. // Toggle macro debug mode
  808. macroDebugMode = macroDebugMode ? 0 : 1;
  809. print( NL );
  810. info_msg("Macro Debug Mode: ");
  811. printInt8( macroDebugMode );
  812. }
  813. void cliFunc_macroList( char* args )
  814. {
  815. // Show pending key events
  816. print( NL );
  817. info_msg("Pending Key Events: ");
  818. printInt16( (uint16_t)macroTriggerListBufferSize );
  819. print(" : ");
  820. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  821. {
  822. printHex( macroTriggerListBuffer[ key ].scanCode );
  823. print(" ");
  824. }
  825. // Show pending trigger macros
  826. print( NL );
  827. info_msg("Pending Trigger Macros: ");
  828. printInt16( (uint16_t)macroTriggerMacroPendingListSize );
  829. print(" : ");
  830. for ( unsigned int macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  831. {
  832. printHex( macroTriggerMacroPendingList[ macro ] );
  833. print(" ");
  834. }
  835. // Show pending result macros
  836. print( NL );
  837. info_msg("Pending Result Macros: ");
  838. printInt16( (uint16_t)macroResultMacroPendingListSize );
  839. print(" : ");
  840. for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  841. {
  842. printHex( macroResultMacroPendingList[ macro ] );
  843. print(" ");
  844. }
  845. // Show available trigger macro indices
  846. print( NL );
  847. info_msg("Trigger Macros Range: T0 -> T");
  848. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  849. // Show available result macro indices
  850. print( NL );
  851. info_msg("Result Macros Range: R0 -> R");
  852. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  853. // Show Trigger to Result Macro Links
  854. print( NL );
  855. info_msg("Trigger : Result Macro Pairs");
  856. for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
  857. {
  858. print( NL );
  859. print("\tT");
  860. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  861. print(" : R");
  862. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  863. }
  864. }
  865. void cliFunc_macroProc( char* args )
  866. {
  867. // Toggle macro pause mode
  868. macroPauseMode = macroPauseMode ? 0 : 1;
  869. print( NL );
  870. info_msg("Macro Processing Mode: ");
  871. printInt8( macroPauseMode );
  872. }
  873. void macroDebugShowTrigger( unsigned int index )
  874. {
  875. // Only proceed if the macro exists
  876. if ( index >= TriggerMacroNum )
  877. return;
  878. // Trigger Macro Show
  879. TriggerMacro *macro = &TriggerMacroList[ index ];
  880. print( NL );
  881. info_msg("Trigger Macro Index: ");
  882. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  883. print( NL );
  884. // Read the comboLength for combo in the sequence (sequence of combos)
  885. unsigned int pos = 0;
  886. uint8_t comboLength = macro->guide[ pos ];
  887. // Iterate through and interpret the guide
  888. while ( comboLength != 0 )
  889. {
  890. // Initial position of the combo
  891. unsigned int comboPos = ++pos;
  892. // Iterate through the combo
  893. while ( pos < comboLength * TriggerGuideSize + comboPos )
  894. {
  895. // Assign TriggerGuide element (key type, state and scancode)
  896. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  897. // Display guide information about trigger key
  898. printHex( guide->scanCode );
  899. print("|");
  900. printHex( guide->type );
  901. print("|");
  902. printHex( guide->state );
  903. // Increment position
  904. pos += TriggerGuideSize;
  905. // Only show combo separator if there are combos left in the sequence element
  906. if ( pos < comboLength * TriggerGuideSize + comboPos )
  907. print("+");
  908. }
  909. // Read the next comboLength
  910. comboLength = macro->guide[ pos ];
  911. // Only show sequence separator if there is another combo to process
  912. if ( comboLength != 0 )
  913. print(";");
  914. }
  915. // Display current position
  916. print( NL "Position: " );
  917. printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
  918. // Display result macro index
  919. print( NL "Result Macro Index: " );
  920. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  921. }
  922. void macroDebugShowResult( unsigned int index )
  923. {
  924. // Only proceed if the macro exists
  925. if ( index >= ResultMacroNum )
  926. return;
  927. // Trigger Macro Show
  928. ResultMacro *macro = &ResultMacroList[ index ];
  929. print( NL );
  930. info_msg("Result Macro Index: ");
  931. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  932. print( NL );
  933. // Read the comboLength for combo in the sequence (sequence of combos)
  934. unsigned int pos = 0;
  935. uint8_t comboLength = macro->guide[ pos++ ];
  936. // Iterate through and interpret the guide
  937. while ( comboLength != 0 )
  938. {
  939. // Function Counter, used to keep track of the combos processed
  940. unsigned int funcCount = 0;
  941. // Iterate through the combo
  942. while ( funcCount < comboLength )
  943. {
  944. // Assign TriggerGuide element (key type, state and scancode)
  945. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  946. // Display Function Index
  947. printHex( guide->index );
  948. print("|");
  949. // Display Function Ptr Address
  950. printHex( (unsigned int)CapabilitiesList[ guide->index ].func );
  951. print("|");
  952. // Display/Lookup Capability Name (utilize debug mode of capability)
  953. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  954. capability( 0xFF, 0xFF, 0 );
  955. // Display Argument(s)
  956. print("(");
  957. for ( unsigned int arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  958. {
  959. // Arguments are only 8 bit values
  960. printHex( (&guide->args)[ arg ] );
  961. // Only show arg separator if there are args left
  962. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  963. print(",");
  964. }
  965. print(")");
  966. // Increment position
  967. pos += ResultGuideSize( guide );
  968. // Increment function count
  969. funcCount++;
  970. // Only show combo separator if there are combos left in the sequence element
  971. if ( funcCount < comboLength )
  972. print("+");
  973. }
  974. // Read the next comboLength
  975. comboLength = macro->guide[ pos++ ];
  976. // Only show sequence separator if there is another combo to process
  977. if ( comboLength != 0 )
  978. print(";");
  979. }
  980. // Display current position
  981. print( NL "Position: " );
  982. printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
  983. // Display final trigger state/type
  984. print( NL "Final Trigger State (State/Type): " );
  985. printHex( macro->state );
  986. print("/");
  987. printHex( macro->stateType );
  988. }
  989. void cliFunc_macroShow( char* args )
  990. {
  991. // Parse codes from arguments
  992. char* curArgs;
  993. char* arg1Ptr;
  994. char* arg2Ptr = args;
  995. // Process all args
  996. for ( ;; )
  997. {
  998. curArgs = arg2Ptr;
  999. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1000. // Stop processing args if no more are found
  1001. if ( *arg1Ptr == '\0' )
  1002. break;
  1003. // Ignore invalid codes
  1004. switch ( arg1Ptr[0] )
  1005. {
  1006. // Indexed Trigger Macro
  1007. case 'T':
  1008. macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
  1009. break;
  1010. // Indexed Result Macro
  1011. case 'R':
  1012. macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. void cliFunc_macroStep( char* args )
  1018. {
  1019. // Parse number from argument
  1020. // NOTE: Only first argument is used
  1021. char* arg1Ptr;
  1022. char* arg2Ptr;
  1023. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  1024. // Default to 1, if no argument given
  1025. unsigned int count = (unsigned int)decToInt( arg1Ptr );
  1026. if ( count == 0 )
  1027. count = 1;
  1028. // Set the macro step counter, negative int's are cast to uint
  1029. macroStepCounter = count;
  1030. }