btn-recognizer 0.2.2

Timestamp-driven button debouncing with multi-tap, hold, repeat, and multi-key chord gesture recognition
Documentation
# fsm-engine

Timestamp-driven button debouncing and multi-gesture recognition for
embedded input subsystems.

`fsm-engine` provides a complete **physical-to-semantic recognition pipeline**:

- **Asymmetric press/release debounce** — independent durations, zero polling
- **Multi-tap detection** — single, double, and higher-order taps, configurable
  tap timeout and multi-tap window
- **Hold with milestones** — strictly increasing thresholds, each emitted as a
  distinct event
- **Coalesced repeat** — one event per update carrying the number of elapsed
  repeat intervals, avoiding unbounded catch-up bursts
- **Multi-key chord arbitration** — eager matching with priority-based overlap
  resolution, configurable release policies (AnyMember / AllMembers)
- **Virtual chord controls** — chords reuse the same tap/hold/repeat gesture
  recognizer as physical keys
- **Owned event batches** — every event carries `occurred_at` and `recognized_at`
  timestamps, with explicit `processed_at` per batch
- **Lossless input adapter** — `VecDeque`-backed queue with retryable fallible
  sinks, atomic batch commit on mapping success

Internally, the pipeline stages are built on a generic **HashMap-driven Mealy
state-machine engine** that remains part of the public API for use in other
contexts.

## Quick start

```rust
use std::time::Duration;
use fsm_engine::key::{
    ButtonConfig, ButtonEngine, ButtonSnapshot, FrameworkConfig, KeyId, RawLevel, Timestamp,
};

// One active-low button with 20 ms debounce
let config = FrameworkConfig::new(vec![ButtonConfig::active_low(
    KeyId(1),
    Duration::from_millis(20),
)]);
let mut engine = ButtonEngine::new(config)?;

// Feed two consecutive GPIO snapshots (20 ms apart) to confirm a press
engine.update(ButtonSnapshot {
    at: Timestamp::from_millis(0),
    levels: &[RawLevel::Low],
})?;

let batch = engine.update(ButtonSnapshot {
    at: Timestamp::from_millis(20),
    levels: &[RawLevel::Low],
})?;
// batch.physical contains one ButtonEdge { phase: Down, ... }
// batch.events   contains one ButtonEvent { kind: State { phase: Down }, ... }
# Ok::<(), Box<dyn std::error::Error>>(())
```

When the engine has a pending chord or gesture deadline, call `advance_to()`
even if no GPIO levels changed. Check `EventBatch::next_wakeup` (or
`ButtonEngine::next_wakeup()`) for the earliest deadline.

## Gesture example

```rust
use std::time::Duration;
use fsm_engine::key::{
    ButtonConfig, ButtonEngine, ButtonEventKind, ButtonPhase, ButtonSnapshot, ControlId,
    FrameworkConfig, GestureConfig, GestureKind, KeyId, RawLevel, Timestamp,
};

let mut config = FrameworkConfig::new(vec![ButtonConfig::active_low(
    KeyId(1),
    Duration::ZERO, // zero debounce for illustration
)]);
config.default_gestures = GestureConfig {
    tap_max: Duration::from_millis(200),
    multi_tap_window: Duration::from_millis(300),
    max_taps: 2,
    hold_thresholds: vec![Duration::from_millis(500), Duration::from_millis(1500)],
    ..Default::default()
};

let mut engine = ButtonEngine::new(config)?;

// Press at 0 ms, release at 100 ms
engine.update(ButtonSnapshot { at: Timestamp::from_millis(0),   levels: &[RawLevel::Low] })?;
engine.update(ButtonSnapshot { at: Timestamp::from_millis(100), levels: &[RawLevel::High] })?;

// Advance past the multi-tap window (100 + 300 = 400 ms)
let batch = engine.advance_to(Timestamp::from_millis(400))?;
assert!(batch.events.iter().any(|e| matches!(e.kind, ButtonEventKind::Gesture {
    kind: GestureKind::Tap { count: 1 }, ..
})));
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Chord example

```rust
use std::time::Duration;
use fsm_engine::key::{
    ButtonConfig, ButtonEngine, ButtonEventKind, ButtonPhase, ButtonSnapshot, ChordConfig,
    ChordId, ChordReleasePolicy, ControlId, FrameworkConfig, KeyId, RawLevel, Timestamp,
};

let mut config = FrameworkConfig::new(vec![
    ButtonConfig::active_low(KeyId(1), Duration::ZERO),
    ButtonConfig::active_low(KeyId(2), Duration::ZERO),
]);
config.chords = vec![ChordConfig {
    id: ChordId(10),
    members: vec![KeyId(1), KeyId(2)],
    window: Duration::from_millis(50),
    priority: 0,
    release: ChordReleasePolicy::AnyMember,
}];

let mut engine = ButtonEngine::new(config)?;

// Both keys pressed simultaneously → chord activated
let batch = engine.update(ButtonSnapshot {
    at: Timestamp::from_millis(10),
    levels: &[RawLevel::Low, RawLevel::Low],
})?;
assert!(batch.events.iter().any(|e| matches!(e.kind, ButtonEventKind::State {
    control: ControlId::Chord(ChordId(10)), phase: ButtonPhase::Down,
})));
// Individual key-down events are suppressed — only the chord appears
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Generic Mealy FSM

The underlying state-machine engine is also public:

```rust
use fsm_engine::Fsm;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum State { Idle, Running }

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Event { Start }

let mut fsm = Fsm::builder()
    .initial_state(State::Idle)
    .on(State::Idle, Event::Start, State::Running, "started")
    .build()?;

let (state, motion) = fsm.step(&Event::Start)?;
assert_eq!((*state, *motion), (State::Running, "started"));
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Architecture

| Stage | Input | Output |
|-------|-------|--------|
| `DebounceBank` | `ButtonSnapshot` (GPIO levels) | `ButtonEdge` (confirmed physical edges) |
| `ChordResolver` | `ButtonEdge` | `ControlEdge` (Key or Chord, with arbitration) |
| `GestureBank` | `ControlEdge` | `ButtonEvent` (State / Tap / Hold / Repeat) |
| Input adapter | `ButtonEvent` | application events with codes and sequence numbers |

All stages reject time regression. Every event satisfies
`occurred_at ≤ recognized_at ≤ processed_at`.

## Documentation

- [Architecture overview]docs/ARCHITECTURE.md — data flow, time model, contracts
- [Design document]docs/Design.md — detailed software architecture
- [Testing strategy]docs/TESTING.md — verification contract and test conventions
- [Changelog]CHANGELOG.md

## License

MIT