tinkerforge_async/bindings/
distance_us_bricklet.rs

1/* ***********************************************************
2 * This file was automatically generated on 2024-02-16.      *
3 *                                                           *
4 * Rust Bindings Version 2.0.20                              *
5 *                                                           *
6 * If you have a bugfix for this file and want to commit it, *
7 * please fix the bug in the generator. You can find a link  *
8 * to the generators git repository on tinkerforge.com       *
9 *************************************************************/
10
11//! Measures distance between 2cm and 400cm with ultrasound.
12//!
13//! See also the documentation [here](https://www.tinkerforge.com/en/doc/Software/Bricklets/DistanceUS_Bricklet_Rust.html).
14#[allow(unused_imports)]
15use crate::{
16    base58::Uid, byte_converter::*, device::*, error::TinkerforgeError, ip_connection::async_io::AsyncIpConnection,
17    low_level_traits::LowLevelRead,
18};
19#[allow(unused_imports)]
20use futures_core::Stream;
21#[allow(unused_imports)]
22use tokio_stream::StreamExt;
23pub enum DistanceUsBrickletFunction {
24    GetDistanceValue,
25    SetDistanceCallbackPeriod,
26    GetDistanceCallbackPeriod,
27    SetDistanceCallbackThreshold,
28    GetDistanceCallbackThreshold,
29    SetDebouncePeriod,
30    GetDebouncePeriod,
31    SetMovingAverage,
32    GetMovingAverage,
33    GetIdentity,
34    CallbackDistance,
35    CallbackDistanceReached,
36}
37impl From<DistanceUsBrickletFunction> for u8 {
38    fn from(fun: DistanceUsBrickletFunction) -> Self {
39        match fun {
40            DistanceUsBrickletFunction::GetDistanceValue => 1,
41            DistanceUsBrickletFunction::SetDistanceCallbackPeriod => 2,
42            DistanceUsBrickletFunction::GetDistanceCallbackPeriod => 3,
43            DistanceUsBrickletFunction::SetDistanceCallbackThreshold => 4,
44            DistanceUsBrickletFunction::GetDistanceCallbackThreshold => 5,
45            DistanceUsBrickletFunction::SetDebouncePeriod => 6,
46            DistanceUsBrickletFunction::GetDebouncePeriod => 7,
47            DistanceUsBrickletFunction::SetMovingAverage => 10,
48            DistanceUsBrickletFunction::GetMovingAverage => 11,
49            DistanceUsBrickletFunction::GetIdentity => 255,
50            DistanceUsBrickletFunction::CallbackDistance => 8,
51            DistanceUsBrickletFunction::CallbackDistanceReached => 9,
52        }
53    }
54}
55pub const DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OFF: char = 'x';
56pub const DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OUTSIDE: char = 'o';
57pub const DISTANCE_US_BRICKLET_THRESHOLD_OPTION_INSIDE: char = 'i';
58pub const DISTANCE_US_BRICKLET_THRESHOLD_OPTION_SMALLER: char = '<';
59pub const DISTANCE_US_BRICKLET_THRESHOLD_OPTION_GREATER: char = '>';
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
62pub struct DistanceCallbackThreshold {
63    pub option: char,
64    pub min: u16,
65    pub max: u16,
66}
67impl FromByteSlice for DistanceCallbackThreshold {
68    fn bytes_expected() -> usize {
69        5
70    }
71    fn from_le_byte_slice(bytes: &[u8]) -> DistanceCallbackThreshold {
72        DistanceCallbackThreshold {
73            option: <char>::from_le_byte_slice(&bytes[0..1]),
74            min: <u16>::from_le_byte_slice(&bytes[1..3]),
75            max: <u16>::from_le_byte_slice(&bytes[3..5]),
76        }
77    }
78}
79
80#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
81pub struct Identity {
82    pub uid: String,
83    pub connected_uid: String,
84    pub position: char,
85    pub hardware_version: [u8; 3],
86    pub firmware_version: [u8; 3],
87    pub device_identifier: u16,
88}
89impl FromByteSlice for Identity {
90    fn bytes_expected() -> usize {
91        25
92    }
93    fn from_le_byte_slice(bytes: &[u8]) -> Identity {
94        Identity {
95            uid: <String>::from_le_byte_slice(&bytes[0..8]),
96            connected_uid: <String>::from_le_byte_slice(&bytes[8..16]),
97            position: <char>::from_le_byte_slice(&bytes[16..17]),
98            hardware_version: <[u8; 3]>::from_le_byte_slice(&bytes[17..20]),
99            firmware_version: <[u8; 3]>::from_le_byte_slice(&bytes[20..23]),
100            device_identifier: <u16>::from_le_byte_slice(&bytes[23..25]),
101        }
102    }
103}
104
105/// Measures distance between 2cm and 400cm with ultrasound
106#[derive(Clone)]
107pub struct DistanceUsBricklet {
108    device: Device,
109}
110impl DistanceUsBricklet {
111    pub const DEVICE_IDENTIFIER: u16 = 229;
112    pub const DEVICE_DISPLAY_NAME: &'static str = "Distance US Bricklet";
113    /// Creates an object with the unique device ID `uid`. This object can then be used after the IP Connection `ip_connection` is connected.
114    pub fn new(uid: Uid, connection: AsyncIpConnection) -> DistanceUsBricklet {
115        let mut result = DistanceUsBricklet { device: Device::new([2, 0, 10], uid, connection, Self::DEVICE_DISPLAY_NAME) };
116        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetDistanceValue) as usize] = ResponseExpectedFlag::AlwaysTrue;
117        result.device.response_expected[u8::from(DistanceUsBrickletFunction::SetDistanceCallbackPeriod) as usize] =
118            ResponseExpectedFlag::True;
119        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetDistanceCallbackPeriod) as usize] =
120            ResponseExpectedFlag::AlwaysTrue;
121        result.device.response_expected[u8::from(DistanceUsBrickletFunction::SetDistanceCallbackThreshold) as usize] =
122            ResponseExpectedFlag::True;
123        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetDistanceCallbackThreshold) as usize] =
124            ResponseExpectedFlag::AlwaysTrue;
125        result.device.response_expected[u8::from(DistanceUsBrickletFunction::SetDebouncePeriod) as usize] = ResponseExpectedFlag::True;
126        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetDebouncePeriod) as usize] =
127            ResponseExpectedFlag::AlwaysTrue;
128        result.device.response_expected[u8::from(DistanceUsBrickletFunction::SetMovingAverage) as usize] = ResponseExpectedFlag::False;
129        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetMovingAverage) as usize] = ResponseExpectedFlag::AlwaysTrue;
130        result.device.response_expected[u8::from(DistanceUsBrickletFunction::GetIdentity) as usize] = ResponseExpectedFlag::AlwaysTrue;
131        result
132    }
133
134    /// Returns the response expected flag for the function specified by the function ID parameter.
135    /// It is true if the function is expected to send a response, false otherwise.
136    ///
137    /// For getter functions this is enabled by default and cannot be disabled, because those
138    /// functions will always send a response. For callback configuration functions it is enabled
139    /// by default too, but can be disabled by [`set_response_expected`](crate::distance_us_bricklet::DistanceUsBricklet::set_response_expected).
140    /// For setter functions it is disabled by default and can be enabled.
141    ///
142    /// Enabling the response expected flag for a setter function allows to detect timeouts
143    /// and other error conditions calls of this setter as well. The device will then send a response
144    /// for this purpose. If this flag is disabled for a setter function then no response is sent
145    /// and errors are silently ignored, because they cannot be detected.
146    ///
147    /// See [`set_response_expected`](crate::distance_us_bricklet::DistanceUsBricklet::set_response_expected) for the list of function ID constants available for this function.
148    pub fn get_response_expected(&mut self, fun: DistanceUsBrickletFunction) -> Result<bool, GetResponseExpectedError> {
149        self.device.get_response_expected(u8::from(fun))
150    }
151
152    /// Changes the response expected flag of the function specified by the function ID parameter.
153    /// This flag can only be changed for setter (default value: false) and callback configuration
154    /// functions (default value: true). For getter functions it is always enabled.
155    ///
156    /// Enabling the response expected flag for a setter function allows to detect timeouts and
157    /// other error conditions calls of this setter as well. The device will then send a response
158    /// for this purpose. If this flag is disabled for a setter function then no response is sent
159    /// and errors are silently ignored, because they cannot be detected.
160    pub fn set_response_expected(
161        &mut self,
162        fun: DistanceUsBrickletFunction,
163        response_expected: bool,
164    ) -> Result<(), SetResponseExpectedError> {
165        self.device.set_response_expected(u8::from(fun), response_expected)
166    }
167
168    /// Changes the response expected flag for all setter and callback configuration functions of this device at once.
169    pub fn set_response_expected_all(&mut self, response_expected: bool) {
170        self.device.set_response_expected_all(response_expected)
171    }
172
173    /// Returns the version of the API definition (major, minor, revision) implemented by this API bindings.
174    /// This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.
175    pub fn get_api_version(&self) -> [u8; 3] {
176        self.device.api_version
177    }
178
179    /// This receiver is triggered periodically with the period that is set by
180    /// [`set_distance_callback_period`]. The parameter is the distance value
181    /// of the sensor.
182    ///
183    /// The [`get_distance_callback_receiver`] receiver is only triggered if the distance value has changed
184    /// since the last triggering.
185    ///
186    /// [`set_distance_callback_period`]: #method.set_distance_callback_period
187    /// [`get_distance_callback_receiver`]: #method.get_distance_callback_receiver
188    pub async fn get_distance_callback_receiver(&mut self) -> impl Stream<Item = u16> {
189        self.device
190            .get_callback_receiver(u8::from(DistanceUsBrickletFunction::CallbackDistance))
191            .await
192            .map(|p| u16::from_le_byte_slice(p.body()))
193    }
194
195    /// This receiver is triggered when the threshold as set by
196    /// [`set_distance_callback_threshold`] is reached.
197    /// The parameter is the distance value of the sensor.
198    ///
199    /// If the threshold keeps being reached, the receiver is triggered periodically
200    /// with the period as set by [`set_debounce_period`].
201    pub async fn get_distance_reached_callback_receiver(&mut self) -> impl Stream<Item = u16> {
202        self.device
203            .get_callback_receiver(u8::from(DistanceUsBrickletFunction::CallbackDistanceReached))
204            .await
205            .map(|p| u16::from_le_byte_slice(p.body()))
206    }
207
208    /// Returns the current distance value measured by the sensor.
209    /// A small value corresponds to a small distance, a big
210    /// value corresponds to a big distance. The relation between the measured distance
211    /// value and the actual distance is affected by the 5V supply voltage (deviations
212    /// in the supply voltage result in deviations in the distance values) and is
213    /// non-linear (resolution is bigger at close range).
214    ///
215    /// If you want to get the distance value periodically, it is recommended to
216    /// use the [`get_distance_callback_receiver`] receiver and set the period with
217    /// [`set_distance_callback_period`].
218    pub async fn get_distance_value(&mut self) -> Result<u16, TinkerforgeError> {
219        let payload = [0; 0];
220
221        #[allow(unused_variables)]
222        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetDistanceValue), &payload).await?;
223        Ok(u16::from_le_byte_slice(result.body()))
224    }
225
226    /// Sets the period with which the [`get_distance_callback_receiver`] receiver is triggered
227    /// periodically. A value of 0 turns the receiver off.
228    ///
229    /// Der [`get_distance_callback_receiver`] receiver is only triggered if the distance value has changed
230    /// since the last triggering.
231    pub async fn set_distance_callback_period(&mut self, period: u32) -> Result<(), TinkerforgeError> {
232        let mut payload = [0; 4];
233        period.write_to_slice(&mut payload[0..4]);
234
235        #[allow(unused_variables)]
236        let result = self.device.set(u8::from(DistanceUsBrickletFunction::SetDistanceCallbackPeriod), &payload).await?;
237        Ok(())
238    }
239
240    /// Returns the period as set by [`set_distance_callback_period`].
241    pub async fn get_distance_callback_period(&mut self) -> Result<u32, TinkerforgeError> {
242        let payload = [0; 0];
243
244        #[allow(unused_variables)]
245        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetDistanceCallbackPeriod), &payload).await?;
246        Ok(u32::from_le_byte_slice(result.body()))
247    }
248
249    /// Sets the thresholds for the [`get_distance_reached_callback_receiver`] receiver.
250    ///
251    /// The following options are possible:
252    ///
253    ///  Option| Description
254    ///  --- | ---
255    ///  'x'|    Receiver is turned off
256    ///  'o'|    Receiver is triggered when the distance value is *outside* the min and max values
257    ///  'i'|    Receiver is triggered when the distance value is *inside* the min and max values
258    ///  '<'|    Receiver is triggered when the distance value is smaller than the min value (max is ignored)
259    ///  '>'|    Receiver is triggered when the distance value is greater than the min value (max is ignored)
260    ///
261    /// Associated constants:
262    /// * DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OFF
263    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OUTSIDE
264    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_INSIDE
265    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_SMALLER
266    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_GREATER
267    pub async fn set_distance_callback_threshold(&mut self, option: char, min: u16, max: u16) -> Result<(), TinkerforgeError> {
268        let mut payload = [0; 5];
269        option.write_to_slice(&mut payload[0..1]);
270        min.write_to_slice(&mut payload[1..3]);
271        max.write_to_slice(&mut payload[3..5]);
272
273        #[allow(unused_variables)]
274        let result = self.device.set(u8::from(DistanceUsBrickletFunction::SetDistanceCallbackThreshold), &payload).await?;
275        Ok(())
276    }
277
278    /// Returns the threshold as set by [`set_distance_callback_threshold`].
279    ///
280    /// Associated constants:
281    /// * DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OFF
282    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_OUTSIDE
283    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_INSIDE
284    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_SMALLER
285    ///	* DISTANCE_US_BRICKLET_THRESHOLD_OPTION_GREATER
286    pub async fn get_distance_callback_threshold(&mut self) -> Result<DistanceCallbackThreshold, TinkerforgeError> {
287        let payload = [0; 0];
288
289        #[allow(unused_variables)]
290        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetDistanceCallbackThreshold), &payload).await?;
291        Ok(DistanceCallbackThreshold::from_le_byte_slice(result.body()))
292    }
293
294    /// Sets the period with which the threshold receivers
295    ///
296    /// * [`get_distance_reached_callback_receiver`],
297    ///
298    /// are triggered, if the thresholds
299    ///
300    /// * [`set_distance_callback_threshold`],
301    ///
302    /// keep being reached.
303    pub async fn set_debounce_period(&mut self, debounce: u32) -> Result<(), TinkerforgeError> {
304        let mut payload = [0; 4];
305        debounce.write_to_slice(&mut payload[0..4]);
306
307        #[allow(unused_variables)]
308        let result = self.device.set(u8::from(DistanceUsBrickletFunction::SetDebouncePeriod), &payload).await?;
309        Ok(())
310    }
311
312    /// Returns the debounce period as set by [`set_debounce_period`].
313    pub async fn get_debounce_period(&mut self) -> Result<u32, TinkerforgeError> {
314        let payload = [0; 0];
315
316        #[allow(unused_variables)]
317        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetDebouncePeriod), &payload).await?;
318        Ok(u32::from_le_byte_slice(result.body()))
319    }
320
321    /// Sets the length of a [moving averaging](https://en.wikipedia.org/wiki/Moving_average)__
322    /// for the distance value.
323    ///
324    /// Setting the length to 0 will turn the averaging completely off. With less
325    /// averaging, there is more noise on the data.
326    pub async fn set_moving_average(&mut self, average: u8) -> Result<(), TinkerforgeError> {
327        let mut payload = [0; 1];
328        average.write_to_slice(&mut payload[0..1]);
329
330        #[allow(unused_variables)]
331        let result = self.device.set(u8::from(DistanceUsBrickletFunction::SetMovingAverage), &payload).await?;
332        Ok(())
333    }
334
335    /// Returns the length moving average as set by [`set_moving_average`].
336    pub async fn get_moving_average(&mut self) -> Result<u8, TinkerforgeError> {
337        let payload = [0; 0];
338
339        #[allow(unused_variables)]
340        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetMovingAverage), &payload).await?;
341        Ok(u8::from_le_byte_slice(result.body()))
342    }
343
344    /// Returns the UID, the UID where the Bricklet is connected to,
345    /// the position, the hardware and firmware version as well as the
346    /// device identifier.
347    ///
348    /// The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
349    /// A Bricklet connected to an [Isolator Bricklet](isolator_bricklet) is always at
350    /// position 'z'.
351    ///
352    /// The device identifier numbers can be found [here](device_identifier).
353    /// |device_identifier_constant|
354    pub async fn get_identity(&mut self) -> Result<Identity, TinkerforgeError> {
355        let payload = [0; 0];
356
357        #[allow(unused_variables)]
358        let result = self.device.get(u8::from(DistanceUsBrickletFunction::GetIdentity), &payload).await?;
359        Ok(Identity::from_le_byte_slice(result.body()))
360    }
361}