-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButtonTransitions.cpp
More file actions
611 lines (554 loc) · 20.5 KB
/
ButtonTransitions.cpp
File metadata and controls
611 lines (554 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
* MIT License
*
* Copyright (c) 2025 Björn Gaebel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* File: ButtonTransitions.cpp
* Brief: Hybrid button state machine: exact full-release combos and
* tap-while-hold detection with optional conditions, debounced
* mask + coalescing for near-simultaneous presses.
* Project: E-Bike Vereinzelung RC27 (button handling)
* Author: Björn Gaebel
* Date: 2025-09-11
* Version: 1.0.0
* License: MIT
* SPDX-License-Identifier: MIT
*/
#include <Arduino.h>
#include "ButtonTransitions.h"
/*** Internal state ************************************************************/
enum ComboState
{
ComboIdle,
ComboPressing
};
static ComboState comboState = ComboIdle;
static uint8_t activePressMask = 0;
static uint32_t comboStartTime = 0;
static uint8_t initialPressMask = 0; // for diagnostics
static bool suppressFullRelease = false;
static bool didExecAction = false;
static uint8_t anchorHoldMask = 0;
static uint32_t anchorStartTime = 0; // reserved, not used yet (kept for extension)
static uint8_t activeTapMask = 0;
static uint32_t tapStartTime = 0;
/***************** transitionsInit *********************************************
* params: none
* return: void
* Description:
* Resets all internal state of the button transition processor.
******************************************************************************/
void transitionsInit(void)
{
comboState = ComboIdle;
activePressMask = 0;
comboStartTime = 0;
anchorHoldMask = 0;
anchorStartTime = 0;
activeTapMask = 0;
tapStartTime = 0;
initialPressMask = 0;
suppressFullRelease = false;
didExecAction = false;
}
/***************** transitionsReset ********************************************
* params: none
* return: void
* Description:
* Clears current press/tap context without changing overall initialization.
******************************************************************************/
void transitionsReset(void)
{
comboState = ComboIdle;
activePressMask = 0;
comboStartTime = 0;
anchorHoldMask = 0;
activeTapMask = 0;
tapStartTime = 0;
initialPressMask = 0;
suppressFullRelease = false;
didExecAction = false;
// Coalesce/debounce state is intentionally not hard-reset here beyond mask;
// stableMask/candidateMask timelines continue across sessions.
}
/***************** debugPrintMask **********************************************
* params:
* mask - bitmask of currently pressed buttons (bit i => Si pressed)
* return: void
* Description:
* Debug-only helper (compiled only with #if defined(DEBUG)).
* Prints the currently pressed combination via Serial in a stable, human-
* readable format without changing any state of the button logic.
*
* Intended call sites:
* - At press start (after coalescing).
* - On any mask change while holding.
* (Avoid calling every loop tick.)
*
* Output format:
* [BTN] pressed: mask=0xMM (S0+S3+S5) // "none" if mask == 0
*
* Requirements:
* - Serial.begin(...) already called in setup (e.g., 500000 baud).
* - Loop bound matches number of buttons (default below: 8).
*
* Notes:
* - O(nButtons); uses F() to keep strings in flash (no heap use).
* - To print names instead of S0..S7, replace the inner print with a lookup.
******************************************************************************/
#if defined(DEBUG)
static void debugPrintMask(uint8_t mask)
{
Serial.print(F("[BTN] pressed: mask=0x"));
if (mask < 16)
{
Serial.print('0');
}
Serial.print(mask, HEX);
Serial.print(F(" ("));
bool isFirst = true;
for (uint8_t i = 0; i < 8; ++i)
{
if (mask & (1u << i))
{
if (!isFirst)
{
Serial.print('+');
}
Serial.print(F("S"));
Serial.print(i);
isFirst = false;
}
}
if (isFirst)
{
Serial.print(F("none"));
}
Serial.println(F(")"));
}
#endif
/***************** Coalescing window (near-simultaneous press grouping) ********
* params: none
* return: none
* Description:
* Aggregates near-simultaneous button presses at the beginning of a press
* session so that combinations started "almost at the same time" are treated
* as one combo (e.g., S0 then S1 within 30 ms becomes S0|S1).
******************************************************************************/
#ifndef COMBO_COALESCE_MS
#define COMBO_COALESCE_MS 30u
#endif
static bool pressCoalesceActive = false;
static uint32_t pressCoalesceUntil = 0;
static uint8_t pressCoalesceMask = 0;
/***************** Debounced mask layer ****************************************
* params:
* now - current time in ms
* return: uint8_t debounced mask
* Description:
* Stable commit of the raw button mask after a fixed debounce time. This avoids
* transient single-bit flutters when multiple buttons are pressed "together".
******************************************************************************/
#ifndef BTN_DEBOUNCE_MS
#define BTN_DEBOUNCE_MS 20u
#endif
static uint8_t stableMask = 0;
static uint8_t candidateMask = 0;
static uint32_t candidateSince = 0;
static inline uint8_t getDebouncedMask(uint32_t now)
{
uint8_t raw = getButtonMask();
if (raw != candidateMask)
{
candidateMask = raw;
candidateSince = now;
}
if ((uint32_t)(now - candidateSince) >= BTN_DEBOUNCE_MS)
{
if (stableMask != candidateMask)
{
#if defined(DEBUG)
// debugPrintMask(candidateMask);
#endif
stableMask = candidateMask;
}
}
return stableMask;
}
/***************** selectBestFullRelease **************************************
* params:
* tableEx - pointer to extended transition table
* num - number of entries
* mask - exact mask held until release
* held - hold time in ms
* return: int index of best matching transition or -1
* Description:
* Exact-match policy. Among all FULL_RELEASE entries with the same mask and
* minDuration <= held, returns the one with the largest minDuration.
******************************************************************************/
static int selectBestFullRelease(struct ButtonTransitionEx* tableEx, size_t num, uint8_t mask, uint32_t held)
{
int bestIdx = -1;
uint32_t bestMin = 0;
for (size_t i = 0; i < num; ++i)
{
if (tableEx[i].evalType != ComboEvalOnFullRelease)
{
continue;
}
if (tableEx[i].mask == mask && held >= tableEx[i].minDuration)
{
if (tableEx[i].cond && !tableEx[i].cond())
{
continue; // condition not satisfied
}
if (tableEx[i].minDuration >= bestMin)
{
bestMin = tableEx[i].minDuration;
bestIdx = (int)i;
}
}
}
return bestIdx;
}
/***************** selectTapWhileHold ******************************************
* params:
* tableEx - pointer to extended transition table
* num - number of entries
* hold - holdMask currently held (must match exactly)
* tap - tapMask that was pressed+released (exact match)
* tapDur - tap duration in ms
* return: int index of best matching transition or -1
* Description:
* Exact-match policy for both hold and tap masks. Among candidates that accept
* tapDur (tapMin <= tapDur <= tapMax or tapMax==0), returns the one with the
* largest tapMin (prioritize stricter timing).
******************************************************************************/
static int selectTapWhileHold(struct ButtonTransitionEx* tableEx, size_t num, uint8_t hold, uint8_t tap, uint32_t tapDur)
{
int bestIdx = -1;
uint32_t bestMin = 0;
for (size_t i = 0; i < num; ++i)
{
if (tableEx[i].evalType != ComboEvalTapWhileHold)
{
continue;
}
if (tableEx[i].holdMask == hold && tableEx[i].tapMask == tap)
{
bool within = (tapDur >= tableEx[i].tapMin) && ((tableEx[i].tapMax == 0) || (tapDur <= tableEx[i].tapMax));
if (!within)
{
continue;
}
if (tableEx[i].cond && !tableEx[i].cond())
{
continue; // condition not satisfied
}
if (tableEx[i].tapMin >= bestMin)
{
bestMin = tableEx[i].tapMin;
bestIdx = (int)i;
}
}
}
return bestIdx;
}
/***************** popcount8 ***************************************************
* params:
* x - 8-bit value
* return: uint8_t number of set bits in x
* Description:
* Efficient population count for 8-bit values using SWAR technique. Used to
* rank holdMask candidates by size when selecting an anchor.
******************************************************************************/
static inline uint8_t popcount8(uint8_t x)
{
x = x - ((x >> 1) & 0x55);
x = (x & 0x33) + ((x >> 2) & 0x33);
return (uint8_t)((x + (x >> 4)) & 0x0F);
}
/***************** findAnchorHold **********************************************
* params:
* curMask - current debounced mask
* tableEx - transition table
* num - number of entries
* return: uint8_t holdMask to use as anchor, or 0 if none fits
* Description:
* Finds the "best" anchor holdMask that is a subset of curMask. Preference is
* given to anchors with more bits (more specific masks).
******************************************************************************/
static uint8_t findAnchorHold(uint8_t curMask, struct ButtonTransitionEx* tableEx, size_t num)
{
uint8_t best = 0;
uint8_t bestCount = 0;
for (size_t i = 0; i < num; ++i)
{
if (tableEx[i].evalType != ComboEvalTapWhileHold)
{
continue;
}
uint8_t hold = tableEx[i].holdMask;
if (hold != 0 && (curMask & hold) == hold)
{
uint8_t cnt = popcount8(hold);
if (cnt > bestCount)
{
bestCount = cnt;
best = hold;
}
}
}
return best;
}
/***************** processTransitionsHybrid ************************************
* params:
* tableEx - pointer to extended transition table (current mode)
* num - number of entries in table
* now - current time in ms (e.g., millis())
* return: void
* Description:
* Hybrid state machine handling:
* - Full-release: evaluate exact activePressMask when curMask becomes 0, then
* execute the longest satisfied entry once.
* - Tap-while-hold: while anchorHoldMask is fully pressed, detect each press
* and release of an additional exact tapMask and execute matching entry.
******************************************************************************/
void processTransitionsHybrid(struct ButtonTransitionEx* tableEx, size_t num, uint32_t now)
{
uint8_t curMask = getDebouncedMask(now);
switch (comboState)
{
case ComboIdle:
{
if (curMask != 0)
{
comboState = ComboPressing;
activePressMask = curMask;
comboStartTime = now;
// Session start
initialPressMask = curMask;
suppressFullRelease = false;
didExecAction = false;
// Start coalescing window
pressCoalesceActive = true;
pressCoalesceUntil = now + COMBO_COALESCE_MS;
pressCoalesceMask = curMask;
// Tap context
activeTapMask = 0;
tapStartTime = 0;
}
break;
}
case ComboPressing:
{
// Handle near-simultaneous press grouping
if (pressCoalesceActive)
{
pressCoalesceMask = (uint8_t)(pressCoalesceMask | curMask);
if ((int32_t)(now - pressCoalesceUntil) >= 0)
{
activePressMask = pressCoalesceMask;
#if defined(DEBUG)
debugPrintMask(activePressMask);
#endif
pressCoalesceActive = false;
// Initialize anchor from finalized starting mask
anchorHoldMask = findAnchorHold(activePressMask, tableEx, num);
if (anchorHoldMask != 0)
{
anchorStartTime = now;
}
}
// Skip the rest of the case while coalescing
break;
}
// Mark session as "multi-press seen" (>= 2 bits) to gate single full-release
if (curMask != 0 && (uint8_t)(curMask & (uint8_t)(curMask - 1)) != 0)
{
suppressFullRelease = true;
}
// Tap-while-hold evaluation
if (anchorHoldMask != 0)
{
// Anchor must remain fully pressed
if ((curMask & anchorHoldMask) != anchorHoldMask)
{
// Anchor lost → drop tap context
anchorHoldMask = 0;
activeTapMask = 0;
tapStartTime = 0;
}
else
{
// Bits beyond the anchor are candidates for the tap
uint8_t added = (uint8_t)(curMask & (uint8_t)(~anchorHoldMask));
if (activeTapMask == 0)
{
if (added != 0)
{
// Start of a tap
activeTapMask = added;
tapStartTime = now;
}
}
else
{
// Tap in progress
if ((curMask & activeTapMask) == 0)
{
// Tap ended (tap bits released)
uint32_t tapDur = now - tapStartTime;
int ti = selectTapWhileHold(tableEx, num, anchorHoldMask, activeTapMask, tapDur);
#if defined(DEBUG)
Serial.println(F("Tap while hold: end"));
#endif
if (ti >= 0)
{
if (tableEx[ti].action)
{
tableEx[ti].action();
}
#ifndef BTNTRANS_NO_NEXTMODE
nextMode = tableEx[ti].nextMode;
#endif
didExecAction = true; // block later full-release
}
else
{
// Invalid tap → suppress single full-release later
suppressFullRelease = true;
}
// Ready for the next tap
activeTapMask = 0;
tapStartTime = 0;
}
else
{
// Tap bits changed mid-tap → restart timing
uint8_t nowAdded = (uint8_t)(curMask & (uint8_t)(~anchorHoldMask));
if (nowAdded != activeTapMask)
{
activeTapMask = nowAdded;
tapStartTime = now;
}
}
}
}
}
// Full-release path: evaluate only when everything is released
if (curMask == 0)
{
uint32_t held = now - comboStartTime;
if (!didExecAction)
{
int bestIdx = selectBestFullRelease(tableEx, num, activePressMask, held);
if (bestIdx >= 0)
{
// Determine if matched mask is multi (>=2 bits)
uint8_t matchedMask = tableEx[bestIdx].mask;
bool isMultiMask = (matchedMask != 0) && ((matchedMask & (matchedMask - 1)) != 0);
// Suppress only single-key full-release after a session with multi-press
if (!suppressFullRelease || isMultiMask)
{
#if defined(DEBUG)
Serial.println(F("Full-release exec"));
#endif
if (tableEx[bestIdx].action)
{
tableEx[bestIdx].action();
}
#ifndef BTNTRANS_NO_NEXTMODE
nextMode = tableEx[bestIdx].nextMode;
#endif
}
else
{
#if defined(DEBUG)
Serial.println(F("Full-release suppressed (single after multi)"));
#endif
}
}
}
transitionsReset();
}
else if (curMask != activePressMask)
{
// Mask changed while holding: update full-release context
activePressMask = curMask;
comboStartTime = now;
#if defined(DEBUG)
debugPrintMask(curMask);
#endif
// Keep anchor while fully pressed; otherwise, drop and try to find a new one
if (anchorHoldMask != 0)
{
if ((curMask & anchorHoldMask) != anchorHoldMask)
{
// Anchor lost → drop tap context
anchorHoldMask = 0;
activeTapMask = 0;
tapStartTime = 0;
}
}
else
{
// No anchor yet: choose the "best" hold that is a subset of curMask (most bits)
uint8_t bestAnchor = 0;
uint8_t bestCount = 0;
for (size_t i = 0; i < num; ++i)
{
if (tableEx[i].evalType != ComboEvalTapWhileHold)
{
continue;
}
uint8_t hold = tableEx[i].holdMask;
if (hold != 0 && (curMask & hold) == hold)
{
// popcount(hold)
uint8_t x = hold;
x = x - ((x >> 1) & 0x55);
x = (x & 0x33) + ((x >> 2) & 0x33);
uint8_t cnt = (uint8_t)((x + (x >> 4)) & 0x0F);
if (cnt > bestCount)
{
bestCount = cnt;
bestAnchor = hold;
}
}
}
if (bestAnchor != 0)
{
anchorHoldMask = bestAnchor;
anchorStartTime = now;
}
}
// Note: do NOT clear activeTapMask/tapStartTime here; that would kill ongoing taps.
}
break;
}
default:
{
transitionsReset();
break;
}
}
}