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 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  1. /* Copyright (C) 2014-2015 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 <generatedKeymap.h> // Generated using kll at compile time, in build directory
  27. // Connect Includes
  28. #if defined(ConnectEnabled_define)
  29. #include <connect_scan.h>
  30. #endif
  31. // Local Includes
  32. #include "macro.h"
  33. // ----- Function Declarations -----
  34. void cliFunc_capList ( char* args );
  35. void cliFunc_capSelect ( char* args );
  36. void cliFunc_keyHold ( char* args );
  37. void cliFunc_keyPress ( char* args );
  38. void cliFunc_keyRelease( char* args );
  39. void cliFunc_layerDebug( char* args );
  40. void cliFunc_layerList ( char* args );
  41. void cliFunc_layerState( char* args );
  42. void cliFunc_macroDebug( char* args );
  43. void cliFunc_macroList ( char* args );
  44. void cliFunc_macroProc ( char* args );
  45. void cliFunc_macroShow ( char* args );
  46. void cliFunc_macroStep ( char* args );
  47. // ----- Enums -----
  48. // Bit positions are important, passes (correct key) always trump incorrect key votes
  49. typedef enum TriggerMacroVote {
  50. TriggerMacroVote_Release = 0x10, // Correct key
  51. TriggerMacroVote_PassRelease = 0x18, // Correct key (both pass and release)
  52. TriggerMacroVote_Pass = 0x8, // Correct key
  53. TriggerMacroVote_DoNothingRelease = 0x4, // Incorrect key
  54. TriggerMacroVote_DoNothing = 0x2, // Incorrect key
  55. TriggerMacroVote_Fail = 0x1, // Incorrect key
  56. TriggerMacroVote_Invalid = 0x0, // Invalid state
  57. } TriggerMacroVote;
  58. typedef enum TriggerMacroEval {
  59. TriggerMacroEval_DoNothing,
  60. TriggerMacroEval_DoResult,
  61. TriggerMacroEval_DoResultAndRemove,
  62. TriggerMacroEval_Remove,
  63. } TriggerMacroEval;
  64. typedef enum ResultMacroEval {
  65. ResultMacroEval_DoNothing,
  66. ResultMacroEval_Remove,
  67. } ResultMacroEval;
  68. // ----- Variables -----
  69. // Macro Module command dictionary
  70. CLIDict_Entry( capList, "Prints an indexed list of all non USB keycode capabilities." );
  71. CLIDict_Entry( capSelect, "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B" );
  72. CLIDict_Entry( keyHold, "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  73. CLIDict_Entry( keyPress, "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  74. CLIDict_Entry( keyRelease, "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  75. CLIDict_Entry( layerDebug, "Layer debug mode. Shows layer stack and any changes." );
  76. CLIDict_Entry( layerList, "List available layers." );
  77. CLIDict_Entry( 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" );
  78. CLIDict_Entry( macroDebug, "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes." );
  79. CLIDict_Entry( macroList, "List the defined trigger and result macros." );
  80. CLIDict_Entry( macroProc, "Pause/Resume macro processing." );
  81. CLIDict_Entry( 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" );
  82. CLIDict_Entry( macroStep, "Do N macro processing steps. Defaults to 1." );
  83. CLIDict_Def( macroCLIDict, "Macro Module Commands" ) = {
  84. CLIDict_Item( capList ),
  85. CLIDict_Item( capSelect ),
  86. CLIDict_Item( keyHold ),
  87. CLIDict_Item( keyPress ),
  88. CLIDict_Item( keyRelease ),
  89. CLIDict_Item( layerDebug ),
  90. CLIDict_Item( layerList ),
  91. CLIDict_Item( layerState ),
  92. CLIDict_Item( macroDebug ),
  93. CLIDict_Item( macroList ),
  94. CLIDict_Item( macroProc ),
  95. CLIDict_Item( macroShow ),
  96. CLIDict_Item( macroStep ),
  97. { 0, 0, 0 } // Null entry for dictionary end
  98. };
  99. // Layer debug flag - If set, displays any changes to layers and the full layer stack on change
  100. uint8_t layerDebugMode = 0;
  101. // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
  102. uint8_t macroDebugMode = 0;
  103. // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
  104. uint8_t macroPauseMode = 0;
  105. // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
  106. uint16_t macroStepCounter = 0;
  107. // Key Trigger List Buffer and Layer Cache
  108. // The layer cache is set on press only, hold and release events refer to the value set on press
  109. TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
  110. uint8_t macroTriggerListBufferSize = 0;
  111. var_uint_t macroTriggerListLayerCache[ MaxScanCode ];
  112. // Pending Trigger Macro Index List
  113. // * Any trigger macros that need processing from a previous macro processing loop
  114. // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
  115. // Possibly could be calculated by the KLL compiler
  116. // XXX It may be possible to calculate the worst case using the KLL compiler
  117. uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
  118. uint16_t macroTriggerMacroPendingListSize = 0;
  119. // Layer Index Stack
  120. // * When modifying layer state and the state is non-0x0, the stack must be adjusted
  121. uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
  122. uint16_t macroLayerIndexStackSize = 0;
  123. // Pending Result Macro Index List
  124. // * Any result macro that needs processing from a previous macro processing loop
  125. uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
  126. uint16_t macroResultMacroPendingListSize = 0;
  127. // Interconnect ScanCode Cache
  128. #if defined(ConnectEnabled_define)
  129. // TODO This can be shrunk by the size of the max node 0 ScanCode
  130. TriggerGuide macroInterconnectCache[ MaxScanCode ];
  131. uint8_t macroInterconnectCacheSize = 0;
  132. #endif
  133. // ----- Capabilities -----
  134. // Sets the given layer with the specified layerState
  135. void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
  136. {
  137. // Ignore if layer does not exist
  138. if ( layer >= LayerNum )
  139. return;
  140. // Is layer in the LayerIndexStack?
  141. uint8_t inLayerIndexStack = 0;
  142. uint16_t stackItem = 0;
  143. while ( stackItem < macroLayerIndexStackSize )
  144. {
  145. // Flag if layer is already in the LayerIndexStack
  146. if ( macroLayerIndexStack[ stackItem ] == layer )
  147. {
  148. inLayerIndexStack = 1;
  149. break;
  150. }
  151. // Increment to next item
  152. stackItem++;
  153. }
  154. // Toggle Layer State Byte
  155. if ( LayerState[ layer ] & layerState )
  156. {
  157. // Unset
  158. LayerState[ layer ] &= ~layerState;
  159. }
  160. else
  161. {
  162. // Set
  163. LayerState[ layer ] |= layerState;
  164. }
  165. // If the layer was not in the LayerIndexStack add it
  166. if ( !inLayerIndexStack )
  167. {
  168. macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
  169. }
  170. // If the layer is in the LayerIndexStack and the state is 0x00, remove
  171. if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
  172. {
  173. // Remove the layer from the LayerIndexStack
  174. // Using the already positioned stackItem variable from the loop above
  175. while ( stackItem < macroLayerIndexStackSize )
  176. {
  177. macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
  178. stackItem++;
  179. }
  180. // Reduce LayerIndexStack size
  181. macroLayerIndexStackSize--;
  182. }
  183. // Layer Debug Mode
  184. if ( layerDebugMode )
  185. {
  186. dbug_msg("Layer ");
  187. // Iterate over each of the layers displaying the state as a hex value
  188. for ( uint16_t index = 0; index < LayerNum; index++ )
  189. {
  190. printHex_op( LayerState[ index ], 0 );
  191. }
  192. // Always show the default layer (it's always 0)
  193. print(" 0");
  194. // Iterate over the layer stack starting from the bottom of the stack
  195. for ( uint16_t index = macroLayerIndexStackSize; index > 0; index-- )
  196. {
  197. print(":");
  198. printHex_op( macroLayerIndexStack[ index - 1 ], 0 );
  199. }
  200. print( NL );
  201. }
  202. }
  203. // Modifies the specified Layer control byte
  204. // Argument #1: Layer Index -> uint16_t
  205. // Argument #2: Layer State -> uint8_t
  206. void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  207. {
  208. // Display capability name
  209. if ( stateType == 0xFF && state == 0xFF )
  210. {
  211. print("Macro_layerState(layerIndex,layerState)");
  212. return;
  213. }
  214. // Only use capability on press or release
  215. // TODO Analog
  216. // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
  217. if ( stateType == 0x00 && state == 0x02 ) // Hold condition
  218. return;
  219. // Get layer index from arguments
  220. // Cast pointer to uint8_t to uint16_t then access that memory location
  221. uint16_t layer = *(uint16_t*)(&args[0]);
  222. // Get layer toggle byte
  223. uint8_t layerState = args[ sizeof(uint16_t) ];
  224. Macro_layerState( state, stateType, layer, layerState );
  225. }
  226. // Latches given layer
  227. // Argument #1: Layer Index -> uint16_t
  228. void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  229. {
  230. // Display capability name
  231. if ( stateType == 0xFF && state == 0xFF )
  232. {
  233. print("Macro_layerLatch(layerIndex)");
  234. return;
  235. }
  236. // Only use capability on press
  237. // TODO Analog
  238. if ( stateType == 0x00 && state != 0x03 ) // Only on release
  239. return;
  240. // Get layer index from arguments
  241. // Cast pointer to uint8_t to uint16_t then access that memory location
  242. uint16_t layer = *(uint16_t*)(&args[0]);
  243. Macro_layerState( state, stateType, layer, 0x02 );
  244. }
  245. // Locks given layer
  246. // Argument #1: Layer Index -> uint16_t
  247. void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  248. {
  249. // Display capability name
  250. if ( stateType == 0xFF && state == 0xFF )
  251. {
  252. print("Macro_layerLock(layerIndex)");
  253. return;
  254. }
  255. // Only use capability on press
  256. // TODO Analog
  257. // XXX Could also be on release, but that's sorta dumb -HaaTa
  258. if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
  259. return;
  260. // Get layer index from arguments
  261. // Cast pointer to uint8_t to uint16_t then access that memory location
  262. uint16_t layer = *(uint16_t*)(&args[0]);
  263. Macro_layerState( state, stateType, layer, 0x04 );
  264. }
  265. // Shifts given layer
  266. // Argument #1: Layer Index -> uint16_t
  267. void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  268. {
  269. // Display capability name
  270. if ( stateType == 0xFF && state == 0xFF )
  271. {
  272. print("Macro_layerShift(layerIndex)");
  273. return;
  274. }
  275. // Only use capability on press or release
  276. // TODO Analog
  277. if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
  278. return;
  279. // Get layer index from arguments
  280. // Cast pointer to uint8_t to uint16_t then access that memory location
  281. uint16_t layer = *(uint16_t*)(&args[0]);
  282. Macro_layerState( state, stateType, layer, 0x01 );
  283. }
  284. // ----- Functions -----
  285. // Looks up the trigger list for the given scan code (from the active layer)
  286. // NOTE: Calling function must handle the NULL pointer case
  287. nat_ptr_t *Macro_layerLookup( TriggerGuide *guide, uint8_t latch_expire )
  288. {
  289. uint8_t scanCode = guide->scanCode;
  290. // TODO Analog
  291. // If a normal key, and not pressed, do a layer cache lookup
  292. if ( guide->type == 0x00 && guide->state != 0x01 )
  293. {
  294. // Cached layer
  295. var_uint_t cachedLayer = macroTriggerListLayerCache[ scanCode ];
  296. // Lookup map, then layer
  297. nat_ptr_t **map = (nat_ptr_t**)LayerIndex[ cachedLayer ].triggerMap;
  298. const Layer *layer = &LayerIndex[ cachedLayer ];
  299. return map[ scanCode - layer->first ];
  300. }
  301. // If no trigger macro is defined at the given layer, fallthrough to the next layer
  302. for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
  303. {
  304. // Lookup Layer
  305. const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
  306. // Check if latch has been pressed for this layer
  307. // XXX Regardless of whether a key is found, the latch is removed on first lookup
  308. uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
  309. if ( latch && latch_expire )
  310. {
  311. Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
  312. }
  313. // Only use layer, if state is valid
  314. // XOR each of the state bits
  315. // If only two are enabled, do not use this state
  316. if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
  317. {
  318. // Lookup layer
  319. nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
  320. // Determine if layer has key defined
  321. // Make sure scanCode is between layer first and last scancodes
  322. if ( map != 0
  323. && scanCode <= layer->last
  324. && scanCode >= layer->first
  325. && *map[ scanCode - layer->first ] != 0 )
  326. {
  327. // Set the layer cache
  328. macroTriggerListLayerCache[ scanCode ] = macroLayerIndexStack[ layerIndex ];
  329. return map[ scanCode - layer->first ];
  330. }
  331. }
  332. }
  333. // Do lookup on default layer
  334. nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
  335. // Lookup default layer
  336. const Layer *layer = &LayerIndex[0];
  337. // Make sure scanCode is between layer first and last scancodes
  338. if ( map != 0
  339. && scanCode <= layer->last
  340. && scanCode >= layer->first
  341. && *map[ scanCode - layer->first ] != 0 )
  342. {
  343. // Set the layer cache to default map
  344. macroTriggerListLayerCache[ scanCode ] = 0;
  345. return map[ scanCode - layer->first ];
  346. }
  347. // Otherwise no defined Trigger Macro
  348. erro_msg("Scan Code has no defined Trigger Macro: ");
  349. printHex( scanCode );
  350. print( NL );
  351. return 0;
  352. }
  353. // Add an interconnect ScanCode
  354. // These are handled differently (less information is sent, hold/off states must be assumed)
  355. #if defined(ConnectEnabled_define)
  356. inline void Macro_interconnectAdd( void *trigger_ptr )
  357. {
  358. TriggerGuide *trigger = (TriggerGuide*)trigger_ptr;
  359. // Error checking
  360. uint8_t error = 0;
  361. switch ( trigger->type )
  362. {
  363. case 0x00: // Normal key
  364. switch ( trigger->state )
  365. {
  366. case 0x00:
  367. case 0x01:
  368. case 0x02:
  369. case 0x03:
  370. break;
  371. default:
  372. erro_msg("Invalid key state - ");
  373. error = 1;
  374. break;
  375. }
  376. break;
  377. // Invalid TriggerGuide type
  378. default:
  379. erro_msg("Invalid type - ");
  380. error = 1;
  381. break;
  382. }
  383. // Check if ScanCode is out of range
  384. if ( scanCode > MaxScanCode )
  385. {
  386. warn_msg("ScanCode is out of range/not defined - ");
  387. error = 1;
  388. }
  389. // Display TriggerGuide
  390. if ( error )
  391. {
  392. printHex( trigger->type );
  393. print(" ");
  394. printHex( trigger->state );
  395. print(" ");
  396. printHex( trigger->scanCode );
  397. print( NL );
  398. return;
  399. }
  400. // Add trigger to the Interconnect Cache
  401. // During each processing loop, a scancode may be re-added depending on it's state
  402. for ( uint8_t c = 0; c < macroInterconnectCacheSize; c++ )
  403. {
  404. // Check if the same ScanCode
  405. if ( macroInterconnectCache[ c ].scanCode == trigger->scanCode )
  406. {
  407. // Update the state
  408. macroInterconnectCache[ c ].state = trigger->state;
  409. return;
  410. }
  411. }
  412. // If not in the list, add it
  413. macroInterconnectCache[ macroInterconnectCacheSize++ ] = *trigger;
  414. }
  415. #endif
  416. // Update the scancode key state
  417. // States:
  418. // * 0x00 - Off
  419. // * 0x01 - Pressed
  420. // * 0x02 - Held
  421. // * 0x03 - Released
  422. // * 0x04 - Unpressed (this is currently ignored)
  423. inline void Macro_keyState( uint8_t scanCode, uint8_t state )
  424. {
  425. #if defined(ConnectEnabled_define)
  426. // Only compile in if a Connect node module is available
  427. if ( !Connect_master )
  428. {
  429. // ScanCodes are only added if there was a state change (on/off)
  430. switch ( state )
  431. {
  432. case 0x00: // Off
  433. case 0x02: // Held
  434. return;
  435. }
  436. }
  437. #endif
  438. // Only add to macro trigger list if one of three states
  439. switch ( state )
  440. {
  441. case 0x01: // Pressed
  442. case 0x02: // Held
  443. case 0x03: // Released
  444. // Check if ScanCode is out of range
  445. if ( scanCode > MaxScanCode )
  446. {
  447. warn_msg("ScanCode is out of range/not defined: ");
  448. printHex( scanCode );
  449. print( NL );
  450. return;
  451. }
  452. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  453. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  454. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
  455. macroTriggerListBufferSize++;
  456. break;
  457. }
  458. }
  459. // Update the scancode analog state
  460. // States:
  461. // * 0x00 - Off
  462. // * 0x01 - Released
  463. // * 0x02-0xFF - Analog value (low to high)
  464. inline void Macro_analogState( uint8_t scanCode, uint8_t state )
  465. {
  466. // Only add to macro trigger list if non-off
  467. // TODO Handle change for interconnect
  468. if ( state != 0x00 )
  469. {
  470. // Check if ScanCode is out of range
  471. if ( scanCode > MaxScanCode )
  472. {
  473. warn_msg("ScanCode is out of range/not defined: ");
  474. printHex( scanCode );
  475. print( NL );
  476. return;
  477. }
  478. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  479. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  480. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
  481. macroTriggerListBufferSize++;
  482. }
  483. }
  484. // Update led state
  485. // States:
  486. // * 0x00 - Off
  487. // * 0x01 - On
  488. inline void Macro_ledState( uint8_t ledCode, uint8_t state )
  489. {
  490. // Only add to macro trigger list if non-off
  491. // TODO Handle change for interconnect
  492. if ( state != 0x00 )
  493. {
  494. // Check if LedCode is out of range
  495. // TODO
  496. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
  497. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  498. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
  499. macroTriggerListBufferSize++;
  500. }
  501. }
  502. // Append result macro to pending list, checking for duplicates
  503. // Do nothing if duplicate
  504. inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
  505. {
  506. // Lookup result macro index
  507. var_uint_t resultMacroIndex = triggerMacro->result;
  508. // Iterate through result macro pending list, making sure this macro hasn't been added yet
  509. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  510. {
  511. // If duplicate found, do nothing
  512. if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
  513. return;
  514. }
  515. // No duplicates found, add to pending list
  516. macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
  517. // Lookup scanCode of the last key in the last combo
  518. var_uint_t pos = 0;
  519. for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
  520. {
  521. pos += TriggerGuideSize * comboLength + 1;
  522. comboLength = triggerMacro->guide[ pos ];
  523. }
  524. uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
  525. // Lookup scanCode in buffer list for the current state and stateType
  526. for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
  527. {
  528. if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
  529. {
  530. ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
  531. ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
  532. }
  533. }
  534. // Reset the macro position
  535. ResultMacroRecordList[ resultMacroIndex ].pos = 0;
  536. }
  537. // Determine if long ResultMacro (more than 1 seqence element)
  538. inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
  539. {
  540. // Check the second sequence combo length
  541. // If non-zero return non-zero (long sequence)
  542. // 0 otherwise (short sequence)
  543. var_uint_t position = 1;
  544. for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
  545. position += ResultGuideSize( (ResultGuide*)&macro->guide[ position ] );
  546. return macro->guide[ position ];
  547. }
  548. // Determine if long TriggerMacro (more than 1 sequence element)
  549. inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
  550. {
  551. // Check the second sequence combo length
  552. // If non-zero return non-zero (long sequence)
  553. // 0 otherwise (short sequence)
  554. return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
  555. }
  556. // Votes on the given key vs. guide, short macros
  557. inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  558. {
  559. // Depending on key type
  560. switch ( guide->type )
  561. {
  562. // Normal State Type
  563. case 0x00:
  564. // For short TriggerMacros completely ignore incorrect keys
  565. if ( guide->scanCode == key->scanCode )
  566. {
  567. switch ( key->state )
  568. {
  569. // Correct key, pressed, possible passing
  570. case 0x01:
  571. return TriggerMacroVote_Pass;
  572. // Correct key, held, possible passing or release
  573. case 0x02:
  574. return TriggerMacroVote_PassRelease;
  575. // Correct key, released, possible release
  576. case 0x03:
  577. return TriggerMacroVote_Release;
  578. }
  579. }
  580. return TriggerMacroVote_DoNothing;
  581. // LED State Type
  582. case 0x01:
  583. erro_print("LED State Type - Not implemented...");
  584. break;
  585. // Analog State Type
  586. case 0x02:
  587. erro_print("Analog State Type - Not implemented...");
  588. break;
  589. // Invalid State Type
  590. default:
  591. erro_print("Invalid State Type. This is a bug.");
  592. break;
  593. }
  594. // XXX Shouldn't reach here
  595. return TriggerMacroVote_Invalid;
  596. }
  597. // Votes on the given key vs. guide, long macros
  598. // A long macro is defined as a guide with more than 1 combo
  599. inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  600. {
  601. // Depending on key type
  602. switch ( guide->type )
  603. {
  604. // Normal State Type
  605. case 0x00:
  606. // Depending on the state of the buffered key, make voting decision
  607. // Incorrect key
  608. if ( guide->scanCode != key->scanCode )
  609. {
  610. switch ( key->state )
  611. {
  612. // Wrong key, pressed, fail
  613. case 0x01:
  614. return TriggerMacroVote_Fail;
  615. // Wrong key, held, do not pass (no effect)
  616. case 0x02:
  617. return TriggerMacroVote_DoNothing;
  618. // Wrong key released, fail out if pos == 0
  619. case 0x03:
  620. return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
  621. }
  622. }
  623. // Correct key
  624. else
  625. {
  626. switch ( key->state )
  627. {
  628. // Correct key, pressed, possible passing
  629. case 0x01:
  630. return TriggerMacroVote_Pass;
  631. // Correct key, held, possible passing or release
  632. case 0x02:
  633. return TriggerMacroVote_PassRelease;
  634. // Correct key, released, possible release
  635. case 0x03:
  636. return TriggerMacroVote_Release;
  637. }
  638. }
  639. break;
  640. // LED State Type
  641. case 0x01:
  642. erro_print("LED State Type - Not implemented...");
  643. break;
  644. // Analog State Type
  645. case 0x02:
  646. erro_print("Analog State Type - Not implemented...");
  647. break;
  648. // Invalid State Type
  649. default:
  650. erro_print("Invalid State Type. This is a bug.");
  651. break;
  652. }
  653. // XXX Shouldn't reach here
  654. return TriggerMacroVote_Invalid;
  655. }
  656. // Evaluate/Update TriggerMacro
  657. TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
  658. {
  659. // Lookup TriggerMacro
  660. const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
  661. TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
  662. // Check if macro has finished and should be incremented sequence elements
  663. if ( record->state == TriggerMacro_Release )
  664. {
  665. record->state = TriggerMacro_Waiting;
  666. record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
  667. }
  668. // Current Macro position
  669. var_uint_t pos = record->pos;
  670. // Length of the combo being processed
  671. uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
  672. // If no combo items are left, remove the TriggerMacro from the pending list
  673. if ( comboLength == 0 )
  674. {
  675. return TriggerMacroEval_Remove;
  676. }
  677. // Check if this is a long Trigger Macro
  678. uint8_t longMacro = Macro_isLongTriggerMacro( macro );
  679. // Iterate through the items in the combo, voting the on the key state
  680. // If any of the pressed keys do not match, fail the macro
  681. //
  682. // The macro is waiting for input when in the TriggerMacro_Waiting state
  683. // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
  684. // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
  685. // On scan after position increment, change to TriggerMacro_Waiting state
  686. // TODO Add support for system LED states (NumLock, CapsLock, etc.)
  687. // TODO Add support for analog key states
  688. // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
  689. // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
  690. TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
  691. for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
  692. {
  693. // Assign TriggerGuide element (key type, state and scancode)
  694. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
  695. TriggerMacroVote vote = TriggerMacroVote_Invalid;
  696. // Iterate through the key buffer, comparing to each key in the combo
  697. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  698. {
  699. // Lookup key information
  700. TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
  701. // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
  702. // Also mask all of the non-passing votes
  703. vote |= longMacro
  704. ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
  705. : Macro_evalShortTriggerMacroVote( keyInfo, guide );
  706. if ( vote >= TriggerMacroVote_Pass )
  707. {
  708. vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
  709. break;
  710. }
  711. }
  712. // If no pass vote was found after scanning all of the keys
  713. // Fail the combo, if this is a short macro (long macros already will have a fail vote)
  714. if ( !longMacro && vote < TriggerMacroVote_Pass )
  715. vote |= TriggerMacroVote_Fail;
  716. // After voting, append to overall vote
  717. overallVote |= vote;
  718. }
  719. // If no pass vote was found after scanning the entire combo
  720. // And this is the first position in the combo, just remove it (nothing important happened)
  721. if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
  722. overallVote |= TriggerMacroVote_Fail;
  723. // Decide new state of macro after voting
  724. // Fail macro, remove from pending list
  725. if ( overallVote & TriggerMacroVote_Fail )
  726. {
  727. return TriggerMacroEval_Remove;
  728. }
  729. // Do nothing, incorrect key is being held or released
  730. else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
  731. {
  732. // Just doing nothing :)
  733. }
  734. // If ready for transition and in Press state, set to Waiting and increment combo position
  735. // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
  736. else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
  737. {
  738. record->state = TriggerMacro_Release;
  739. // If this is the last combo in the sequence, remove from the pending list
  740. if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
  741. return TriggerMacroEval_DoResultAndRemove;
  742. }
  743. // If passing and in Waiting state, set macro state to Press
  744. else if ( overallVote & TriggerMacroVote_Pass
  745. && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
  746. {
  747. record->state = TriggerMacro_Press;
  748. // If in press state, and this is the final combo, send request for ResultMacro
  749. // Check to see if the result macro only has a single element
  750. // If this result macro has more than 1 key, only send once
  751. // TODO Add option to have long macro repeat rate
  752. if ( macro->guide[ pos + comboLength + 1 ] == 0 )
  753. {
  754. // Long result macro (more than 1 combo)
  755. if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
  756. {
  757. // Only ever trigger result once, on press
  758. if ( overallVote == TriggerMacroVote_Pass )
  759. {
  760. return TriggerMacroEval_DoResultAndRemove;
  761. }
  762. }
  763. // Short result macro
  764. else
  765. {
  766. // Only trigger result once, on press, if long trigger (more than 1 combo)
  767. if ( Macro_isLongTriggerMacro( macro ) )
  768. {
  769. return TriggerMacroEval_DoResultAndRemove;
  770. }
  771. // Otherwise, trigger result continuously
  772. else
  773. {
  774. return TriggerMacroEval_DoResult;
  775. }
  776. }
  777. }
  778. }
  779. // Otherwise, just remove the macro on key release
  780. // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
  781. else if ( overallVote & TriggerMacroVote_Release )
  782. {
  783. return TriggerMacroEval_DoResultAndRemove;
  784. }
  785. // If this is a short macro, just remove it
  786. // The state can be rebuilt on the next iteration
  787. if ( !longMacro )
  788. return TriggerMacroEval_Remove;
  789. return TriggerMacroEval_DoNothing;
  790. }
  791. // Evaluate/Update ResultMacro
  792. inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
  793. {
  794. // Lookup ResultMacro
  795. const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
  796. ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
  797. // Current Macro position
  798. var_uint_t pos = record->pos;
  799. // Length of combo being processed
  800. uint8_t comboLength = macro->guide[ pos ];
  801. // Function Counter, used to keep track of the combo items processed
  802. var_uint_t funcCount = 0;
  803. // Combo Item Position within the guide
  804. var_uint_t comboItem = pos + 1;
  805. // Iterate through the Result Combo
  806. while ( funcCount < comboLength )
  807. {
  808. // Assign TriggerGuide element (key type, state and scancode)
  809. ResultGuide *guide = (ResultGuide*)(&macro->guide[ comboItem ]);
  810. // Do lookup on capability function
  811. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  812. // Call capability
  813. capability( record->state, record->stateType, &guide->args );
  814. // Increment counters
  815. funcCount++;
  816. comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
  817. }
  818. // Move to next item in the sequence
  819. record->pos = comboItem;
  820. // If the ResultMacro is finished, remove
  821. if ( macro->guide[ comboItem ] == 0 )
  822. {
  823. record->pos = 0;
  824. return ResultMacroEval_Remove;
  825. }
  826. // Otherwise leave the macro in the list
  827. return ResultMacroEval_DoNothing;
  828. }
  829. // Update pending trigger list
  830. inline void Macro_updateTriggerMacroPendingList()
  831. {
  832. // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
  833. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  834. {
  835. // TODO LED States
  836. // TODO Analog Switches
  837. // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
  838. if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
  839. continue;
  840. // TODO Analog
  841. // If this is a release case, indicate to layer lookup for possible latch expiry
  842. uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
  843. // Lookup Trigger List
  844. nat_ptr_t *triggerList = Macro_layerLookup( &macroTriggerListBuffer[ key ], latch_expire );
  845. // If there was an error during lookup, skip
  846. if ( triggerList == 0 )
  847. continue;
  848. // Number of Triggers in list
  849. nat_ptr_t triggerListSize = triggerList[0];
  850. // Iterate over triggerList to see if any TriggerMacros need to be added
  851. // First item is the number of items in the TriggerList
  852. for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
  853. {
  854. // Lookup trigger macro index
  855. var_uint_t triggerMacroIndex = triggerList[ macro ];
  856. // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
  857. // triggerList needs to be added
  858. var_uint_t pending = 0;
  859. for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
  860. {
  861. // Stop scanning if the trigger macro index is found in the pending list
  862. if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
  863. break;
  864. }
  865. // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
  866. // Add it to the list
  867. if ( pending == macroTriggerMacroPendingListSize )
  868. {
  869. macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
  870. // Reset macro position
  871. TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
  872. TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
  873. }
  874. }
  875. }
  876. }
  877. // Macro Procesing Loop
  878. // Called once per USB buffer send
  879. inline void Macro_process()
  880. {
  881. #if defined(ConnectEnabled_define)
  882. // Only compile in if a Connect node module is available
  883. // If this is a interconnect slave node, send all scancodes to master node
  884. if ( !Connect_master )
  885. {
  886. if ( macroTriggerListBufferSize > 0 )
  887. {
  888. Connect_send_ScanCode( Connect_id, macroTriggerListBuffer, macroTriggerListBufferSize );
  889. macroTriggerListBufferSize = 0;
  890. }
  891. return;
  892. }
  893. #endif
  894. // Only do one round of macro processing between Output Module timer sends
  895. if ( USBKeys_Sent != 0 )
  896. return;
  897. #if defined(ConnectEnabled_define)
  898. // Check if there are any ScanCodes in the interconnect cache to process
  899. if ( Connect_master && macroInterconnectCacheSize > 0 )
  900. {
  901. // Iterate over all the cache ScanCodes
  902. uint8_t currentInterconnectCacheSize = macroInterconnectCacheSize;
  903. macroInterconnectCacheSize = 0;
  904. for ( uint8_t c = 0; c < currentInterconnectCacheSize; c++ )
  905. {
  906. // Add to the trigger list
  907. macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = macroInterconnectCache[ c ];
  908. // TODO Handle other TriggerGuide types (e.g. analog)
  909. switch ( macroInterconnectCache[ c ].type )
  910. {
  911. // Normal (Press/Hold/Release)
  912. case 0x00:
  913. // Decide what to do based on the current state
  914. switch ( macroInterconnectCache[ c ].state )
  915. {
  916. // Re-add to interconnect cache in hold state
  917. case 0x01: // Press
  918. //case 0x02: // Hold // XXX Why does this not work? -HaaTa
  919. macroInterconnectCache[ c ].state = 0x02;
  920. macroInterconnectCache[ macroInterconnectCacheSize++ ] = macroInterconnectCache[ c ];
  921. break;
  922. case 0x03: // Remove
  923. break;
  924. // Otherwise, do not re-add
  925. }
  926. }
  927. }
  928. }
  929. #endif
  930. // If the pause flag is set, only process if the step counter is non-zero
  931. if ( macroPauseMode )
  932. {
  933. if ( macroStepCounter == 0 )
  934. return;
  935. // Proceed, decrementing the step counter
  936. macroStepCounter--;
  937. dbug_print("Macro Step");
  938. }
  939. // Update pending trigger list, before processing TriggerMacros
  940. Macro_updateTriggerMacroPendingList();
  941. // Tail pointer for macroTriggerMacroPendingList
  942. // Macros must be explicitly re-added
  943. var_uint_t macroTriggerMacroPendingListTail = 0;
  944. // Iterate through the pending TriggerMacros, processing each of them
  945. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  946. {
  947. switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
  948. {
  949. // Trigger Result Macro (purposely falling through)
  950. case TriggerMacroEval_DoResult:
  951. // Append ResultMacro to PendingList
  952. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  953. default:
  954. macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
  955. break;
  956. // Trigger Result Macro and Remove (purposely falling through)
  957. case TriggerMacroEval_DoResultAndRemove:
  958. // Append ResultMacro to PendingList
  959. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  960. // Remove Macro from Pending List, nothing to do, removing by default
  961. case TriggerMacroEval_Remove:
  962. break;
  963. }
  964. }
  965. // Update the macroTriggerMacroPendingListSize with the tail pointer
  966. macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
  967. // Tail pointer for macroResultMacroPendingList
  968. // Macros must be explicitly re-added
  969. var_uint_t macroResultMacroPendingListTail = 0;
  970. // Iterate through the pending ResultMacros, processing each of them
  971. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  972. {
  973. switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
  974. {
  975. // Re-add macros to pending list
  976. case ResultMacroEval_DoNothing:
  977. default:
  978. macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
  979. break;
  980. // Remove Macro from Pending List, nothing to do, removing by default
  981. case ResultMacroEval_Remove:
  982. break;
  983. }
  984. }
  985. // Update the macroResultMacroPendingListSize with the tail pointer
  986. macroResultMacroPendingListSize = macroResultMacroPendingListTail;
  987. // Signal buffer that we've used it
  988. Scan_finishedWithMacro( macroTriggerListBufferSize );
  989. // Reset TriggerList buffer
  990. macroTriggerListBufferSize = 0;
  991. // If Macro debug mode is set, clear the USB Buffer
  992. if ( macroDebugMode )
  993. {
  994. USBKeys_Modifiers = 0;
  995. USBKeys_Sent = 0;
  996. }
  997. }
  998. inline void Macro_setup()
  999. {
  1000. // Register Macro CLI dictionary
  1001. CLI_registerDictionary( macroCLIDict, macroCLIDictName );
  1002. // Disable Macro debug mode
  1003. macroDebugMode = 0;
  1004. // Disable Macro pause flag
  1005. macroPauseMode = 0;
  1006. // Set Macro step counter to zero
  1007. macroStepCounter = 0;
  1008. // Make sure macro trigger buffer is empty
  1009. macroTriggerListBufferSize = 0;
  1010. // Initialize TriggerMacro states
  1011. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1012. {
  1013. TriggerMacroRecordList[ macro ].pos = 0;
  1014. TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
  1015. }
  1016. // Initialize ResultMacro states
  1017. for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
  1018. {
  1019. ResultMacroRecordList[ macro ].pos = 0;
  1020. ResultMacroRecordList[ macro ].state = 0;
  1021. ResultMacroRecordList[ macro ].stateType = 0;
  1022. }
  1023. }
  1024. // ----- CLI Command Functions -----
  1025. void cliFunc_capList( char* args )
  1026. {
  1027. print( NL );
  1028. info_msg("Capabilities List ");
  1029. printHex( CapabilitiesNum );
  1030. // Iterate through all of the capabilities and display them
  1031. for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
  1032. {
  1033. print( NL "\t" );
  1034. printHex( cap );
  1035. print(" - ");
  1036. // Display/Lookup Capability Name (utilize debug mode of capability)
  1037. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1038. capability( 0xFF, 0xFF, 0 );
  1039. }
  1040. }
  1041. void cliFunc_capSelect( char* args )
  1042. {
  1043. // Parse code from argument
  1044. char* curArgs;
  1045. char* arg1Ptr;
  1046. char* arg2Ptr = args;
  1047. // Total number of args to scan (must do a lookup if a keyboard capability is selected)
  1048. var_uint_t totalArgs = 2; // Always at least two args
  1049. var_uint_t cap = 0;
  1050. // Arguments used for keyboard capability function
  1051. var_uint_t argSetCount = 0;
  1052. uint8_t *argSet = (uint8_t*)args;
  1053. // Process all args
  1054. for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
  1055. {
  1056. curArgs = arg2Ptr;
  1057. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1058. // Stop processing args if no more are found
  1059. // Extra arguments are ignored
  1060. if ( *arg1Ptr == '\0' )
  1061. break;
  1062. // For the first argument, choose the capability
  1063. if ( c == 0 ) switch ( arg1Ptr[0] )
  1064. {
  1065. // Keyboard Capability
  1066. case 'K':
  1067. // Determine capability index
  1068. cap = numToInt( &arg1Ptr[1] );
  1069. // Lookup the number of args
  1070. totalArgs += CapabilitiesList[ cap ].argCount;
  1071. continue;
  1072. }
  1073. // Because allocating memory isn't doable, and the argument count is arbitrary
  1074. // The argument pointer is repurposed as the argument list (much smaller anyways)
  1075. argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
  1076. // Once all the arguments are prepared, call the keyboard capability function
  1077. if ( argSetCount == totalArgs )
  1078. {
  1079. // Indicate that the capability was called
  1080. print( NL );
  1081. info_msg("K");
  1082. printInt8( cap );
  1083. print(" - ");
  1084. printHex( argSet[0] );
  1085. print(" - ");
  1086. printHex( argSet[1] );
  1087. print(" - ");
  1088. printHex( argSet[2] );
  1089. print( "..." NL );
  1090. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1091. capability( argSet[0], argSet[1], &argSet[2] );
  1092. }
  1093. }
  1094. }
  1095. void cliFunc_keyHold( char* args )
  1096. {
  1097. // Parse codes from arguments
  1098. char* curArgs;
  1099. char* arg1Ptr;
  1100. char* arg2Ptr = args;
  1101. // Process all args
  1102. for ( ;; )
  1103. {
  1104. curArgs = arg2Ptr;
  1105. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1106. // Stop processing args if no more are found
  1107. if ( *arg1Ptr == '\0' )
  1108. break;
  1109. // Ignore non-Scancode numbers
  1110. switch ( arg1Ptr[0] )
  1111. {
  1112. // Scancode
  1113. case 'S':
  1114. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
  1115. break;
  1116. }
  1117. }
  1118. }
  1119. void cliFunc_keyPress( char* args )
  1120. {
  1121. // Parse codes from arguments
  1122. char* curArgs;
  1123. char* arg1Ptr;
  1124. char* arg2Ptr = args;
  1125. // Process all args
  1126. for ( ;; )
  1127. {
  1128. curArgs = arg2Ptr;
  1129. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1130. // Stop processing args if no more are found
  1131. if ( *arg1Ptr == '\0' )
  1132. break;
  1133. // Ignore non-Scancode numbers
  1134. switch ( arg1Ptr[0] )
  1135. {
  1136. // Scancode
  1137. case 'S':
  1138. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  1139. break;
  1140. }
  1141. }
  1142. }
  1143. void cliFunc_keyRelease( char* args )
  1144. {
  1145. // Parse codes from arguments
  1146. char* curArgs;
  1147. char* arg1Ptr;
  1148. char* arg2Ptr = args;
  1149. // Process all args
  1150. for ( ;; )
  1151. {
  1152. curArgs = arg2Ptr;
  1153. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1154. // Stop processing args if no more are found
  1155. if ( *arg1Ptr == '\0' )
  1156. break;
  1157. // Ignore non-Scancode numbers
  1158. switch ( arg1Ptr[0] )
  1159. {
  1160. // Scancode
  1161. case 'S':
  1162. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  1163. break;
  1164. }
  1165. }
  1166. }
  1167. void cliFunc_layerDebug( char *args )
  1168. {
  1169. // Toggle layer debug mode
  1170. layerDebugMode = layerDebugMode ? 0 : 1;
  1171. print( NL );
  1172. info_msg("Layer Debug Mode: ");
  1173. printInt8( layerDebugMode );
  1174. }
  1175. void cliFunc_layerList( char* args )
  1176. {
  1177. print( NL );
  1178. info_msg("Layer List");
  1179. // Iterate through all of the layers and display them
  1180. for ( uint16_t layer = 0; layer < LayerNum; layer++ )
  1181. {
  1182. print( NL "\t" );
  1183. printHex( layer );
  1184. print(" - ");
  1185. // Display layer name
  1186. dPrint( (char*)LayerIndex[ layer ].name );
  1187. // Default map
  1188. if ( layer == 0 )
  1189. print(" \033[1m(default)\033[0m");
  1190. // Layer State
  1191. print( NL "\t\t Layer State: " );
  1192. printHex( LayerState[ layer ] );
  1193. // First -> Last Indices
  1194. print(" First -> Last Indices: ");
  1195. printHex( LayerIndex[ layer ].first );
  1196. print(" -> ");
  1197. printHex( LayerIndex[ layer ].last );
  1198. }
  1199. }
  1200. void cliFunc_layerState( char* args )
  1201. {
  1202. // Parse codes from arguments
  1203. char* curArgs;
  1204. char* arg1Ptr;
  1205. char* arg2Ptr = args;
  1206. uint8_t arg1 = 0;
  1207. uint8_t arg2 = 0;
  1208. // Process first two args
  1209. for ( uint8_t c = 0; c < 2; c++ )
  1210. {
  1211. curArgs = arg2Ptr;
  1212. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1213. // Stop processing args if no more are found
  1214. if ( *arg1Ptr == '\0' )
  1215. break;
  1216. switch ( c )
  1217. {
  1218. // First argument (e.g. L1)
  1219. case 0:
  1220. if ( arg1Ptr[0] != 'L' )
  1221. return;
  1222. arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
  1223. break;
  1224. // Second argument (e.g. 4)
  1225. case 1:
  1226. arg2 = (uint8_t)numToInt( arg1Ptr );
  1227. // Display operation (to indicate that it worked)
  1228. print( NL );
  1229. info_msg("Setting Layer L");
  1230. printInt8( arg1 );
  1231. print(" to - ");
  1232. printHex( arg2 );
  1233. // Set the layer state
  1234. LayerState[ arg1 ] = arg2;
  1235. break;
  1236. }
  1237. }
  1238. }
  1239. void cliFunc_macroDebug( char* args )
  1240. {
  1241. // Toggle macro debug mode
  1242. macroDebugMode = macroDebugMode ? 0 : 1;
  1243. print( NL );
  1244. info_msg("Macro Debug Mode: ");
  1245. printInt8( macroDebugMode );
  1246. }
  1247. void cliFunc_macroList( char* args )
  1248. {
  1249. // Show pending key events
  1250. print( NL );
  1251. info_msg("Pending Key Events: ");
  1252. printInt16( (uint16_t)macroTriggerListBufferSize );
  1253. print(" : ");
  1254. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  1255. {
  1256. printHex( macroTriggerListBuffer[ key ].scanCode );
  1257. print(" ");
  1258. }
  1259. // Show pending trigger macros
  1260. print( NL );
  1261. info_msg("Pending Trigger Macros: ");
  1262. printInt16( (uint16_t)macroTriggerMacroPendingListSize );
  1263. print(" : ");
  1264. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  1265. {
  1266. printHex( macroTriggerMacroPendingList[ macro ] );
  1267. print(" ");
  1268. }
  1269. // Show pending result macros
  1270. print( NL );
  1271. info_msg("Pending Result Macros: ");
  1272. printInt16( (uint16_t)macroResultMacroPendingListSize );
  1273. print(" : ");
  1274. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1275. {
  1276. printHex( macroResultMacroPendingList[ macro ] );
  1277. print(" ");
  1278. }
  1279. // Show available trigger macro indices
  1280. print( NL );
  1281. info_msg("Trigger Macros Range: T0 -> T");
  1282. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1283. // Show available result macro indices
  1284. print( NL );
  1285. info_msg("Result Macros Range: R0 -> R");
  1286. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1287. // Show Trigger to Result Macro Links
  1288. print( NL );
  1289. info_msg("Trigger : Result Macro Pairs");
  1290. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1291. {
  1292. print( NL );
  1293. print("\tT");
  1294. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  1295. print(" : R");
  1296. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  1297. }
  1298. }
  1299. void cliFunc_macroProc( char* args )
  1300. {
  1301. // Toggle macro pause mode
  1302. macroPauseMode = macroPauseMode ? 0 : 1;
  1303. print( NL );
  1304. info_msg("Macro Processing Mode: ");
  1305. printInt8( macroPauseMode );
  1306. }
  1307. void macroDebugShowTrigger( var_uint_t index )
  1308. {
  1309. // Only proceed if the macro exists
  1310. if ( index >= TriggerMacroNum )
  1311. return;
  1312. // Trigger Macro Show
  1313. const TriggerMacro *macro = &TriggerMacroList[ index ];
  1314. TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
  1315. print( NL );
  1316. info_msg("Trigger Macro Index: ");
  1317. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1318. print( NL );
  1319. // Read the comboLength for combo in the sequence (sequence of combos)
  1320. var_uint_t pos = 0;
  1321. uint8_t comboLength = macro->guide[ pos ];
  1322. // Iterate through and interpret the guide
  1323. while ( comboLength != 0 )
  1324. {
  1325. // Initial position of the combo
  1326. var_uint_t comboPos = ++pos;
  1327. // Iterate through the combo
  1328. while ( pos < comboLength * TriggerGuideSize + comboPos )
  1329. {
  1330. // Assign TriggerGuide element (key type, state and scancode)
  1331. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  1332. // Display guide information about trigger key
  1333. printHex( guide->scanCode );
  1334. print("|");
  1335. printHex( guide->type );
  1336. print("|");
  1337. printHex( guide->state );
  1338. // Increment position
  1339. pos += TriggerGuideSize;
  1340. // Only show combo separator if there are combos left in the sequence element
  1341. if ( pos < comboLength * TriggerGuideSize + comboPos )
  1342. print("+");
  1343. }
  1344. // Read the next comboLength
  1345. comboLength = macro->guide[ pos ];
  1346. // Only show sequence separator if there is another combo to process
  1347. if ( comboLength != 0 )
  1348. print(";");
  1349. }
  1350. // Display current position
  1351. print( NL "Position: " );
  1352. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1353. // Display result macro index
  1354. print( NL "Result Macro Index: " );
  1355. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  1356. // Display trigger macro state
  1357. print( NL "Trigger Macro State: " );
  1358. switch ( record->state )
  1359. {
  1360. case TriggerMacro_Press: print("Press"); break;
  1361. case TriggerMacro_Release: print("Release"); break;
  1362. case TriggerMacro_Waiting: print("Waiting"); break;
  1363. }
  1364. }
  1365. void macroDebugShowResult( var_uint_t index )
  1366. {
  1367. // Only proceed if the macro exists
  1368. if ( index >= ResultMacroNum )
  1369. return;
  1370. // Trigger Macro Show
  1371. const ResultMacro *macro = &ResultMacroList[ index ];
  1372. ResultMacroRecord *record = &ResultMacroRecordList[ index ];
  1373. print( NL );
  1374. info_msg("Result Macro Index: ");
  1375. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1376. print( NL );
  1377. // Read the comboLength for combo in the sequence (sequence of combos)
  1378. var_uint_t pos = 0;
  1379. uint8_t comboLength = macro->guide[ pos++ ];
  1380. // Iterate through and interpret the guide
  1381. while ( comboLength != 0 )
  1382. {
  1383. // Function Counter, used to keep track of the combos processed
  1384. var_uint_t funcCount = 0;
  1385. // Iterate through the combo
  1386. while ( funcCount < comboLength )
  1387. {
  1388. // Assign TriggerGuide element (key type, state and scancode)
  1389. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  1390. // Display Function Index
  1391. printHex( guide->index );
  1392. print("|");
  1393. // Display Function Ptr Address
  1394. printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
  1395. print("|");
  1396. // Display/Lookup Capability Name (utilize debug mode of capability)
  1397. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  1398. capability( 0xFF, 0xFF, 0 );
  1399. // Display Argument(s)
  1400. print("(");
  1401. for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  1402. {
  1403. // Arguments are only 8 bit values
  1404. printHex( (&guide->args)[ arg ] );
  1405. // Only show arg separator if there are args left
  1406. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  1407. print(",");
  1408. }
  1409. print(")");
  1410. // Increment position
  1411. pos += ResultGuideSize( guide );
  1412. // Increment function count
  1413. funcCount++;
  1414. // Only show combo separator if there are combos left in the sequence element
  1415. if ( funcCount < comboLength )
  1416. print("+");
  1417. }
  1418. // Read the next comboLength
  1419. comboLength = macro->guide[ pos++ ];
  1420. // Only show sequence separator if there is another combo to process
  1421. if ( comboLength != 0 )
  1422. print(";");
  1423. }
  1424. // Display current position
  1425. print( NL "Position: " );
  1426. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1427. // Display final trigger state/type
  1428. print( NL "Final Trigger State (State/Type): " );
  1429. printHex( record->state );
  1430. print("/");
  1431. printHex( record->stateType );
  1432. }
  1433. void cliFunc_macroShow( char* args )
  1434. {
  1435. // Parse codes from arguments
  1436. char* curArgs;
  1437. char* arg1Ptr;
  1438. char* arg2Ptr = args;
  1439. // Process all args
  1440. for ( ;; )
  1441. {
  1442. curArgs = arg2Ptr;
  1443. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1444. // Stop processing args if no more are found
  1445. if ( *arg1Ptr == '\0' )
  1446. break;
  1447. // Ignore invalid codes
  1448. switch ( arg1Ptr[0] )
  1449. {
  1450. // Indexed Trigger Macro
  1451. case 'T':
  1452. macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
  1453. break;
  1454. // Indexed Result Macro
  1455. case 'R':
  1456. macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
  1457. break;
  1458. }
  1459. }
  1460. }
  1461. void cliFunc_macroStep( char* args )
  1462. {
  1463. // Parse number from argument
  1464. // NOTE: Only first argument is used
  1465. char* arg1Ptr;
  1466. char* arg2Ptr;
  1467. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  1468. // Default to 1, if no argument given
  1469. var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
  1470. if ( count == 0 )
  1471. count = 1;
  1472. // Set the macro step counter, negative int's are cast to uint
  1473. macroStepCounter = count;
  1474. }