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
//! EV3 Buttons
//!
//! ```no_run
//! use ev3dev_lang_rust::Ev3Button;
//! use std::thread;
//! use std::time::Duration;
//!
//! # fn main() -> ev3dev_lang_rust::Ev3Result<()> {
//! let button = Ev3Button::new()?;
//!
//! loop {
//!     button.process();
//!
//!     println!("Is 'up' pressed: {}", button.is_up());
//!     println!("Pressed buttons: {:?}", button.get_pressed_buttons());
//!
//!     thread::sleep(Duration::from_millis(100));
//! }
//! # }
//! ```

use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::rc::Rc;

use crate::Ev3Result;

const KEY_BUF_LEN: usize = 96;
const EVIOCGKEY: u32 = 2_153_792_792;

/// Helper struct for ButtonFileHandler.
struct FileMapEntry {
    pub file: File,
    pub buffer_cache: [u8; KEY_BUF_LEN],
}
// Manuelly implement Debug cause `buffer_cache` does not implement Debug.
impl fmt::Debug for FileMapEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileMapEntry")
            .field("file", &self.file)
            .finish()
    }
}

/// Helper struct for ButtonFileHandler.
#[derive(Debug)]
struct ButtonMapEntry {
    pub file_name: String,
    pub key_code: u32,
}

/// This implementation depends on the availability of the EVIOCGKEY ioctl
/// to be able to read the button state buffer. See Linux kernel source
/// in /include/uapi/linux/input.h for details.
#[derive(Debug)]
struct ButtonFileHandler {
    file_map: HashMap<String, FileMapEntry>,
    button_map: HashMap<String, ButtonMapEntry>,
    pressed_buttons: HashSet<String>,
}

impl ButtonFileHandler {
    /// Create a new instance.
    fn new() -> Self {
        ButtonFileHandler {
            file_map: HashMap::new(),
            button_map: HashMap::new(),
            pressed_buttons: HashSet::new(),
        }
    }

    /// Add a button the the file handler.
    fn add_button(&mut self, name: &str, file_name: &str, key_code: u32) -> Ev3Result<()> {
        if !self.file_map.contains_key(file_name) {
            let file = File::open(file_name)?;
            let buffer_cache = [0u8; KEY_BUF_LEN];

            self.file_map
                .insert(file_name.to_owned(), FileMapEntry { file, buffer_cache });
        }

        self.button_map.insert(
            name.to_owned(),
            ButtonMapEntry {
                file_name: file_name.to_owned(),
                key_code,
            },
        );

        Ok(())
    }

    fn get_pressed_buttons(&self) -> HashSet<String> {
        self.pressed_buttons.clone()
    }

    /// Check if a button is pressed.
    fn get_button_state(&self, name: &str) -> bool {
        self.pressed_buttons.contains(name)
    }

    /// Check for currenly pressed buttons. If the new state differs from the
    /// old state, call the appropriate button event handlers.
    fn process(&mut self) {
        for entry in self.file_map.values_mut() {
            unsafe {
                libc::ioctl(
                    entry.file.as_raw_fd(),
                    EVIOCGKEY.into(),
                    &mut entry.buffer_cache,
                );
            }
        }

        self.pressed_buttons.clear();

        for (
            btn_name,
            ButtonMapEntry {
                file_name,
                key_code,
            },
        ) in self.button_map.iter()
        {
            let buffer = &self.file_map[file_name].buffer_cache;

            if (buffer[(key_code / 8) as usize] & 1 << (key_code % 8)) != 0 {
                self.pressed_buttons.insert(btn_name.to_owned());
            }
        }
    }
}

/// Ev3 brick button handler. Opens the corresponding `/dev/input` file handlers.
///
/// This implementation depends on the availability of the EVIOCGKEY ioctl
/// to be able to read the button state buffer. See Linux kernel source
/// in /include/uapi/linux/input.h for details.
///
/// ```no_run
/// use ev3dev_lang_rust::Ev3Button;
/// use std::thread;
/// use std::time::Duration;
///
/// # fn main() -> ev3dev_lang_rust::Ev3Result<()> {
/// let button = Ev3Button::new()?;
///
/// loop {
///     button.process();
///
///     println!("Is 'up' pressed: {}", button.is_up());
///     println!("Pressed buttons: {:?}", button.get_pressed_buttons());
///
///     thread::sleep(Duration::from_millis(100));
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Ev3Button {
    button_handler: Rc<RefCell<ButtonFileHandler>>,
}

impl Ev3Button {
    /// Ev3 brick button handler. Opens the corresponding `/dev/input` file handlers.
    pub fn new() -> Ev3Result<Self> {
        let mut handler = ButtonFileHandler::new();

        handler.add_button("up", "/dev/input/by-path/platform-gpio_keys-event", 103)?;
        handler.add_button("down", "/dev/input/by-path/platform-gpio_keys-event", 108)?;
        handler.add_button("left", "/dev/input/by-path/platform-gpio_keys-event", 105)?;
        handler.add_button("right", "/dev/input/by-path/platform-gpio_keys-event", 106)?;
        handler.add_button("enter", "/dev/input/by-path/platform-gpio_keys-event", 28)?;
        handler.add_button(
            "backspace",
            "/dev/input/by-path/platform-gpio_keys-event",
            14,
        )?;

        Ok(Self {
            button_handler: Rc::new(RefCell::new(handler)),
        })
    }

    /// Check for currenly pressed buttons. If the new state differs from the
    /// old state, call the appropriate button event handlers.
    pub fn process(&self) {
        self.button_handler.borrow_mut().process()
    }

    /// Get all pressed buttons by name.
    pub fn get_pressed_buttons(&self) -> HashSet<String> {
        self.button_handler.borrow().get_pressed_buttons()
    }

    /// Check if 'up' button is pressed.
    pub fn is_up(&self) -> bool {
        self.button_handler.borrow().get_button_state("up")
    }

    /// Check if 'down' button is pressed.
    pub fn is_down(&self) -> bool {
        self.button_handler.borrow().get_button_state("down")
    }

    /// Check if 'left' button is pressed.
    pub fn is_left(&self) -> bool {
        self.button_handler.borrow().get_button_state("left")
    }

    /// Check if 'right' button is pressed.
    pub fn is_right(&self) -> bool {
        self.button_handler.borrow().get_button_state("right")
    }

    /// Check if 'enter' button is pressed.
    pub fn is_enter(&self) -> bool {
        self.button_handler.borrow().get_button_state("enter")
    }

    /// Check if 'backspace' button is pressed.
    pub fn is_backspace(&self) -> bool {
        self.button_handler.borrow().get_button_state("backspace")
    }
}