Skip to main content

ev3dev_lang_rust/sensors/
mod.rs

1//! # Container module for sensor types
2
3mod sensor;
4pub use self::sensor::Sensor;
5
6mod color_sensor;
7pub use self::color_sensor::ColorSensor;
8
9mod hi_technic_color_sensor;
10pub use self::hi_technic_color_sensor::HiTechnicColorSensor;
11
12mod ir_seeker_sensor;
13pub use self::ir_seeker_sensor::IrSeekerSensor;
14
15mod compass_sensor;
16pub use self::compass_sensor::CompassSensor;
17
18mod light_sensor;
19pub use self::light_sensor::LightSensor;
20
21mod gyro_sensor;
22pub use self::gyro_sensor::GyroSensor;
23
24mod infrared_sensor;
25pub use self::infrared_sensor::BeaconSeeker;
26pub use self::infrared_sensor::InfraredSensor;
27pub use self::infrared_sensor::RemoteControl;
28
29mod touch_sensor;
30pub use self::touch_sensor::TouchSensor;
31
32mod ultrasonic_sensor;
33pub use self::ultrasonic_sensor::UltrasonicSensor;
34
35use crate::Ev3Result;
36use crate::LegoPort;
37use crate::{port_constants, Port};
38
39/// EV3 ports `in1` to `in4`
40#[derive(Debug, Copy, Clone)]
41pub enum SensorPort {
42    /// EV3 `in1` port
43    In1,
44    /// EV3 `in2` port
45    In2,
46    /// EV3 `in3` port
47    In3,
48    /// EV3 `in4` port
49    In4,
50}
51
52impl SensorPort {
53    /// Try to format a device name path to a  port name.
54    pub fn format_name(name: &str) -> String {
55        match name {
56            "sensor0" => SensorPort::In1.address(),
57            "sensor1" => SensorPort::In2.address(),
58            "sensor2" => SensorPort::In3.address(),
59            "sensor3" => SensorPort::In4.address(),
60            _ => name.to_owned(),
61        }
62    }
63}
64
65impl Port for SensorPort {
66    fn address(&self) -> String {
67        match self {
68            SensorPort::In1 => port_constants::INPUT_1.to_owned(),
69            SensorPort::In2 => port_constants::INPUT_2.to_owned(),
70            SensorPort::In3 => port_constants::INPUT_3.to_owned(),
71            SensorPort::In4 => port_constants::INPUT_4.to_owned(),
72        }
73    }
74
75    fn get_lego_port(&self) -> Ev3Result<LegoPort> {
76        LegoPort::get(*self)
77    }
78}
79
80#[macro_export]
81/// Add a sensor mode constant with getter and setter
82macro_rules! sensor_mode {
83    ($value:expr, $const_name:ident, $docstring:expr, $setter:ident, $getter:ident) => {
84        #[doc = $docstring]
85        pub const $const_name: &'static str = $value;
86
87        #[doc = $docstring]
88        pub fn $setter(&self) -> Ev3Result<()> {
89            self.set_mode(Self::$const_name)
90        }
91
92        #[doc = $docstring]
93        pub fn $getter(&self) -> Ev3Result<bool> {
94            Ok(self.get_mode()? == Self::$const_name)
95        }
96    };
97}