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
#[macro_use]
extern crate log;
use evdev;
use evdev::Device;
use std::thread;
use std::time::Duration;
mod manager;
pub use self::manager::Manager;
use evdev::raw::input_event;
pub type BoxedCallback = Box<FnMut() -> () + std::marker::Send>;
pub fn execute_on_click(button_mac_address: &str, mut callback: BoxedCallback) {
loop {
if let Some(button) = find_device_with_mac(&button_mac_address) {
info!("Listening to events from {:?}", &button_mac_address);
execute_on_every_click_until_events_error(button, &mut callback);
thread::sleep(Duration::from_millis(500));
}
}
}
fn find_device_with_mac(target_mac_address: &str) -> Option<Device> {
evdev::enumerate().into_iter().find(|device| {
if let Some(mac_address) = device.unique_name() {
target_mac_address.as_bytes() == mac_address.as_bytes()
} else {
false
}
})
}
fn execute_on_every_click_until_events_error(mut button: Device, callback: &mut BoxedCallback) {
loop {
match button.events_no_sync() {
Ok(events) => events
.filter(is_pressed_volume_up)
.for_each(|_| {
debug!("Callback triggered");
callback()
}),
Err(error) => {
error!("Error listening to events ({}).", error.errno().desc());
break;
}
}
}
}
fn is_pressed_volume_up(event: &input_event) -> bool {
evdev::KEY.number::<u16>() == event._type
&& evdev::Key::KEY_VOLUMEUP as u16 == event.code
&& 1 == event.value
}