tinkerforge_async/bindings/
moisture_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 soil moisture.
12//!
13//! See also the documentation [here](https://www.tinkerforge.com/en/doc/Software/Bricklets/Moisture_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 MoistureBrickletFunction {
24    GetMoistureValue,
25    SetMoistureCallbackPeriod,
26    GetMoistureCallbackPeriod,
27    SetMoistureCallbackThreshold,
28    GetMoistureCallbackThreshold,
29    SetDebouncePeriod,
30    GetDebouncePeriod,
31    SetMovingAverage,
32    GetMovingAverage,
33    GetIdentity,
34    CallbackMoisture,
35    CallbackMoistureReached,
36}
37impl From<MoistureBrickletFunction> for u8 {
38    fn from(fun: MoistureBrickletFunction) -> Self {
39        match fun {
40            MoistureBrickletFunction::GetMoistureValue => 1,
41            MoistureBrickletFunction::SetMoistureCallbackPeriod => 2,
42            MoistureBrickletFunction::GetMoistureCallbackPeriod => 3,
43            MoistureBrickletFunction::SetMoistureCallbackThreshold => 4,
44            MoistureBrickletFunction::GetMoistureCallbackThreshold => 5,
45            MoistureBrickletFunction::SetDebouncePeriod => 6,
46            MoistureBrickletFunction::GetDebouncePeriod => 7,
47            MoistureBrickletFunction::SetMovingAverage => 10,
48            MoistureBrickletFunction::GetMovingAverage => 11,
49            MoistureBrickletFunction::GetIdentity => 255,
50            MoistureBrickletFunction::CallbackMoisture => 8,
51            MoistureBrickletFunction::CallbackMoistureReached => 9,
52        }
53    }
54}
55pub const MOISTURE_BRICKLET_THRESHOLD_OPTION_OFF: char = 'x';
56pub const MOISTURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE: char = 'o';
57pub const MOISTURE_BRICKLET_THRESHOLD_OPTION_INSIDE: char = 'i';
58pub const MOISTURE_BRICKLET_THRESHOLD_OPTION_SMALLER: char = '<';
59pub const MOISTURE_BRICKLET_THRESHOLD_OPTION_GREATER: char = '>';
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
62pub struct MoistureCallbackThreshold {
63    pub option: char,
64    pub min: u16,
65    pub max: u16,
66}
67impl FromByteSlice for MoistureCallbackThreshold {
68    fn bytes_expected() -> usize {
69        5
70    }
71    fn from_le_byte_slice(bytes: &[u8]) -> MoistureCallbackThreshold {
72        MoistureCallbackThreshold {
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 soil moisture
106#[derive(Clone)]
107pub struct MoistureBricklet {
108    device: Device,
109}
110impl MoistureBricklet {
111    pub const DEVICE_IDENTIFIER: u16 = 232;
112    pub const DEVICE_DISPLAY_NAME: &'static str = "Moisture 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) -> MoistureBricklet {
115        let mut result = MoistureBricklet { device: Device::new([2, 0, 10], uid, connection, Self::DEVICE_DISPLAY_NAME) };
116        result.device.response_expected[u8::from(MoistureBrickletFunction::GetMoistureValue) as usize] = ResponseExpectedFlag::AlwaysTrue;
117        result.device.response_expected[u8::from(MoistureBrickletFunction::SetMoistureCallbackPeriod) as usize] =
118            ResponseExpectedFlag::True;
119        result.device.response_expected[u8::from(MoistureBrickletFunction::GetMoistureCallbackPeriod) as usize] =
120            ResponseExpectedFlag::AlwaysTrue;
121        result.device.response_expected[u8::from(MoistureBrickletFunction::SetMoistureCallbackThreshold) as usize] =
122            ResponseExpectedFlag::True;
123        result.device.response_expected[u8::from(MoistureBrickletFunction::GetMoistureCallbackThreshold) as usize] =
124            ResponseExpectedFlag::AlwaysTrue;
125        result.device.response_expected[u8::from(MoistureBrickletFunction::SetDebouncePeriod) as usize] = ResponseExpectedFlag::True;
126        result.device.response_expected[u8::from(MoistureBrickletFunction::GetDebouncePeriod) as usize] = ResponseExpectedFlag::AlwaysTrue;
127        result.device.response_expected[u8::from(MoistureBrickletFunction::SetMovingAverage) as usize] = ResponseExpectedFlag::False;
128        result.device.response_expected[u8::from(MoistureBrickletFunction::GetMovingAverage) as usize] = ResponseExpectedFlag::AlwaysTrue;
129        result.device.response_expected[u8::from(MoistureBrickletFunction::GetIdentity) as usize] = ResponseExpectedFlag::AlwaysTrue;
130        result
131    }
132
133    /// Returns the response expected flag for the function specified by the function ID parameter.
134    /// It is true if the function is expected to send a response, false otherwise.
135    ///
136    /// For getter functions this is enabled by default and cannot be disabled, because those
137    /// functions will always send a response. For callback configuration functions it is enabled
138    /// by default too, but can be disabled by [`set_response_expected`](crate::moisture_bricklet::MoistureBricklet::set_response_expected).
139    /// For setter functions it is disabled by default and can be enabled.
140    ///
141    /// Enabling the response expected flag for a setter function allows to detect timeouts
142    /// and other error conditions calls of this setter as well. The device will then send a response
143    /// for this purpose. If this flag is disabled for a setter function then no response is sent
144    /// and errors are silently ignored, because they cannot be detected.
145    ///
146    /// See [`set_response_expected`](crate::moisture_bricklet::MoistureBricklet::set_response_expected) for the list of function ID constants available for this function.
147    pub fn get_response_expected(&mut self, fun: MoistureBrickletFunction) -> Result<bool, GetResponseExpectedError> {
148        self.device.get_response_expected(u8::from(fun))
149    }
150
151    /// Changes the response expected flag of the function specified by the function ID parameter.
152    /// This flag can only be changed for setter (default value: false) and callback configuration
153    /// functions (default value: true). For getter functions it is always enabled.
154    ///
155    /// Enabling the response expected flag for a setter function allows to detect timeouts and
156    /// other error conditions calls of this setter as well. The device will then send a response
157    /// for this purpose. If this flag is disabled for a setter function then no response is sent
158    /// and errors are silently ignored, because they cannot be detected.
159    pub fn set_response_expected(
160        &mut self,
161        fun: MoistureBrickletFunction,
162        response_expected: bool,
163    ) -> Result<(), SetResponseExpectedError> {
164        self.device.set_response_expected(u8::from(fun), response_expected)
165    }
166
167    /// Changes the response expected flag for all setter and callback configuration functions of this device at once.
168    pub fn set_response_expected_all(&mut self, response_expected: bool) {
169        self.device.set_response_expected_all(response_expected)
170    }
171
172    /// Returns the version of the API definition (major, minor, revision) implemented by this API bindings.
173    /// This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.
174    pub fn get_api_version(&self) -> [u8; 3] {
175        self.device.api_version
176    }
177
178    /// This receiver is triggered periodically with the period that is set by
179    /// [`set_moisture_callback_period`]. The parameter is the
180    /// moisture value of the sensor.
181    ///
182    /// The [`get_moisture_callback_receiver`] receiver is only triggered if the moisture value has changed
183    /// since the last triggering.
184    ///
185    /// [`set_moisture_callback_period`]: #method.set_moisture_callback_period
186    /// [`get_moisture_callback_receiver`]: #method.get_moisture_callback_receiver
187    pub async fn get_moisture_callback_receiver(&mut self) -> impl Stream<Item = u16> {
188        self.device
189            .get_callback_receiver(u8::from(MoistureBrickletFunction::CallbackMoisture))
190            .await
191            .map(|p| u16::from_le_byte_slice(p.body()))
192    }
193
194    /// This receiver is triggered when the threshold as set by
195    /// [`set_moisture_callback_threshold`] is reached.
196    /// The parameter is the moisture value of the sensor.
197    ///
198    /// If the threshold keeps being reached, the receiver is triggered periodically
199    /// with the period as set by [`set_debounce_period`].
200    pub async fn get_moisture_reached_callback_receiver(&mut self) -> impl Stream<Item = u16> {
201        self.device
202            .get_callback_receiver(u8::from(MoistureBrickletFunction::CallbackMoistureReached))
203            .await
204            .map(|p| u16::from_le_byte_slice(p.body()))
205    }
206
207    /// Returns the current moisture value.
208    /// A small value corresponds to little moisture, a big
209    /// value corresponds to much moisture.
210    ///
211    /// If you want to get the moisture value periodically, it is recommended
212    /// to use the [`get_moisture_callback_receiver`] receiver and set the period with
213    /// [`set_moisture_callback_period`].
214    pub async fn get_moisture_value(&mut self) -> Result<u16, TinkerforgeError> {
215        let payload = [0; 0];
216
217        #[allow(unused_variables)]
218        let result = self.device.get(u8::from(MoistureBrickletFunction::GetMoistureValue), &payload).await?;
219        Ok(u16::from_le_byte_slice(result.body()))
220    }
221
222    /// Sets the period with which the [`get_moisture_callback_receiver`] receiver is triggered
223    /// periodically. A value of 0 turns the receiver off.
224    ///
225    /// The [`get_moisture_callback_receiver`] receiver is only triggered if the moisture value has changed
226    /// since the last triggering.
227    pub async fn set_moisture_callback_period(&mut self, period: u32) -> Result<(), TinkerforgeError> {
228        let mut payload = [0; 4];
229        period.write_to_slice(&mut payload[0..4]);
230
231        #[allow(unused_variables)]
232        let result = self.device.set(u8::from(MoistureBrickletFunction::SetMoistureCallbackPeriod), &payload).await?;
233        Ok(())
234    }
235
236    /// Returns the period as set by [`set_moisture_callback_period`].
237    pub async fn get_moisture_callback_period(&mut self) -> Result<u32, TinkerforgeError> {
238        let payload = [0; 0];
239
240        #[allow(unused_variables)]
241        let result = self.device.get(u8::from(MoistureBrickletFunction::GetMoistureCallbackPeriod), &payload).await?;
242        Ok(u32::from_le_byte_slice(result.body()))
243    }
244
245    /// Sets the thresholds for the [`get_moisture_reached_callback_receiver`] receiver.
246    ///
247    /// The following options are possible:
248    ///
249    ///  Option| Description
250    ///  --- | ---
251    ///  'x'|    Receiver is turned off
252    ///  'o'|    Receiver is triggered when the moisture value is *outside* the min and max values
253    ///  'i'|    Receiver is triggered when the moisture value is *inside* the min and max values
254    ///  '<'|    Receiver is triggered when the moisture value is smaller than the min value (max is ignored)
255    ///  '>'|    Receiver is triggered when the moisture value is greater than the min value (max is ignored)
256    ///
257    /// Associated constants:
258    /// * MOISTURE_BRICKLET_THRESHOLD_OPTION_OFF
259    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE
260    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_INSIDE
261    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_SMALLER
262    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_GREATER
263    pub async fn set_moisture_callback_threshold(&mut self, option: char, min: u16, max: u16) -> Result<(), TinkerforgeError> {
264        let mut payload = [0; 5];
265        option.write_to_slice(&mut payload[0..1]);
266        min.write_to_slice(&mut payload[1..3]);
267        max.write_to_slice(&mut payload[3..5]);
268
269        #[allow(unused_variables)]
270        let result = self.device.set(u8::from(MoistureBrickletFunction::SetMoistureCallbackThreshold), &payload).await?;
271        Ok(())
272    }
273
274    /// Returns the threshold as set by [`set_moisture_callback_threshold`].
275    ///
276    /// Associated constants:
277    /// * MOISTURE_BRICKLET_THRESHOLD_OPTION_OFF
278    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE
279    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_INSIDE
280    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_SMALLER
281    ///	* MOISTURE_BRICKLET_THRESHOLD_OPTION_GREATER
282    pub async fn get_moisture_callback_threshold(&mut self) -> Result<MoistureCallbackThreshold, TinkerforgeError> {
283        let payload = [0; 0];
284
285        #[allow(unused_variables)]
286        let result = self.device.get(u8::from(MoistureBrickletFunction::GetMoistureCallbackThreshold), &payload).await?;
287        Ok(MoistureCallbackThreshold::from_le_byte_slice(result.body()))
288    }
289
290    /// Sets the period with which the threshold receiver
291    ///
292    /// * [`get_moisture_reached_callback_receiver`]
293    ///
294    /// is triggered, if the threshold
295    ///
296    /// * [`set_moisture_callback_threshold`]
297    ///
298    /// keeps being reached.
299    pub async fn set_debounce_period(&mut self, debounce: u32) -> Result<(), TinkerforgeError> {
300        let mut payload = [0; 4];
301        debounce.write_to_slice(&mut payload[0..4]);
302
303        #[allow(unused_variables)]
304        let result = self.device.set(u8::from(MoistureBrickletFunction::SetDebouncePeriod), &payload).await?;
305        Ok(())
306    }
307
308    /// Returns the debounce period as set by [`set_debounce_period`].
309    pub async fn get_debounce_period(&mut self) -> Result<u32, TinkerforgeError> {
310        let payload = [0; 0];
311
312        #[allow(unused_variables)]
313        let result = self.device.get(u8::from(MoistureBrickletFunction::GetDebouncePeriod), &payload).await?;
314        Ok(u32::from_le_byte_slice(result.body()))
315    }
316
317    /// Sets the length of a [moving averaging](https://en.wikipedia.org/wiki/Moving_average)__
318    /// for the moisture value.
319    ///
320    /// Setting the length to 0 will turn the averaging completely off. With less
321    /// averaging, there is more noise on the data.
322    pub async fn set_moving_average(&mut self, average: u8) -> Result<(), TinkerforgeError> {
323        let mut payload = [0; 1];
324        average.write_to_slice(&mut payload[0..1]);
325
326        #[allow(unused_variables)]
327        let result = self.device.set(u8::from(MoistureBrickletFunction::SetMovingAverage), &payload).await?;
328        Ok(())
329    }
330
331    /// Returns the length moving average as set by [`set_moving_average`].
332    pub async fn get_moving_average(&mut self) -> Result<u8, TinkerforgeError> {
333        let payload = [0; 0];
334
335        #[allow(unused_variables)]
336        let result = self.device.get(u8::from(MoistureBrickletFunction::GetMovingAverage), &payload).await?;
337        Ok(u8::from_le_byte_slice(result.body()))
338    }
339
340    /// Returns the UID, the UID where the Bricklet is connected to,
341    /// the position, the hardware and firmware version as well as the
342    /// device identifier.
343    ///
344    /// The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
345    /// A Bricklet connected to an [Isolator Bricklet](isolator_bricklet) is always at
346    /// position 'z'.
347    ///
348    /// The device identifier numbers can be found [here](device_identifier).
349    /// |device_identifier_constant|
350    pub async fn get_identity(&mut self) -> Result<Identity, TinkerforgeError> {
351        let payload = [0; 0];
352
353        #[allow(unused_variables)]
354        let result = self.device.get(u8::from(MoistureBrickletFunction::GetIdentity), &payload).await?;
355        Ok(Identity::from_le_byte_slice(result.body()))
356    }
357}