use std::error::Error;
use std::fmt;
use crate::fsm_engine::Fsm;
use super::config::{ButtonConfig, DebounceConfig};
use super::debounce_fsm::{self, Event, Motion, State};
use super::types::{ButtonEdge, ButtonPhase, RawLevel, Timestamp};
#[derive(Debug, Clone)]
pub struct Debouncer {
fsm: Fsm<State, Event, Motion>,
config: DebounceConfig,
candidate_since: Option<Timestamp>,
last_update: Option<Timestamp>,
}
impl Debouncer {
pub fn new(config: DebounceConfig, initially_pressed: bool) -> Self {
Self {
fsm: debounce_fsm::new(initially_pressed),
config,
candidate_since: None,
last_update: None,
}
}
pub fn update(
&mut self,
pressed: bool,
now: Timestamp,
) -> Result<Option<ButtonPhase>, DebounceError> {
self.ensure_monotonic(now)?;
let event = if pressed {
Event::SamplePressed
} else {
Event::SampleReleased
};
let motion = self.step(event)?;
self.apply_motion(motion, now);
let state = *self.fsm.current_state();
let Some(candidate_phase) = state.candidate_phase() else {
return Ok(None);
};
let candidate_since = self
.candidate_since
.expect("candidate states always have a start timestamp");
let elapsed = now
.checked_duration_since(candidate_since)
.expect("monotonic time checked before state update");
let required = match candidate_phase {
ButtonPhase::Down => self.config.press,
ButtonPhase::Up => self.config.release,
};
if elapsed < required {
return Ok(None);
}
let motion = self.step(Event::CandidateStable)?;
Ok(self.apply_motion(motion, now))
}
pub fn stable_pressed(&self) -> bool {
self.fsm.current_state().stable_pressed()
}
pub fn candidate_since(&self) -> Option<Timestamp> {
self.candidate_since
}
fn ensure_monotonic(&mut self, now: Timestamp) -> Result<(), DebounceError> {
if let Some(previous) = self.last_update {
if now < previous {
return Err(DebounceError::TimeRegression { previous, now });
}
}
self.last_update = Some(now);
Ok(())
}
fn step(&mut self, event: Event) -> Result<Motion, DebounceError> {
self.fsm
.step(&event)
.map(|(_, motion)| *motion)
.map_err(|source| DebounceError::InvalidTransition(source.to_string()))
}
fn apply_motion(&mut self, motion: Motion, now: Timestamp) -> Option<ButtonPhase> {
match motion {
Motion::None => None,
Motion::ArmCandidate => {
self.candidate_since = Some(now);
None
}
Motion::CancelCandidate => {
self.candidate_since = None;
None
}
Motion::Confirm(phase) => {
self.candidate_since = None;
Some(phase)
}
}
}
}
#[derive(Debug, Clone)]
struct DebounceChannel {
config: ButtonConfig,
debouncer: Debouncer,
}
#[derive(Debug, Clone)]
pub struct DebounceBank {
channels: Vec<DebounceChannel>,
last_update: Option<Timestamp>,
}
impl DebounceBank {
pub fn new(buttons: &[ButtonConfig]) -> Self {
Self {
channels: buttons
.iter()
.cloned()
.map(|config| DebounceChannel {
debouncer: Debouncer::new(config.debounce, config.initially_pressed),
config,
})
.collect(),
last_update: None,
}
}
pub fn update(
&mut self,
now: Timestamp,
levels: &[RawLevel],
) -> Result<Vec<ButtonEdge>, DebounceBankError> {
if levels.len() != self.channels.len() {
return Err(DebounceBankError::SnapshotLength {
expected: self.channels.len(),
actual: levels.len(),
});
}
if let Some(previous) = self.last_update {
if now < previous {
return Err(DebounceBankError::TimeRegression { previous, now });
}
}
let mut edges = Vec::new();
for (index, (channel, &level)) in self.channels.iter_mut().zip(levels).enumerate() {
let pressed = channel.config.active_level.is_pressed(level);
if let Some(phase) = channel
.debouncer
.update(pressed, now)
.map_err(|source| DebounceBankError::Channel { index, source })?
{
edges.push(ButtonEdge {
key: channel.config.id,
phase,
occurred_at: now,
recognized_at: now,
});
}
}
self.last_update = Some(now);
Ok(edges)
}
pub fn len(&self) -> usize {
self.channels.len()
}
pub fn is_empty(&self) -> bool {
self.channels.is_empty()
}
pub fn stable_pressed(&self, index: usize) -> Option<bool> {
self.channels
.get(index)
.map(|channel| channel.debouncer.stable_pressed())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DebounceError {
TimeRegression { previous: Timestamp, now: Timestamp },
InvalidTransition(String),
}
impl fmt::Display for DebounceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TimeRegression { previous, now } => {
write!(f, "debouncer time regressed from {previous} to {now}")
}
Self::InvalidTransition(detail) => write!(f, "debouncer invariant failed: {detail}"),
}
}
}
impl Error for DebounceError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DebounceBankError {
SnapshotLength { expected: usize, actual: usize },
TimeRegression { previous: Timestamp, now: Timestamp },
Channel { index: usize, source: DebounceError },
}
impl fmt::Display for DebounceBankError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SnapshotLength { expected, actual } => {
write!(f, "expected {expected} GPIO levels, received {actual}")
}
Self::TimeRegression { previous, now } => {
write!(f, "debounce bank time regressed from {previous} to {now}")
}
Self::Channel { index, source } => {
write!(f, "debouncer {index} failed: {source}")
}
}
}
}
impl Error for DebounceBankError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Channel { source, .. } => Some(source),
Self::SnapshotLength { .. } | Self::TimeRegression { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key::config::ActiveLevel;
use crate::key::types::KeyId;
use std::time::Duration;
fn time(ms: u64) -> Timestamp {
Timestamp::from_millis(ms)
}
fn symmetric(ms: u64) -> DebounceConfig {
DebounceConfig::symmetric(Duration::from_millis(ms))
}
#[test]
fn confirms_press_at_exact_deadline() {
let mut debouncer = Debouncer::new(symmetric(20), false);
assert_eq!(debouncer.update(true, time(10)).unwrap(), None);
assert_eq!(debouncer.update(true, time(29)).unwrap(), None);
assert_eq!(
debouncer.update(true, time(30)).unwrap(),
Some(ButtonPhase::Down)
);
assert!(debouncer.stable_pressed());
}
#[test]
fn opposite_sample_at_deadline_cancels_candidate() {
let mut debouncer = Debouncer::new(symmetric(20), false);
assert_eq!(debouncer.update(true, time(10)).unwrap(), None);
assert_eq!(debouncer.update(false, time(30)).unwrap(), None);
assert!(!debouncer.stable_pressed());
assert_eq!(debouncer.candidate_since(), None);
}
#[test]
fn bounce_restarts_candidate_duration() {
let mut debouncer = Debouncer::new(symmetric(20), false);
debouncer.update(true, time(10)).unwrap();
debouncer.update(false, time(12)).unwrap();
debouncer.update(true, time(15)).unwrap();
assert_eq!(debouncer.update(true, time(34)).unwrap(), None);
assert_eq!(
debouncer.update(true, time(35)).unwrap(),
Some(ButtonPhase::Down)
);
}
#[test]
fn uses_independent_release_duration() {
let mut debouncer = Debouncer::new(
DebounceConfig {
press: Duration::from_millis(10),
release: Duration::from_millis(30),
},
false,
);
debouncer.update(true, time(0)).unwrap();
debouncer.update(true, time(10)).unwrap();
debouncer.update(false, time(20)).unwrap();
assert_eq!(debouncer.update(false, time(49)).unwrap(), None);
assert_eq!(
debouncer.update(false, time(50)).unwrap(),
Some(ButtonPhase::Up)
);
}
#[test]
fn zero_duration_confirms_immediately() {
let mut debouncer = Debouncer::new(symmetric(0), false);
assert_eq!(
debouncer.update(true, time(1)).unwrap(),
Some(ButtonPhase::Down)
);
}
#[test]
fn rejects_time_regression_without_changing_candidate() {
let mut debouncer = Debouncer::new(symmetric(20), false);
debouncer.update(true, time(10)).unwrap();
assert_eq!(
debouncer.update(true, time(9)),
Err(DebounceError::TimeRegression {
previous: time(10),
now: time(9),
})
);
assert_eq!(debouncer.candidate_since(), Some(time(10)));
}
#[test]
fn bank_normalizes_active_levels_and_preserves_configuration_order() {
let buttons = vec![
ButtonConfig {
id: KeyId(7),
active_level: ActiveLevel::Low,
debounce: symmetric(0),
initially_pressed: false,
},
ButtonConfig {
id: KeyId(3),
active_level: ActiveLevel::High,
debounce: symmetric(0),
initially_pressed: false,
},
];
let mut bank = DebounceBank::new(&buttons);
let edges = bank
.update(time(1), &[RawLevel::Low, RawLevel::High])
.unwrap();
assert_eq!(
edges.iter().map(|edge| edge.key).collect::<Vec<_>>(),
vec![KeyId(7), KeyId(3)]
);
}
#[test]
fn bank_length_error_does_not_advance_time() {
let buttons = vec![ButtonConfig::active_low(KeyId(1), Duration::from_millis(0))];
let mut bank = DebounceBank::new(&buttons);
assert_eq!(
bank.update(time(10), &[]),
Err(DebounceBankError::SnapshotLength {
expected: 1,
actual: 0,
})
);
assert_eq!(bank.update(time(9), &[RawLevel::Low]).unwrap().len(), 1);
}
}