Skip to main content

btn_recognizer/key/
debounce.rs

1use std::error::Error;
2use std::fmt;
3
4use crate::fsm_engine::Fsm;
5
6use super::config::{ButtonConfig, DebounceConfig};
7use super::debounce_fsm::{self, Event, Motion, State};
8use super::types::{ButtonEdge, ButtonPhase, RawLevel, Timestamp};
9
10/// Timestamp-driven debouncer for one normalized button signal.
11#[derive(Debug, Clone)]
12pub struct Debouncer {
13    fsm: Fsm<State, Event, Motion>,
14    config: DebounceConfig,
15    candidate_since: Option<Timestamp>,
16    last_update: Option<Timestamp>,
17}
18
19impl Debouncer {
20    pub fn new(config: DebounceConfig, initially_pressed: bool) -> Self {
21        Self {
22            fsm: debounce_fsm::new(initially_pressed),
23            config,
24            candidate_since: None,
25            last_update: None,
26        }
27    }
28
29    /// Process one normalized sample (`true` means physically pressed).
30    ///
31    /// The sample transition is always applied before testing the deadline.
32    /// Consequently, an opposite sample exactly at the deadline cancels the
33    /// candidate instead of briefly confirming the wrong stable state.
34    pub fn update(
35        &mut self,
36        pressed: bool,
37        now: Timestamp,
38    ) -> Result<Option<ButtonPhase>, DebounceError> {
39        self.ensure_monotonic(now)?;
40
41        let event = if pressed {
42            Event::SamplePressed
43        } else {
44            Event::SampleReleased
45        };
46        let motion = self.step(event)?;
47        self.apply_motion(motion, now);
48
49        let state = *self.fsm.current_state();
50        let Some(candidate_phase) = state.candidate_phase() else {
51            return Ok(None);
52        };
53        let candidate_since = self
54            .candidate_since
55            .expect("candidate states always have a start timestamp");
56        let elapsed = now
57            .checked_duration_since(candidate_since)
58            .expect("monotonic time checked before state update");
59        let required = match candidate_phase {
60            ButtonPhase::Down => self.config.press,
61            ButtonPhase::Up => self.config.release,
62        };
63
64        if elapsed < required {
65            return Ok(None);
66        }
67
68        let motion = self.step(Event::CandidateStable)?;
69        Ok(self.apply_motion(motion, now))
70    }
71
72    pub fn stable_pressed(&self) -> bool {
73        self.fsm.current_state().stable_pressed()
74    }
75
76    pub fn candidate_since(&self) -> Option<Timestamp> {
77        self.candidate_since
78    }
79
80    fn ensure_monotonic(&mut self, now: Timestamp) -> Result<(), DebounceError> {
81        if let Some(previous) = self.last_update {
82            if now < previous {
83                return Err(DebounceError::TimeRegression { previous, now });
84            }
85        }
86        self.last_update = Some(now);
87        Ok(())
88    }
89
90    fn step(&mut self, event: Event) -> Result<Motion, DebounceError> {
91        self.fsm
92            .step(&event)
93            .map(|(_, motion)| *motion)
94            .map_err(|source| DebounceError::InvalidTransition(source.to_string()))
95    }
96
97    fn apply_motion(&mut self, motion: Motion, now: Timestamp) -> Option<ButtonPhase> {
98        match motion {
99            Motion::None => None,
100            Motion::ArmCandidate => {
101                self.candidate_since = Some(now);
102                None
103            }
104            Motion::CancelCandidate => {
105                self.candidate_since = None;
106                None
107            }
108            Motion::Confirm(phase) => {
109                self.candidate_since = None;
110                Some(phase)
111            }
112        }
113    }
114}
115
116#[derive(Debug, Clone)]
117struct DebounceChannel {
118    config: ButtonConfig,
119    debouncer: Debouncer,
120}
121
122/// A fixed-order collection of button debouncers.
123///
124/// Every update consumes a complete GPIO snapshot. The `levels` slice must use
125/// the same order as the configuration passed to [`Self::new`].
126#[derive(Debug, Clone)]
127pub struct DebounceBank {
128    channels: Vec<DebounceChannel>,
129    last_update: Option<Timestamp>,
130}
131
132impl DebounceBank {
133    pub fn new(buttons: &[ButtonConfig]) -> Self {
134        Self {
135            channels: buttons
136                .iter()
137                .cloned()
138                .map(|config| DebounceChannel {
139                    debouncer: Debouncer::new(config.debounce, config.initially_pressed),
140                    config,
141                })
142                .collect(),
143            last_update: None,
144        }
145    }
146
147    pub fn update(
148        &mut self,
149        now: Timestamp,
150        levels: &[RawLevel],
151    ) -> Result<Vec<ButtonEdge>, DebounceBankError> {
152        if levels.len() != self.channels.len() {
153            return Err(DebounceBankError::SnapshotLength {
154                expected: self.channels.len(),
155                actual: levels.len(),
156            });
157        }
158        if let Some(previous) = self.last_update {
159            if now < previous {
160                return Err(DebounceBankError::TimeRegression { previous, now });
161            }
162        }
163
164        let mut edges = Vec::new();
165        for (index, (channel, &level)) in self.channels.iter_mut().zip(levels).enumerate() {
166            let pressed = channel.config.active_level.is_pressed(level);
167            if let Some(phase) = channel
168                .debouncer
169                .update(pressed, now)
170                .map_err(|source| DebounceBankError::Channel { index, source })?
171            {
172                edges.push(ButtonEdge {
173                    key: channel.config.id,
174                    phase,
175                    occurred_at: now,
176                    recognized_at: now,
177                });
178            }
179        }
180        self.last_update = Some(now);
181        Ok(edges)
182    }
183
184    pub fn len(&self) -> usize {
185        self.channels.len()
186    }
187
188    pub fn is_empty(&self) -> bool {
189        self.channels.is_empty()
190    }
191
192    pub fn stable_pressed(&self, index: usize) -> Option<bool> {
193        self.channels
194            .get(index)
195            .map(|channel| channel.debouncer.stable_pressed())
196    }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum DebounceError {
201    TimeRegression { previous: Timestamp, now: Timestamp },
202    InvalidTransition(String),
203}
204
205impl fmt::Display for DebounceError {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match self {
208            Self::TimeRegression { previous, now } => {
209                write!(f, "debouncer time regressed from {previous} to {now}")
210            }
211            Self::InvalidTransition(detail) => write!(f, "debouncer invariant failed: {detail}"),
212        }
213    }
214}
215
216impl Error for DebounceError {
217    fn source(&self) -> Option<&(dyn Error + 'static)> {
218        None
219    }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum DebounceBankError {
224    SnapshotLength { expected: usize, actual: usize },
225    TimeRegression { previous: Timestamp, now: Timestamp },
226    Channel { index: usize, source: DebounceError },
227}
228
229impl fmt::Display for DebounceBankError {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            Self::SnapshotLength { expected, actual } => {
233                write!(f, "expected {expected} GPIO levels, received {actual}")
234            }
235            Self::TimeRegression { previous, now } => {
236                write!(f, "debounce bank time regressed from {previous} to {now}")
237            }
238            Self::Channel { index, source } => {
239                write!(f, "debouncer {index} failed: {source}")
240            }
241        }
242    }
243}
244
245impl Error for DebounceBankError {
246    fn source(&self) -> Option<&(dyn Error + 'static)> {
247        match self {
248            Self::Channel { source, .. } => Some(source),
249            Self::SnapshotLength { .. } | Self::TimeRegression { .. } => None,
250        }
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::key::config::ActiveLevel;
258    use crate::key::types::KeyId;
259    use std::time::Duration;
260
261    fn time(ms: u64) -> Timestamp {
262        Timestamp::from_millis(ms)
263    }
264
265    fn symmetric(ms: u64) -> DebounceConfig {
266        DebounceConfig::symmetric(Duration::from_millis(ms))
267    }
268
269    #[test]
270    fn confirms_press_at_exact_deadline() {
271        let mut debouncer = Debouncer::new(symmetric(20), false);
272        assert_eq!(debouncer.update(true, time(10)).unwrap(), None);
273        assert_eq!(debouncer.update(true, time(29)).unwrap(), None);
274        assert_eq!(
275            debouncer.update(true, time(30)).unwrap(),
276            Some(ButtonPhase::Down)
277        );
278        assert!(debouncer.stable_pressed());
279    }
280
281    #[test]
282    fn opposite_sample_at_deadline_cancels_candidate() {
283        let mut debouncer = Debouncer::new(symmetric(20), false);
284        assert_eq!(debouncer.update(true, time(10)).unwrap(), None);
285        assert_eq!(debouncer.update(false, time(30)).unwrap(), None);
286        assert!(!debouncer.stable_pressed());
287        assert_eq!(debouncer.candidate_since(), None);
288    }
289
290    #[test]
291    fn bounce_restarts_candidate_duration() {
292        let mut debouncer = Debouncer::new(symmetric(20), false);
293        debouncer.update(true, time(10)).unwrap();
294        debouncer.update(false, time(12)).unwrap();
295        debouncer.update(true, time(15)).unwrap();
296        assert_eq!(debouncer.update(true, time(34)).unwrap(), None);
297        assert_eq!(
298            debouncer.update(true, time(35)).unwrap(),
299            Some(ButtonPhase::Down)
300        );
301    }
302
303    #[test]
304    fn uses_independent_release_duration() {
305        let mut debouncer = Debouncer::new(
306            DebounceConfig {
307                press: Duration::from_millis(10),
308                release: Duration::from_millis(30),
309            },
310            false,
311        );
312        debouncer.update(true, time(0)).unwrap();
313        debouncer.update(true, time(10)).unwrap();
314        debouncer.update(false, time(20)).unwrap();
315        assert_eq!(debouncer.update(false, time(49)).unwrap(), None);
316        assert_eq!(
317            debouncer.update(false, time(50)).unwrap(),
318            Some(ButtonPhase::Up)
319        );
320    }
321
322    #[test]
323    fn zero_duration_confirms_immediately() {
324        let mut debouncer = Debouncer::new(symmetric(0), false);
325        assert_eq!(
326            debouncer.update(true, time(1)).unwrap(),
327            Some(ButtonPhase::Down)
328        );
329    }
330
331    #[test]
332    fn rejects_time_regression_without_changing_candidate() {
333        let mut debouncer = Debouncer::new(symmetric(20), false);
334        debouncer.update(true, time(10)).unwrap();
335        assert_eq!(
336            debouncer.update(true, time(9)),
337            Err(DebounceError::TimeRegression {
338                previous: time(10),
339                now: time(9),
340            })
341        );
342        assert_eq!(debouncer.candidate_since(), Some(time(10)));
343    }
344
345    #[test]
346    fn bank_normalizes_active_levels_and_preserves_configuration_order() {
347        let buttons = vec![
348            ButtonConfig {
349                id: KeyId(7),
350                active_level: ActiveLevel::Low,
351                debounce: symmetric(0),
352                initially_pressed: false,
353            },
354            ButtonConfig {
355                id: KeyId(3),
356                active_level: ActiveLevel::High,
357                debounce: symmetric(0),
358                initially_pressed: false,
359            },
360        ];
361        let mut bank = DebounceBank::new(&buttons);
362        let edges = bank
363            .update(time(1), &[RawLevel::Low, RawLevel::High])
364            .unwrap();
365        assert_eq!(
366            edges.iter().map(|edge| edge.key).collect::<Vec<_>>(),
367            vec![KeyId(7), KeyId(3)]
368        );
369    }
370
371    #[test]
372    fn bank_length_error_does_not_advance_time() {
373        let buttons = vec![ButtonConfig::active_low(KeyId(1), Duration::from_millis(0))];
374        let mut bank = DebounceBank::new(&buttons);
375        assert_eq!(
376            bank.update(time(10), &[]),
377            Err(DebounceBankError::SnapshotLength {
378                expected: 1,
379                actual: 0,
380            })
381        );
382        assert_eq!(bank.update(time(9), &[RawLevel::Low]).unwrap().len(), 1);
383    }
384}