Skip to main content

m5stack_core/io/
touch_buttons.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Touch→button emulation for the CoreS3 (FT6336U).
3//!
4//! The CoreS3 has no physical front-panel buttons; a strip of the touch panel
5//! is split into three zones emulating the classic M5Stack Left/Center/Right
6//! buttons. A small state machine detects short taps (with multi-tap
7//! counting) and long presses and emits the same
8//! [`ButtonEvent`](crate::io::buttons::ButtonEvent) as the Fire27's physical
9//! buttons ([`crate::io::buttons`]), so the application maps input events in
10//! one place for both boards.
11//!
12//! Each contact is judged as one **stroke**, finger down to finger up, by
13//! where it started and whether it stayed put. A stroke that travels more
14//! than [`TouchButtonsConfig::tap_slop_px`] is a swipe and emits nothing: a
15//! drag that merely crossed the strip used to fire the key it crossed. Above
16//! the strip, two still taps in quick succession are a
17//! [`TouchInput::DoubleTap`] ([`TouchButtons::next_input`]).
18
19use embassy_time::{Duration, Instant, Timer};
20
21use crate::driver::ft6336u;
22use crate::io::buttons::{ButtonAction, ButtonEvent, ButtonId, ButtonTiming};
23use crate::io::shared_i2c::SharedI2cBus;
24
25pub struct TouchButtonsConfig {
26    /// Touch-poll interval.
27    pub poll_ms: u64,
28    /// Hold time before a press becomes [`ButtonAction::Long`].
29    pub long_press_ms: u64,
30    /// Max gap between taps that still counts as a multi-tap. Set to `0` to
31    /// disable multi-tap counting entirely: each tap emits `Short(1)` on the next
32    /// poll after release (~`poll_ms`), with no counting delay — for
33    /// latency-sensitive input like an encoder (#58). See
34    /// [`with_timing`](Self::with_timing) /
35    /// [`ButtonTiming::immediate_single_press`] for the cross-driver preset.
36    pub multi_tap_ms: u64,
37    /// Zone strip: touches above this Y are ignored.
38    pub zone_y_min: u16,
39    /// X below this is [`ButtonId::Left`].
40    pub zone_x_left: u16,
41    /// X below this (and ≥ `zone_x_left`) is [`ButtonId::Center`]; above,
42    /// [`ButtonId::Right`].
43    pub zone_x_right: u16,
44    /// Travel, in px on either axis, beyond which a stroke is a swipe and
45    /// emits nothing.
46    pub tap_slop_px: u16,
47    /// Max gap from the first tap's release to the second's touch-down for a
48    /// [`TouchInput::DoubleTap`]. `0` disables it.
49    pub double_tap_ms: u64,
50}
51
52/// Bottom 40 px strip (y ≥ 200) split into thirds.
53impl Default for TouchButtonsConfig {
54    fn default() -> Self {
55        Self {
56            poll_ms: 20,
57            long_press_ms: 500,
58            multi_tap_ms: 300,
59            zone_y_min: 200,
60            zone_x_left: 107,
61            zone_x_right: 213,
62            tap_slop_px: 24,
63            double_tap_ms: 400,
64        }
65    }
66}
67
68impl TouchButtonsConfig {
69    /// [`Default`] geometry/poll, but with the press-decoding timings taken from
70    /// the cross-driver [`ButtonTiming`] — the same type and presets the Fire27
71    /// physical buttons take (`ButtonResources::into_buttons_with_timing`, feature
72    /// `buttons`). Use [`ButtonTiming::immediate_single_press`] for instant
73    /// single-press input (an encoder).
74    pub fn with_timing(timing: ButtonTiming) -> Self {
75        Self {
76            long_press_ms: timing.long_press_ms,
77            multi_tap_ms: timing.multi_tap_ms,
78            ..Self::default()
79        }
80    }
81}
82
83/// Everything the touch panel can mean: a key, or a double tap above the strip.
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub enum TouchInput {
86    Button(ButtonEvent),
87    DoubleTap,
88}
89
90/// One contact, finger down to finger up.
91#[derive(Clone, Copy)]
92struct Stroke {
93    start: (u16, u16),
94    start_ms: u64,
95    /// Key zone it started in; `None` = the screen above the strip.
96    zone: Option<ButtonId>,
97    /// Travelled past the slop at some point: a swipe, never a tap.
98    moved: bool,
99    long_fired: bool,
100}
101
102/// The stroke decoder: no I/O, no clock, so it is a pure function of the
103/// samples it is fed.
104struct Decoder {
105    stroke: Option<Stroke>,
106    // multi-tap state
107    tap_zone: Option<ButtonId>,
108    tap_count: usize,
109    last_release_ms: u64,
110    /// Release time of a still screen tap still waiting for its second.
111    screen_tap_ms: Option<u64>,
112}
113
114impl Decoder {
115    const fn new() -> Self {
116        Self {
117            stroke: None,
118            tap_zone: None,
119            tap_count: 0,
120            last_release_ms: 0,
121            screen_tap_ms: None,
122        }
123    }
124
125    fn classify(c: &TouchButtonsConfig, (x, y): (u16, u16)) -> Option<ButtonId> {
126        if y < c.zone_y_min {
127            return None;
128        }
129        Some(if x < c.zone_x_left {
130            ButtonId::Left
131        } else if x < c.zone_x_right {
132            ButtonId::Center
133        } else {
134            ButtonId::Right
135        })
136    }
137
138    /// Feed one poll's sample; returns what it completed, if anything.
139    fn step(
140        &mut self,
141        c: &TouchButtonsConfig,
142        now_ms: u64,
143        touch: Option<(u16, u16)>,
144    ) -> Option<TouchInput> {
145        if touch.is_none()
146            && let Some(s) = self.stroke.take()
147        {
148            if s.moved || s.long_fired {
149                self.screen_tap_ms = None;
150                return None;
151            }
152            return match s.zone {
153                Some(zone) => self.key_tap(zone, now_ms),
154                None => self.screen_tap(c, s, now_ms),
155            };
156        }
157        match (self.stroke.as_mut(), touch) {
158            // No stroke, still no touch: flush a pending multi-tap once the
159            // tap window has passed.
160            (None, None) => {
161                if self.tap_count > 0 && now_ms - self.last_release_ms > c.multi_tap_ms {
162                    let id = self.tap_zone.take()?;
163                    let count = core::mem::take(&mut self.tap_count);
164                    return Some(TouchInput::Button(ButtonEvent {
165                        id,
166                        action: ButtonAction::Short(count),
167                    }));
168                }
169                None
170            }
171            (None, Some(p)) => {
172                self.stroke = Some(Stroke {
173                    start: p,
174                    start_ms: now_ms,
175                    zone: Self::classify(c, p),
176                    moved: false,
177                    long_fired: false,
178                });
179                None
180            }
181            (Some(s), Some((x, y))) => {
182                if x.abs_diff(s.start.0).max(y.abs_diff(s.start.1)) > c.tap_slop_px {
183                    s.moved = true;
184                }
185                let zone = s.zone.filter(|_| !s.moved && !s.long_fired)?;
186                if now_ms - s.start_ms <= c.long_press_ms {
187                    return None;
188                }
189                s.long_fired = true;
190                // A long press cancels any pending multi-tap.
191                self.tap_count = 0;
192                self.tap_zone = None;
193                Some(TouchInput::Button(ButtonEvent {
194                    id: zone,
195                    action: ButtonAction::Long,
196                }))
197            }
198            // Released: handled above.
199            (Some(_), None) => None,
200        }
201    }
202
203    fn key_tap(&mut self, zone: ButtonId, now_ms: u64) -> Option<TouchInput> {
204        self.last_release_ms = now_ms;
205        if self.tap_zone == Some(zone) {
206            // Same zone — accumulate the multi-tap.
207            self.tap_count += 1;
208            return None;
209        }
210        // Different zone or first tap — flush the old zone's taps (if any),
211        // start counting the new.
212        let pending = self.tap_zone.replace(zone).filter(|_| self.tap_count > 0);
213        let count = core::mem::replace(&mut self.tap_count, 1);
214        pending.map(|id| {
215            TouchInput::Button(ButtonEvent {
216                id,
217                action: ButtonAction::Short(count),
218            })
219        })
220    }
221
222    fn screen_tap(&mut self, c: &TouchButtonsConfig, s: Stroke, now_ms: u64) -> Option<TouchInput> {
223        // A still hold is not a tap either.
224        if c.double_tap_ms == 0 || now_ms - s.start_ms > c.long_press_ms {
225            self.screen_tap_ms = None;
226            return None;
227        }
228        match self.screen_tap_ms.take() {
229            Some(first) if s.start_ms - first <= c.double_tap_ms => Some(TouchInput::DoubleTap),
230            _ => {
231                self.screen_tap_ms = Some(now_ms);
232                None
233            }
234        }
235    }
236}
237
238/// The emulated three-button strip. Construct once, then await
239/// [`next_event`](Self::next_event) in a loop.
240pub struct TouchButtons {
241    i2c: &'static SharedI2cBus,
242    config: TouchButtonsConfig,
243    /// FT6336U probed and answering (it may need AXP2101 power-up time).
244    probed: bool,
245    decoder: Decoder,
246}
247
248impl TouchButtons {
249    /// Construct with the cross-driver [`ButtonTiming`] (default geometry/poll) —
250    /// the touch-side counterpart of `ButtonResources::into_buttons_with_timing`
251    /// (feature `buttons`). Shorthand for
252    /// `new(i2c, TouchButtonsConfig::with_timing(timing))`.
253    pub fn with_timing(i2c: &'static SharedI2cBus, timing: ButtonTiming) -> Self {
254        Self::new(i2c, TouchButtonsConfig::with_timing(timing))
255    }
256
257    pub fn new(i2c: &'static SharedI2cBus, config: TouchButtonsConfig) -> Self {
258        Self {
259            i2c,
260            config,
261            probed: false,
262            decoder: Decoder::new(),
263        }
264    }
265
266    /// Wait for the FT6336U to appear on the bus (first call only — the
267    /// controller may need AXP2101 power-up time after a cold boot).
268    async fn probe(&mut self) {
269        let mut attempts = 0u32;
270        loop {
271            match ft6336u::read_touch(self.i2c).await {
272                Ok(_) => {
273                    info!("FT6336U found at 0x{:02X}", ft6336u::ADDR);
274                    self.probed = true;
275                    return;
276                }
277                Err(e) => {
278                    attempts += 1;
279                    if attempts <= 3 || attempts.is_multiple_of(50) {
280                        warn!("FT6336U probe #{}: {:?}", attempts, e);
281                    }
282                }
283            }
284            Timer::after(Duration::from_millis(100)).await;
285        }
286    }
287
288    /// Poll the touch controller until a stroke completes a key or a double
289    /// tap. Stroke state persists across calls, so awaiting this in a loop
290    /// loses no events.
291    pub async fn next_input(&mut self) -> TouchInput {
292        if !self.probed {
293            self.probe().await;
294        }
295        loop {
296            Timer::after(Duration::from_millis(self.config.poll_ms)).await;
297            let touch = match ft6336u::read_touch(self.i2c).await {
298                Ok(t) => t,
299                Err(e) => {
300                    warn!("touch I2C err: {:?}", e);
301                    continue;
302                }
303            };
304            if let Some(input) = self
305                .decoder
306                .step(&self.config, Instant::now().as_millis(), touch)
307            {
308                return input;
309            }
310        }
311    }
312
313    /// [`next_input`](Self::next_input), keys only: a double tap is dropped.
314    pub async fn next_event(&mut self) -> ButtonEvent {
315        loop {
316            if let TouchInput::Button(e) = self.next_input().await {
317                return e;
318            }
319        }
320    }
321}