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
//! LEGO EV3 infrared sensor.

use super::{Sensor, SensorPort};
use crate::{sensor_mode, Attribute, Device, Driver, Ev3Error, Ev3Result};
use std::cell::RefCell;
use std::collections::HashSet;
use std::fmt;
use std::rc::Rc;

/// LEGO EV3 infrared sensor.
#[derive(Debug, Clone, Device, Sensor)]
pub struct InfraredSensor {
    driver: Driver,
}

impl InfraredSensor {
    fn new(driver: Driver) -> Self {
        Self { driver }
    }

    findable!(
        "lego-sensor",
        ["lego-ev3-ir"],
        SensorPort,
        "InfraredrSensor",
        "in"
    );

    sensor_mode!(
        "IR-PROX",
        MODE_IR_PROX,
        "Proximity",
        set_mode_ir_prox,
        is_mode_ir_prox
    );
    sensor_mode!(
        "IR-SEEK",
        MODE_IR_SEEK,
        "IR Seeker",
        set_mode_ir_seek,
        is_mode_ir_seek
    );
    sensor_mode!(
        "IR-REMOTE",
        MODE_IR_REMOTE,
        "IR Remote Control",
        set_mode_ir_remote,
        is_mode_ir_remote
    );
    sensor_mode!(
        "IR-REM-A",
        MODE_IR_REM_A,
        "IR Remote Control",
        set_mode_ir_rem_a,
        is_mode_ir_rem_a
    );
    sensor_mode!(
        "IR-S-ALT",
        MODE_IR_S_ALT,
        "Alternate IR Seeker ???",
        set_mode_ir_s_alt,
        is_mode_ir_s_alt
    );
    sensor_mode!(
        "IR-CAL",
        MODE_IR_CAL,
        "Calibration ???",
        set_mode_ir_cal,
        is_mode_ir_cal
    );

    /// Get the proximity distance, in the range 0-100 (pct).
    pub fn get_distance(&self) -> Ev3Result<i32> {
        self.get_value0()
    }
}

struct RemoteControlHelper {
    last_buttons: i32,
    pressed_buttons: HashSet<String>,
}

impl RemoteControlHelper {
    fn new() -> RemoteControlHelper {
        RemoteControlHelper {
            last_buttons: 0,
            pressed_buttons: HashSet::new(),
        }
    }

    fn contains(&self, button: &str) -> bool {
        self.pressed_buttons.contains(button)
    }
}

/// Seeks EV3 Remote Controller in beacon mode.
#[derive(Clone)]
pub struct RemoteControl {
    sensor: InfraredSensor,
    channel: u8,
    helper: Rc<RefCell<RemoteControlHelper>>,
}

// Manuelly implement Debug cause `buffer_cache` does not implement Debug.
impl fmt::Debug for RemoteControl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoteControl")
            .field("sensor", &self.sensor)
            .field("channel", &self.channel)
            .finish()
    }
}

impl RemoteControl {
    /// Wrap a InfraredSensor into a BeaconSeeker
    pub fn new(sensor: InfraredSensor, channel: u8) -> Ev3Result<RemoteControl> {
        sensor.set_mode_ir_remote()?;

        Ok(RemoteControl {
            sensor,
            channel: u8::max(1, u8::min(4, channel)) - 1,
            helper: Rc::new(RefCell::new(RemoteControlHelper::new())),
        })
    }

    /// Checks if `red_up` button is pressed.
    pub fn is_red_up(&self) -> bool {
        self.helper.borrow().contains("red_up")
    }

    /// Checks if `red_down` button is pressed.
    pub fn is_red_down(&self) -> bool {
        self.helper.borrow().contains("red_down")
    }

    /// Checks if `blue_up` button is pressed.
    pub fn is_blue_up(&self) -> bool {
        self.helper.borrow().contains("blue_up")
    }

    /// Checks if `blue_down` button is pressed.
    pub fn is_blue_down(&self) -> bool {
        self.helper.borrow().contains("blue_down")
    }

    /// Checks if `beacon` button is pressed.
    pub fn is_beacon(&self) -> bool {
        self.helper.borrow().contains("beacon")
    }

    /// Check for currenly pressed buttons. If the new state differs from the
    /// old state, call the appropriate button event handlers.
    pub fn process(&self) -> Ev3Result<()> {
        let buttons = self.sensor.get_value(self.channel)?;

        let mut helper = self.helper.borrow_mut();

        if helper.last_buttons != buttons {
            helper.last_buttons = buttons;

            helper.pressed_buttons.clear();

            match buttons {
                1 => {
                    helper.pressed_buttons.insert("red_up".to_owned());
                }
                2 => {
                    helper.pressed_buttons.insert("red_down".to_owned());
                }
                3 => {
                    helper.pressed_buttons.insert("blue_up".to_owned());
                }
                4 => {
                    helper.pressed_buttons.insert("blue_down".to_owned());
                }
                5 => {
                    helper.pressed_buttons.insert("red_up".to_owned());
                    helper.pressed_buttons.insert("blue_up".to_owned());
                }
                6 => {
                    helper.pressed_buttons.insert("red_up".to_owned());
                    helper.pressed_buttons.insert("blue_down".to_owned());
                }
                7 => {
                    helper.pressed_buttons.insert("red_down".to_owned());
                    helper.pressed_buttons.insert("blue_up".to_owned());
                }
                8 => {
                    helper.pressed_buttons.insert("red_down".to_owned());
                    helper.pressed_buttons.insert("blue_down".to_owned());
                }
                9 => {
                    helper.pressed_buttons.insert("beacon".to_owned());
                }
                10 => {
                    helper.pressed_buttons.insert("red_up".to_owned());
                    helper.pressed_buttons.insert("red_down".to_owned());
                }
                11 => {
                    helper.pressed_buttons.insert("blue_up".to_owned());
                    helper.pressed_buttons.insert("blue_down".to_owned());
                }
                _ => {}
            }
        }
        Ok(())
    }
}

/// Seeks EV3 Remote Controller in beacon mode.
#[derive(Debug, Clone)]
pub struct BeaconSeeker {
    sensor: InfraredSensor,
    channel: u8,
}

impl BeaconSeeker {
    /// Wrap a InfraredSensor into a BeaconSeeker
    pub fn new(sensor: InfraredSensor, channel: u8) -> Ev3Result<BeaconSeeker> {
        sensor.set_mode_ir_seek()?;

        Ok(BeaconSeeker {
            sensor,
            channel: u8::max(1, u8::min(4, channel)) - 1,
        })
    }

    /// Returns heading (-25, 25) to the beacon on the given channel.
    pub fn get_heading(&self) -> Ev3Result<i32> {
        self.sensor.get_value(self.channel * 2)
    }

    /// Returns distance (0, 100) to the beacon on the given channel.
    /// Returns -128 when beacon is not found.
    pub fn get_distance(&self) -> Ev3Result<i32> {
        self.sensor.get_value(self.channel * 2 + 1)
    }

    /// Returns heading and distance to the beacon on the given channel as a
    /// tuple.
    pub fn get_heading_and_distance(&self) -> Ev3Result<(i32, i32)> {
        Ok((
            self.sensor.get_value(self.channel * 2)?,
            self.sensor.get_value(self.channel * 2 + 1)?,
        ))
    }
}