device-envoy-rp 0.1.0

Build Pico applications with LED panels, easy Wi-Fi, and composable device abstractions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Background button monitoring with a spawned task.
//!
//! See the [`button_watch!`](crate::button_watch!) macro for usage and
//! [`ButtonWatchGenerated`](super::button_watch_generated::ButtonWatchGenerated) for a sample of a generated type.

use core::sync::atomic::{AtomicBool, Ordering};
use embassy_rp::Peri;
use embassy_rp::gpio::{Input, Pin, Pull};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use embassy_time::Timer;

use super::{PressDuration, PressedTo};

// ============================================================================
// ButtonWatchStaticRp - Static resources for button monitoring
// ============================================================================

// Must be public for macro expansion in downstream crates, but not user-facing API.
#[doc(hidden)]
pub struct ButtonWatchStaticRp {
    signal: Signal<CriticalSectionRawMutex, PressDuration>,
    state_signal: Signal<CriticalSectionRawMutex, bool>,
    state_changed_signal: Signal<CriticalSectionRawMutex, ()>,
    initialized_signal: Signal<CriticalSectionRawMutex, ()>,
    is_pressed: AtomicBool,
    initialized: AtomicBool,
}

impl ButtonWatchStaticRp {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            signal: Signal::new(),
            state_signal: Signal::new(),
            state_changed_signal: Signal::new(),
            initialized_signal: Signal::new(),
            is_pressed: AtomicBool::new(false),
            initialized: AtomicBool::new(false),
        }
    }

    #[must_use]
    pub const fn signal(&self) -> &Signal<CriticalSectionRawMutex, PressDuration> {
        &self.signal
    }

    #[must_use]
    pub const fn state_signal(&self) -> &Signal<CriticalSectionRawMutex, bool> {
        &self.state_signal
    }

    #[must_use]
    pub const fn state_changed_signal(&self) -> &Signal<CriticalSectionRawMutex, ()> {
        &self.state_changed_signal
    }

    #[must_use]
    pub const fn initialized_signal(&self) -> &Signal<CriticalSectionRawMutex, ()> {
        &self.initialized_signal
    }

    #[must_use]
    pub const fn is_pressed(&self) -> &AtomicBool {
        &self.is_pressed
    }

    #[must_use]
    pub const fn initialized(&self) -> &AtomicBool {
        &self.initialized
    }
}

// ============================================================================
// ButtonWatchRp - Handle for background button monitoring
// ============================================================================

// Must be public for macro expansion in downstream crates, but not user-facing API.
// Users interact with the macro-generated structs (e.g., ButtonWatchGenerated), not this type directly.
#[doc(hidden)]
pub struct ButtonWatchRp {
    signal: &'static Signal<CriticalSectionRawMutex, PressDuration>,
    state_signal: &'static Signal<CriticalSectionRawMutex, bool>,
    state_changed_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    initialized_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    is_pressed: &'static AtomicBool,
    initialized: &'static AtomicBool,
}

impl ButtonWatchRp {
    #[must_use]
    pub fn new(button_watch_static: &'static ButtonWatchStaticRp) -> Self {
        Self {
            signal: button_watch_static.signal(),
            state_signal: button_watch_static.state_signal(),
            state_changed_signal: button_watch_static.state_changed_signal(),
            initialized_signal: button_watch_static.initialized_signal(),
            is_pressed: button_watch_static.is_pressed(),
            initialized: button_watch_static.initialized(),
        }
    }

    pub async fn wait_until_initialized(&self) {
        if self.initialized.load(Ordering::Acquire) {
            return;
        }
        self.initialized_signal.wait().await;
    }

    pub async fn wait_for_state_change(&self) {
        self.state_changed_signal.wait().await;
    }
}

impl device_envoy_core::button::__ButtonMonitor for ButtonWatchRp {
    fn is_pressed_raw(&self) -> bool {
        self.is_pressed.load(Ordering::Relaxed)
    }

    async fn wait_until_pressed_state(&mut self, pressed: bool) {
        if self.is_pressed.load(Ordering::Relaxed) == pressed {
            return;
        }

        loop {
            let state = self.state_signal.wait().await;
            if state == pressed {
                return;
            }
        }
    }
}

impl device_envoy_core::button::Button for ButtonWatchRp {
    async fn wait_for_press_duration(&mut self) -> PressDuration {
        self.signal.wait().await
    }
}

// ============================================================================
// Background task implementation
// ============================================================================

/// Background task that monitors button state and fires events.
///
/// Never call directly - spawned automatically by the [`button_watch!`](crate::button_watch!) macro.
#[doc(hidden)]
pub async fn button_watch_task<P: Pin>(
    pin: Peri<'static, P>,
    pressed_to: PressedTo,
    signal: &'static Signal<CriticalSectionRawMutex, PressDuration>,
    state_signal: &'static Signal<CriticalSectionRawMutex, bool>,
    state_changed_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    initialized_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    is_pressed: &'static AtomicBool,
    initialized: &'static AtomicBool,
) -> ! {
    let pull = match pressed_to {
        PressedTo::Voltage => Pull::Down,
        PressedTo::Ground => Pull::Up,
    };
    let mut input = Input::new(pin, pull);
    let mut input_button = InputButton {
        input: &mut input,
        pressed_to,
    };
    signal_press_durations(
        &mut input_button,
        signal,
        state_signal,
        state_changed_signal,
        initialized_signal,
        is_pressed,
        initialized,
    )
    .await
}

struct InputButton<'a> {
    input: &'a mut Input<'static>,
    pressed_to: PressedTo,
}

impl device_envoy_core::button::__ButtonMonitor for InputButton<'_> {
    fn is_pressed_raw(&self) -> bool {
        self.pressed_to.is_pressed(self.input.is_high())
    }

    async fn wait_until_pressed_state(&mut self, pressed: bool) {
        match (pressed, self.pressed_to) {
            (true, PressedTo::Voltage) | (false, PressedTo::Ground) => {
                self.input.wait_for_high().await;
            }
            (true, PressedTo::Ground) | (false, PressedTo::Voltage) => {
                self.input.wait_for_low().await;
            }
        }
    }
}

async fn signal_press_durations<B: device_envoy_core::button::__ButtonMonitor>(
    button: &mut B,
    signal: &'static Signal<CriticalSectionRawMutex, PressDuration>,
    state_signal: &'static Signal<CriticalSectionRawMutex, bool>,
    state_changed_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    initialized_signal: &'static Signal<CriticalSectionRawMutex, ()>,
    is_pressed: &'static AtomicBool,
    initialized: &'static AtomicBool,
) -> ! {
    let initial_pressed = <B as device_envoy_core::button::__ButtonMonitor>::is_pressed_raw(button);
    is_pressed.store(initial_pressed, Ordering::Relaxed);
    state_signal.signal(initial_pressed);
    initialized.store(true, Ordering::Release);
    initialized_signal.signal(());

    loop {
        <B as device_envoy_core::button::__ButtonMonitor>::wait_until_pressed_state(button, false)
            .await;

        <B as device_envoy_core::button::__ButtonMonitor>::wait_until_pressed_state(button, true)
            .await;
        is_pressed.store(true, Ordering::Relaxed);
        state_signal.signal(true);
        state_changed_signal.signal(());

        Timer::after(device_envoy_core::button::BUTTON_DEBOUNCE_DELAY).await;
        if !<B as device_envoy_core::button::__ButtonMonitor>::is_pressed_raw(button) {
            is_pressed.store(false, Ordering::Relaxed);
            state_signal.signal(false);
            state_changed_signal.signal(());
            continue;
        }

        let press_duration = embassy_futures::select::select(
            <B as device_envoy_core::button::__ButtonMonitor>::wait_until_pressed_state(
                button, false,
            ),
            Timer::after(device_envoy_core::button::LONG_PRESS_DURATION),
        )
        .await;

        match press_duration {
            embassy_futures::select::Either::First(()) => {
                is_pressed.store(false, Ordering::Relaxed);
                state_signal.signal(false);
                state_changed_signal.signal(());
                signal.signal(PressDuration::Short);
            }
            embassy_futures::select::Either::Second(()) => {
                signal.signal(PressDuration::Long);
                <B as device_envoy_core::button::__ButtonMonitor>::wait_until_pressed_state(
                    button, false,
                )
                .await;
                is_pressed.store(false, Ordering::Relaxed);
                state_signal.signal(false);
                state_changed_signal.signal(());
            }
        }
    }
}

// ============================================================================
// button_watch! macro
// ============================================================================

/// Creates a button monitoring device abstraction with a background task.
///
/// This macro creates a button monitor that runs in a dedicated background task,
/// providing continuous monitoring without interruption.
///
/// See [`ButtonWatchGenerated`](crate::button::button_watch_generated::ButtonWatchGenerated) for a sample of what the macro generates.
///
/// **Syntax:**
///
/// ```text
/// button_watch! {
///     [<attributes>]
///     [<visibility>] <Name> {
///         pin: <pin_ident>,
///     }
/// }
/// ```
///
/// # Constructors
///
/// - [`new()`](crate::button::button_watch_generated::ButtonWatchGenerated::new) — Create from a pin
///
/// # Use Cases
///
/// Use `button_watch!` instead of [`ButtonRp`](super::ButtonRp) when you need continuous monitoring
/// that works even in fast loops or `select()` operations. [`ButtonRp`](super::ButtonRp) starts
/// fresh monitoring on each call to `wait_for_press()`, which can miss events in busy loops.
///
///  # Parameters
///
/// - `name`: The struct name for the button watch device
/// - `pin`: The GPIO pin connected to the button
///
/// Optional:
/// - `vis`: Visibility modifier (default: private)
///
/// # Example
///
/// ```rust,no_run
/// # #![no_std]
/// # #![no_main]
/// use device_envoy_rp::button_watch;
/// use device_envoy_rp::button::PressDuration;
/// use device_envoy_rp::button::PressedTo;
/// use device_envoy_rp::button::Button as _;
/// use embassy_executor::Spawner;
/// # #[panic_handler]
/// # fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} }
///
/// button_watch! {
///     ButtonWatch13 {
///         pin: PIN_13,
///     }
/// }
///
/// async fn example(
///     p: embassy_rp::Peripherals,
///     spawner: Spawner,
/// ) -> device_envoy_rp::Result<()> {
///     // Create the button monitor (spawns background task automatically)
///     let mut button_watch13 = ButtonWatch13::new(p.PIN_13, PressedTo::Ground, spawner)
///         .await?;
///
///     loop {
///         // Wait for button press - never misses events even if this loop is slow
///         match button_watch13.wait_for_press_duration().await {
///             PressDuration::Short => {
///                 // Handle short press
/// #               break;
///             }
///             PressDuration::Long => {
///                 // Handle long press
/// #               break;
///             }
///         }
///     }
///     Ok(())
/// }
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! button_watch {
    ($($tt:tt)*) => { $crate::__button_watch_impl! { $($tt)* } };
}

/// Implementation macro for `button_watch!`.
///
/// Do not call directly - use [`button_watch!`](crate::button_watch!) instead.
#[doc(hidden)]
#[macro_export]
macro_rules! __button_watch_impl {
    // Entry point with optional visibility
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident {
            pin: $pin:ident,
        }
    ) => {
        $crate::__button_watch_impl! {
            @impl
            meta: [$(#[$meta])*],
            vis: $vis,
            name: $name,
            pin: $pin
        }
    };

    // Entry point with default (private) visibility
    (
        $(#[$meta:meta])*
        $name:ident {
            pin: $pin:ident,
        }
    ) => {
        $crate::__button_watch_impl! {
            @impl
            meta: [$(#[$meta])*],
            vis: ,
            name: $name,
            pin: $pin
        }
    };

    // Internal implementation
    (
        @impl
        meta: [$(#[$meta:meta])*],
        vis: $vis:vis,
        name: $name:ident,
        pin: $pin:ident
    ) => {
        ::paste::paste! {
            $(#[$meta])*
            #[doc = concat!(
                "Button monitor generated by [`button_watch!`].\n\n",
                "Monitors button presses in a background task. ",
                "See the [button_watch module documentation](mod@$crate::button) for usage."
            )]
            $vis struct $name {
                button_watch: $crate::button::ButtonWatchRp,
            }

            impl $name {
                /// Creates a new button monitor and spawns its background task.
                ///
                /// # Parameters
                ///
                /// - `pin`: GPIO pin for the button
                /// - `pressed_to`: How the button is wired ([`PressedTo::Ground`] or [`PressedTo::Voltage`])
                /// - `spawner`: Task spawner for background operations
                ///
                /// # Errors
                ///
                /// Returns an error if the background task cannot be spawned.
                pub async fn new(
                    pin: impl Into<::embassy_rp::Peri<'static, ::embassy_rp::peripherals::$pin>>,
                    pressed_to: $crate::button::PressedTo,
                    spawner: ::embassy_executor::Spawner,
                ) -> $crate::Result<&'static mut Self> {
                    static BUTTON_WATCH_STATIC: $crate::button::ButtonWatchStaticRp =
                        $crate::button::ButtonWatchStaticRp::new();
                    static BUTTON_WATCH_CELL: ::static_cell::StaticCell<$name> =
                        ::static_cell::StaticCell::new();

                    let pin = pin.into();
                    let task_token = [<$name:snake _task>](
                        pin,
                        pressed_to,
                        BUTTON_WATCH_STATIC.signal(),
                        BUTTON_WATCH_STATIC.state_signal(),
                        BUTTON_WATCH_STATIC.state_changed_signal(),
                        BUTTON_WATCH_STATIC.initialized_signal(),
                        BUTTON_WATCH_STATIC.is_pressed(),
                        BUTTON_WATCH_STATIC.initialized(),
                    );
                    spawner.spawn(task_token.map_err($crate::Error::TaskSpawn)?);

                    let button_watch = $crate::button::ButtonWatchRp::new(
                        &BUTTON_WATCH_STATIC,
                    );
                    button_watch.wait_until_initialized().await;

                    let instance = BUTTON_WATCH_CELL.init($name { button_watch });
                    Ok(instance)
                }

            }

            impl ::core::ops::Deref for $name {
                type Target = $crate::button::ButtonWatchRp;

                fn deref(&self) -> &Self::Target {
                    &self.button_watch
                }
            }

            impl $crate::button::__ButtonMonitor for $name {
                fn is_pressed_raw(&self) -> bool {
                    <$crate::button::ButtonWatchRp as $crate::button::Button>::is_pressed(
                        &self.button_watch,
                    )
                }

                async fn wait_until_pressed_state(&mut self, pressed: bool) {
                    <$crate::button::ButtonWatchRp as $crate::button::__ButtonMonitor>::wait_until_pressed_state(
                        &mut self.button_watch,
                        pressed,
                    )
                    .await
                }
            }

            impl $crate::button::Button for $name {
                async fn wait_for_press_duration(&mut self) -> $crate::button::PressDuration {
                    <$crate::button::ButtonWatchRp as $crate::button::Button>::wait_for_press_duration(
                        &mut self.button_watch,
                    )
                    .await
                }
            }

            #[::embassy_executor::task]
            async fn [<$name:snake _task>](
                pin: ::embassy_rp::Peri<'static, ::embassy_rp::peripherals::$pin>,
                pressed_to: $crate::button::PressedTo,
                signal: &'static ::embassy_sync::signal::Signal<
                    ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
                    $crate::button::PressDuration
                >,
                state_signal: &'static ::embassy_sync::signal::Signal<
                    ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
                    bool
                >,
                state_changed_signal: &'static ::embassy_sync::signal::Signal<
                    ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
                    ()
                >,
                initialized_signal: &'static ::embassy_sync::signal::Signal<
                    ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
                    ()
                >,
                is_pressed: &'static ::core::sync::atomic::AtomicBool,
                initialized: &'static ::core::sync::atomic::AtomicBool,
            ) -> ! {
                $crate::button::button_watch_task(
                    pin,
                    pressed_to,
                    signal,
                    state_signal,
                    state_changed_signal,
                    initialized_signal,
                    is_pressed,
                    initialized,
                )
                .await
            }

        }
    };
}