ev3dev_lang_rust/
ev3_button_functions.rs

1/// Helper macro to create all necessary functions for a button
2#[macro_export]
3macro_rules! ev3_button_functions {
4    ($button_name:ident) => {
5        paste! {
6            #[doc = "Check if the `" $button_name "` button is pressed."]
7            #[doc = "```no_run"]
8            #[doc = "use ev3dev_lang_rust::Button;"]
9            #[doc = "use std::thread;"]
10            #[doc = "use std::time::Duration;"]
11            #[doc = ""]
12            #[doc = "# fn main() -> ev3dev_lang_rust::Ev3Result<()> {"]
13            #[doc = "let button = Button::new()?;"]
14            #[doc = ""]
15            #[doc = "loop {"]
16            #[doc = "    button.process();"]
17            #[doc = "    println!(\"Is '" $button_name "' pressed: {}\", button.is_" $button_name "());"]
18            #[doc = "    thread::sleep(Duration::from_millis(100));"]
19            #[doc = "}"]
20            #[doc = "# }"]
21            #[doc = "```"]
22            pub fn [<is_ $button_name>] (&self) -> bool {
23                self.button_handler.borrow().get_button_state(stringify!($button_name))
24            }
25
26            #[doc = "Set an event handler, that is called by `process()` if the pressed state of the `" $button_name "` button changes."]
27            #[doc = "```no_run"]
28            #[doc = "use ev3dev_lang_rust::Button;"]
29            #[doc = "use std::thread;"]
30            #[doc = "use std::time::Duration;"]
31            #[doc = ""]
32            #[doc = "# fn main() -> ev3dev_lang_rust::Ev3Result<()> {"]
33            #[doc = "let mut button = Button::new()?;"]
34            #[doc = ""]
35            #[doc = "button.set_" $button_name "_handler(|is_pressed| {"]
36            #[doc = "    println!(\"Is '" $button_name "' pressed: {}\", is_pressed);"]
37            #[doc = "});"]
38            #[doc = ""]
39            #[doc = "loop {"]
40            #[doc = "    button.process();"]
41            #[doc = "    thread::sleep(Duration::from_millis(100));"]
42            #[doc = "}"]
43            #[doc = "# }"]
44            #[doc = "```"]
45            pub fn [<set_ $button_name _handler>](&mut self, handler: impl Fn(bool) + 'static) {
46                self.button_handler
47                    .borrow_mut()
48                    .set_button_handler(stringify!($button_name), Some(Box::new(handler)));
49            }
50
51            #[doc = "Removes the event handler of the `" $button_name "` button."]
52            pub fn [<remove_ $button_name _handler>](&mut self) {
53                self.button_handler
54                    .borrow_mut()
55                    .set_button_handler(stringify!($button_name), None);
56            }
57        }
58    };
59}