tinkerforge_async/bindings/
sound_intensity_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 sound intensity.
12//!
13//! See also the documentation [here](https://www.tinkerforge.com/en/doc/Software/Bricklets/SoundIntensity_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 SoundIntensityBrickletFunction {
24    GetIntensity,
25    SetIntensityCallbackPeriod,
26    GetIntensityCallbackPeriod,
27    SetIntensityCallbackThreshold,
28    GetIntensityCallbackThreshold,
29    SetDebouncePeriod,
30    GetDebouncePeriod,
31    GetIdentity,
32    CallbackIntensity,
33    CallbackIntensityReached,
34}
35impl From<SoundIntensityBrickletFunction> for u8 {
36    fn from(fun: SoundIntensityBrickletFunction) -> Self {
37        match fun {
38            SoundIntensityBrickletFunction::GetIntensity => 1,
39            SoundIntensityBrickletFunction::SetIntensityCallbackPeriod => 2,
40            SoundIntensityBrickletFunction::GetIntensityCallbackPeriod => 3,
41            SoundIntensityBrickletFunction::SetIntensityCallbackThreshold => 4,
42            SoundIntensityBrickletFunction::GetIntensityCallbackThreshold => 5,
43            SoundIntensityBrickletFunction::SetDebouncePeriod => 6,
44            SoundIntensityBrickletFunction::GetDebouncePeriod => 7,
45            SoundIntensityBrickletFunction::GetIdentity => 255,
46            SoundIntensityBrickletFunction::CallbackIntensity => 8,
47            SoundIntensityBrickletFunction::CallbackIntensityReached => 9,
48        }
49    }
50}
51pub const SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OFF: char = 'x';
52pub const SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OUTSIDE: char = 'o';
53pub const SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_INSIDE: char = 'i';
54pub const SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_SMALLER: char = '<';
55pub const SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_GREATER: char = '>';
56
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
58pub struct IntensityCallbackThreshold {
59    pub option: char,
60    pub min: u16,
61    pub max: u16,
62}
63impl FromByteSlice for IntensityCallbackThreshold {
64    fn bytes_expected() -> usize {
65        5
66    }
67    fn from_le_byte_slice(bytes: &[u8]) -> IntensityCallbackThreshold {
68        IntensityCallbackThreshold {
69            option: <char>::from_le_byte_slice(&bytes[0..1]),
70            min: <u16>::from_le_byte_slice(&bytes[1..3]),
71            max: <u16>::from_le_byte_slice(&bytes[3..5]),
72        }
73    }
74}
75
76#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
77pub struct Identity {
78    pub uid: String,
79    pub connected_uid: String,
80    pub position: char,
81    pub hardware_version: [u8; 3],
82    pub firmware_version: [u8; 3],
83    pub device_identifier: u16,
84}
85impl FromByteSlice for Identity {
86    fn bytes_expected() -> usize {
87        25
88    }
89    fn from_le_byte_slice(bytes: &[u8]) -> Identity {
90        Identity {
91            uid: <String>::from_le_byte_slice(&bytes[0..8]),
92            connected_uid: <String>::from_le_byte_slice(&bytes[8..16]),
93            position: <char>::from_le_byte_slice(&bytes[16..17]),
94            hardware_version: <[u8; 3]>::from_le_byte_slice(&bytes[17..20]),
95            firmware_version: <[u8; 3]>::from_le_byte_slice(&bytes[20..23]),
96            device_identifier: <u16>::from_le_byte_slice(&bytes[23..25]),
97        }
98    }
99}
100
101/// Measures sound intensity
102#[derive(Clone)]
103pub struct SoundIntensityBricklet {
104    device: Device,
105}
106impl SoundIntensityBricklet {
107    pub const DEVICE_IDENTIFIER: u16 = 238;
108    pub const DEVICE_DISPLAY_NAME: &'static str = "Sound Intensity Bricklet";
109    /// Creates an object with the unique device ID `uid`. This object can then be used after the IP Connection `ip_connection` is connected.
110    pub fn new(uid: Uid, connection: AsyncIpConnection) -> SoundIntensityBricklet {
111        let mut result = SoundIntensityBricklet { device: Device::new([2, 0, 10], uid, connection, Self::DEVICE_DISPLAY_NAME) };
112        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::GetIntensity) as usize] = ResponseExpectedFlag::AlwaysTrue;
113        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::SetIntensityCallbackPeriod) as usize] =
114            ResponseExpectedFlag::True;
115        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::GetIntensityCallbackPeriod) as usize] =
116            ResponseExpectedFlag::AlwaysTrue;
117        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::SetIntensityCallbackThreshold) as usize] =
118            ResponseExpectedFlag::True;
119        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::GetIntensityCallbackThreshold) as usize] =
120            ResponseExpectedFlag::AlwaysTrue;
121        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::SetDebouncePeriod) as usize] = ResponseExpectedFlag::True;
122        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::GetDebouncePeriod) as usize] =
123            ResponseExpectedFlag::AlwaysTrue;
124        result.device.response_expected[u8::from(SoundIntensityBrickletFunction::GetIdentity) as usize] = ResponseExpectedFlag::AlwaysTrue;
125        result
126    }
127
128    /// Returns the response expected flag for the function specified by the function ID parameter.
129    /// It is true if the function is expected to send a response, false otherwise.
130    ///
131    /// For getter functions this is enabled by default and cannot be disabled, because those
132    /// functions will always send a response. For callback configuration functions it is enabled
133    /// by default too, but can be disabled by [`set_response_expected`](crate::sound_intensity_bricklet::SoundIntensityBricklet::set_response_expected).
134    /// For setter functions it is disabled by default and can be enabled.
135    ///
136    /// Enabling the response expected flag for a setter function allows to detect timeouts
137    /// and other error conditions calls of this setter as well. The device will then send a response
138    /// for this purpose. If this flag is disabled for a setter function then no response is sent
139    /// and errors are silently ignored, because they cannot be detected.
140    ///
141    /// See [`set_response_expected`](crate::sound_intensity_bricklet::SoundIntensityBricklet::set_response_expected) for the list of function ID constants available for this function.
142    pub fn get_response_expected(&mut self, fun: SoundIntensityBrickletFunction) -> Result<bool, GetResponseExpectedError> {
143        self.device.get_response_expected(u8::from(fun))
144    }
145
146    /// Changes the response expected flag of the function specified by the function ID parameter.
147    /// This flag can only be changed for setter (default value: false) and callback configuration
148    /// functions (default value: true). For getter functions it is always enabled.
149    ///
150    /// Enabling the response expected flag for a setter function allows to detect timeouts and
151    /// other error conditions calls of this setter as well. The device will then send a response
152    /// for this purpose. If this flag is disabled for a setter function then no response is sent
153    /// and errors are silently ignored, because they cannot be detected.
154    pub fn set_response_expected(
155        &mut self,
156        fun: SoundIntensityBrickletFunction,
157        response_expected: bool,
158    ) -> Result<(), SetResponseExpectedError> {
159        self.device.set_response_expected(u8::from(fun), response_expected)
160    }
161
162    /// Changes the response expected flag for all setter and callback configuration functions of this device at once.
163    pub fn set_response_expected_all(&mut self, response_expected: bool) {
164        self.device.set_response_expected_all(response_expected)
165    }
166
167    /// Returns the version of the API definition (major, minor, revision) implemented by this API bindings.
168    /// This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.
169    pub fn get_api_version(&self) -> [u8; 3] {
170        self.device.api_version
171    }
172
173    /// This receiver is triggered periodically with the period that is set by
174    /// [`set_intensity_callback_period`]. The parameter is the intensity
175    /// of the sensor.
176    ///
177    /// The [`get_intensity_callback_receiver`] receiver is only triggered if the intensity has changed
178    /// since the last triggering.
179    ///
180    /// [`set_intensity_callback_period`]: #method.set_intensity_callback_period
181    /// [`get_intensity_callback_receiver`]: #method.get_intensity_callback_receiver
182    pub async fn get_intensity_callback_receiver(&mut self) -> impl Stream<Item = u16> {
183        self.device
184            .get_callback_receiver(u8::from(SoundIntensityBrickletFunction::CallbackIntensity))
185            .await
186            .map(|p| u16::from_le_byte_slice(p.body()))
187    }
188
189    /// This receiver is triggered when the threshold as set by
190    /// [`set_intensity_callback_threshold`] is reached.
191    /// The parameter is the intensity of the encoder.
192    ///
193    /// If the threshold keeps being reached, the receiver is triggered periodically
194    /// with the period as set by [`set_debounce_period`].
195    pub async fn get_intensity_reached_callback_receiver(&mut self) -> impl Stream<Item = u16> {
196        self.device
197            .get_callback_receiver(u8::from(SoundIntensityBrickletFunction::CallbackIntensityReached))
198            .await
199            .map(|p| u16::from_le_byte_slice(p.body()))
200    }
201
202    /// Returns the current sound intensity.
203    ///
204    /// The value corresponds to the
205    /// [upper envelop](https://en.wikipedia.org/wiki/Envelope_(waves))__
206    /// of the signal of the microphone capsule.
207    ///
208    /// If you want to get the intensity periodically, it is recommended to use the
209    /// [`get_intensity_callback_receiver`] receiver and set the period with
210    /// [`set_intensity_callback_period`].
211    pub async fn get_intensity(&mut self) -> Result<u16, TinkerforgeError> {
212        let payload = [0; 0];
213
214        #[allow(unused_variables)]
215        let result = self.device.get(u8::from(SoundIntensityBrickletFunction::GetIntensity), &payload).await?;
216        Ok(u16::from_le_byte_slice(result.body()))
217    }
218
219    /// Sets the period with which the [`get_intensity_callback_receiver`] receiver is triggered
220    /// periodically. A value of 0 turns the receiver off.
221    ///
222    /// The [`get_intensity_callback_receiver`] receiver is only triggered if the intensity has changed
223    /// since the last triggering.
224    pub async fn set_intensity_callback_period(&mut self, period: u32) -> Result<(), TinkerforgeError> {
225        let mut payload = [0; 4];
226        period.write_to_slice(&mut payload[0..4]);
227
228        #[allow(unused_variables)]
229        let result = self.device.set(u8::from(SoundIntensityBrickletFunction::SetIntensityCallbackPeriod), &payload).await?;
230        Ok(())
231    }
232
233    /// Returns the period as set by [`set_intensity_callback_period`].
234    pub async fn get_intensity_callback_period(&mut self) -> Result<u32, TinkerforgeError> {
235        let payload = [0; 0];
236
237        #[allow(unused_variables)]
238        let result = self.device.get(u8::from(SoundIntensityBrickletFunction::GetIntensityCallbackPeriod), &payload).await?;
239        Ok(u32::from_le_byte_slice(result.body()))
240    }
241
242    /// Sets the thresholds for the [`get_intensity_reached_callback_receiver`] receiver.
243    ///
244    /// The following options are possible:
245    ///
246    ///  Option| Description
247    ///  --- | ---
248    ///  'x'|    Receiver is turned off
249    ///  'o'|    Receiver is triggered when the intensity is *outside* the min and max values
250    ///  'i'|    Receiver is triggered when the intensity is *inside* the min and max values
251    ///  '<'|    Receiver is triggered when the intensity is smaller than the min value (max is ignored)
252    ///  '>'|    Receiver is triggered when the intensity is greater than the min value (max is ignored)
253    ///
254    /// Associated constants:
255    /// * SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OFF
256    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OUTSIDE
257    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_INSIDE
258    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_SMALLER
259    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_GREATER
260    pub async fn set_intensity_callback_threshold(&mut self, option: char, min: u16, max: u16) -> Result<(), TinkerforgeError> {
261        let mut payload = [0; 5];
262        option.write_to_slice(&mut payload[0..1]);
263        min.write_to_slice(&mut payload[1..3]);
264        max.write_to_slice(&mut payload[3..5]);
265
266        #[allow(unused_variables)]
267        let result = self.device.set(u8::from(SoundIntensityBrickletFunction::SetIntensityCallbackThreshold), &payload).await?;
268        Ok(())
269    }
270
271    /// Returns the threshold as set by [`set_intensity_callback_threshold`].
272    ///
273    /// Associated constants:
274    /// * SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OFF
275    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_OUTSIDE
276    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_INSIDE
277    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_SMALLER
278    ///	* SOUND_INTENSITY_BRICKLET_THRESHOLD_OPTION_GREATER
279    pub async fn get_intensity_callback_threshold(&mut self) -> Result<IntensityCallbackThreshold, TinkerforgeError> {
280        let payload = [0; 0];
281
282        #[allow(unused_variables)]
283        let result = self.device.get(u8::from(SoundIntensityBrickletFunction::GetIntensityCallbackThreshold), &payload).await?;
284        Ok(IntensityCallbackThreshold::from_le_byte_slice(result.body()))
285    }
286
287    /// Sets the period with which the threshold receiver
288    ///
289    /// * [`get_intensity_reached_callback_receiver`]
290    ///
291    /// is triggered, if the thresholds
292    ///
293    /// * [`set_intensity_callback_threshold`]
294    ///
295    /// keeps being reached.
296    pub async fn set_debounce_period(&mut self, debounce: u32) -> Result<(), TinkerforgeError> {
297        let mut payload = [0; 4];
298        debounce.write_to_slice(&mut payload[0..4]);
299
300        #[allow(unused_variables)]
301        let result = self.device.set(u8::from(SoundIntensityBrickletFunction::SetDebouncePeriod), &payload).await?;
302        Ok(())
303    }
304
305    /// Returns the debounce period as set by [`set_debounce_period`].
306    pub async fn get_debounce_period(&mut self) -> Result<u32, TinkerforgeError> {
307        let payload = [0; 0];
308
309        #[allow(unused_variables)]
310        let result = self.device.get(u8::from(SoundIntensityBrickletFunction::GetDebouncePeriod), &payload).await?;
311        Ok(u32::from_le_byte_slice(result.body()))
312    }
313
314    /// Returns the UID, the UID where the Bricklet is connected to,
315    /// the position, the hardware and firmware version as well as the
316    /// device identifier.
317    ///
318    /// The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
319    /// A Bricklet connected to an [Isolator Bricklet](isolator_bricklet) is always at
320    /// position 'z'.
321    ///
322    /// The device identifier numbers can be found [here](device_identifier).
323    /// |device_identifier_constant|
324    pub async fn get_identity(&mut self) -> Result<Identity, TinkerforgeError> {
325        let payload = [0; 0];
326
327        #[allow(unused_variables)]
328        let result = self.device.get(u8::from(SoundIntensityBrickletFunction::GetIdentity), &payload).await?;
329        Ok(Identity::from_le_byte_slice(result.body()))
330    }
331}