Skip to main content

m5stack_core/io/
buttons.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Unified front-panel button events.
3//!
4//! Both input flavours of the M5Stack Core family emit the same
5//! [`ButtonEvent`]: the Fire27's three physical buttons ([`Buttons`], feature
6//! `buttons`) and the CoreS3's touch-strip emulation
7//! ([`crate::io::touch_buttons::TouchButtons`]). An application maps these to
8//! its own events in one place, identically for both boards.
9
10use esp_hal::gpio::AnyPin;
11
12/// Which of the three front-panel positions fired. On the Fire27 these are
13/// buttons A/B/C; on the CoreS3, the left/center/right touch zones.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ButtonId {
16    Left,
17    Center,
18    Right,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ButtonAction {
23    /// Short press(es); the count is the number of consecutive taps.
24    Short(usize),
25    Long,
26}
27
28/// A generic, positional input event — the #32 I1/I6 contract: it carries only
29/// *where* (`id`) and *what kind* (`action`), never app semantics (no
30/// Inc/Dec/Ok, no nav). Both the Fire27 physical buttons and the CoreS3 touch
31/// zones emit this same type, so a consumer's input router maps it to meaning;
32/// the BSP never does. Do not add app-vocabulary variants here.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct ButtonEvent {
35    pub id: ButtonId,
36    pub action: ButtonAction,
37}
38
39/// Press-decoding timing shared by **both** front-panel drivers — the Fire27
40/// physical buttons (`ButtonResources::into_buttons_with_timing`, feature
41/// `buttons`) and the CoreS3 touch strip
42/// ([`TouchButtonsConfig::with_timing`](crate::io::touch_buttons::TouchButtonsConfig::with_timing)).
43/// Milliseconds (the touch driver's native unit; the Fire27 `async-button`
44/// `Duration`s are built from these).
45///
46/// The knob that matters for latency is `multi_tap_ms`: both drivers count
47/// consecutive taps, which delays *every* single press by that window. Set it to
48/// `0` (see [`immediate_single_press`](Self::immediate_single_press)) for
49/// latency-sensitive input like an encoder — a downstream accumulator can still
50/// sum immediate `Short(1)` events into multi-step (#58).
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ButtonTiming {
53    /// Hold time before a press becomes [`ButtonAction::Long`].
54    pub long_press_ms: u64,
55    /// Max gap between consecutive taps still counted as one multi-tap sequence.
56    /// `0` disables counting: each press emits [`Short(1)`](ButtonAction::Short)
57    /// as soon as it is debounced, with no counting delay.
58    pub multi_tap_ms: u64,
59}
60
61impl ButtonTiming {
62    /// Count multi-taps (the historical behaviour): a single press is delayed by
63    /// the `multi_tap_ms` window so consecutive taps can be counted. 500 ms
64    /// long-press, 300 ms multi-tap window.
65    pub const fn multi_tap() -> Self {
66        Self {
67            long_press_ms: 500,
68            multi_tap_ms: 300,
69        }
70    }
71
72    /// Report every press immediately — multi-tap counting disabled
73    /// (`multi_tap_ms = 0`). For latency-sensitive input (e.g. an encoder). Keeps
74    /// the [`multi_tap`](Self::multi_tap) long-press threshold.
75    pub const fn immediate_single_press() -> Self {
76        Self {
77            long_press_ms: Self::multi_tap().long_press_ms,
78            multi_tap_ms: 0,
79        }
80    }
81}
82
83/// The unified opt-in baseline is [`multi_tap`](Self::multi_tap). Note the legacy
84/// entry points (`ButtonResources::into_buttons`,
85/// [`TouchButtons::new`](crate::io::touch_buttons::TouchButtons::new) with
86/// [`TouchButtonsConfig::default`](crate::io::touch_buttons::TouchButtonsConfig::default))
87/// keep each driver's *original* per-board timings for backward compatibility;
88/// this default is only used where a `ButtonTiming` is taken explicitly.
89impl Default for ButtonTiming {
90    fn default() -> Self {
91        Self::multi_tap()
92    }
93}
94
95/// The three front-panel button pins (Fire27: A=GPIO39, B=GPIO38, C=GPIO37,
96/// active-low). Wired by [`crate::board::fire27::Board::split`].
97pub struct ButtonResources<'a> {
98    pub left: AnyPin<'a>,
99    pub center: AnyPin<'a>,
100    pub right: AnyPin<'a>,
101}
102
103#[cfg(feature = "buttons")]
104mod physical {
105    use async_button::{Button, ButtonConfig, ButtonEvent as AsyncButtonEvent, Mode};
106    use embassy_futures::select::{Either3, select3};
107    use embassy_time_04::Duration;
108    use esp_hal::gpio::{AnyPin, Input, InputConfig, Pin, Pull};
109
110    use super::{ButtonAction, ButtonEvent, ButtonId, ButtonResources, ButtonTiming};
111
112    /// Map the cross-driver [`ButtonTiming`] onto `async-button`'s [`ButtonConfig`]:
113    /// `multi_tap_ms → double_click`, `long_press_ms → long_press`. Debounce keeps
114    /// async-button's default; `mode` is [`Mode::PullUp`] — the BSP owns the
115    /// active-low + pull-up wiring, the caller owns only the timings. The
116    /// `Duration`s are `embassy-time` 0.4 (async-button's pin), built here from ms.
117    fn config_from_timing(timing: ButtonTiming) -> ButtonConfig {
118        ButtonConfig {
119            double_click: Duration::from_millis(timing.multi_tap_ms),
120            long_press: Duration::from_millis(timing.long_press_ms),
121            mode: Mode::PullUp,
122            ..ButtonConfig::default()
123        }
124    }
125
126    impl ButtonResources<'static> {
127        /// Wrap the pins in debounced [`async_button`] drivers with async-button's
128        /// default timings (pull-ups on). A single press is delayed by the multi-tap
129        /// window (~350 ms) so consecutive taps can be counted; for a different
130        /// window — or immediate single-press — use
131        /// [`into_buttons_with_timing`](Self::into_buttons_with_timing).
132        pub fn into_buttons(self) -> Buttons<'static> {
133            self.make_buttons(ButtonConfig::default())
134        }
135
136        /// Like [`into_buttons`](Self::into_buttons) but driven by the cross-driver
137        /// [`ButtonTiming`] — the same type and presets the CoreS3 touch strip takes
138        /// ([`TouchButtonsConfig::with_timing`](crate::io::touch_buttons::TouchButtonsConfig::with_timing)).
139        /// Pass [`ButtonTiming::immediate_single_press`] to trade the multi-tap
140        /// counting delay for instant response, or a custom window / long-press.
141        pub fn into_buttons_with_timing(self, timing: ButtonTiming) -> Buttons<'static> {
142            self.make_buttons(config_from_timing(timing))
143        }
144
145        fn make_buttons(self, config: ButtonConfig) -> Buttons<'static> {
146            let make = |pin| {
147                Button::new(
148                    Input::new(pin, InputConfig::default().with_pull(Pull::Up)),
149                    config,
150                )
151            };
152            let pins = [
153                self.left.number(),
154                self.center.number(),
155                self.right.number(),
156            ];
157            Buttons {
158                left: make(self.left),
159                center: make(self.center),
160                right: make(self.right),
161                pins,
162            }
163        }
164    }
165
166    /// The three debounced front-panel buttons.
167    pub struct Buttons<'a> {
168        left: Button<Input<'a>>,
169        center: Button<Input<'a>>,
170        right: Button<Input<'a>>,
171        /// GPIO numbers of left, centre and right, kept so
172        /// [`Buttons::into_wake_pins`] can hand the pins back:
173        /// `async_button::Button` owns its pin and exposes no accessor.
174        pins: [u8; 3],
175    }
176
177    impl Buttons<'static> {
178        /// Give up the debounced drivers and return the three buttons as plain
179        /// inputs, left, centre, right, for arming them as deep-sleep wake sources.
180        ///
181        /// On Fire27 that is A/B/C, GPIO39/38/37 — RTC IOs, active-low, pulled up
182        /// externally (GPIO34-39 have no internal pulls on the ESP32, so the
183        /// board's resistors hold them high in sleep). Arming is application
184        /// policy: which buttons, and whether to sleep at all.
185        pub fn into_wake_pins(self) -> [Input<'static>; 3] {
186            let pins = self.pins;
187            // Every driver built from these pins is dropped here, before the
188            // steals below. `make_buttons` moved each pin into a field of `self`,
189            // which this consumes, so nothing else was ever given one.
190            #[expect(
191                clippy::drop_non_drop,
192                reason = "fixes the order: the drivers end before the steals even if they gain a Drop"
193            )]
194            drop(self);
195            pins.map(|number| {
196                // SAFETY: the only instance of this pin was the `Input` inside
197                // `self`, dropped above, so no other driver for it exists and
198                // none can be created from this crate's resources.
199                let pin = unsafe { AnyPin::steal(number) };
200                Input::new(pin, InputConfig::default().with_pull(Pull::Up))
201            })
202        }
203    }
204
205    impl Buttons<'_> {
206        /// Wait for the next debounced event on any of the three buttons.
207        /// No polling — the underlying driver awaits pin edges.
208        pub async fn next_event(&mut self) -> ButtonEvent {
209            let (id, event) = match select3(
210                self.left.update(),
211                self.center.update(),
212                self.right.update(),
213            )
214            .await
215            {
216                Either3::First(e) => (ButtonId::Left, e),
217                Either3::Second(e) => (ButtonId::Center, e),
218                Either3::Third(e) => (ButtonId::Right, e),
219            };
220            let action = match event {
221                AsyncButtonEvent::ShortPress { count } => ButtonAction::Short(count),
222                AsyncButtonEvent::LongPress => ButtonAction::Long,
223            };
224            ButtonEvent { id, action }
225        }
226    }
227}
228
229#[cfg(feature = "buttons")]
230pub use physical::Buttons;