tinkerforge_async/bindings/
temperature_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 ambient temperature with 0.5°C accuracy.
12//!
13//! See also the documentation [here](https://www.tinkerforge.com/en/doc/Software/Bricklets/Temperature_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 TemperatureBrickletFunction {
24    GetTemperature,
25    SetTemperatureCallbackPeriod,
26    GetTemperatureCallbackPeriod,
27    SetTemperatureCallbackThreshold,
28    GetTemperatureCallbackThreshold,
29    SetDebouncePeriod,
30    GetDebouncePeriod,
31    SetI2cMode,
32    GetI2cMode,
33    GetIdentity,
34    CallbackTemperature,
35    CallbackTemperatureReached,
36}
37impl From<TemperatureBrickletFunction> for u8 {
38    fn from(fun: TemperatureBrickletFunction) -> Self {
39        match fun {
40            TemperatureBrickletFunction::GetTemperature => 1,
41            TemperatureBrickletFunction::SetTemperatureCallbackPeriod => 2,
42            TemperatureBrickletFunction::GetTemperatureCallbackPeriod => 3,
43            TemperatureBrickletFunction::SetTemperatureCallbackThreshold => 4,
44            TemperatureBrickletFunction::GetTemperatureCallbackThreshold => 5,
45            TemperatureBrickletFunction::SetDebouncePeriod => 6,
46            TemperatureBrickletFunction::GetDebouncePeriod => 7,
47            TemperatureBrickletFunction::SetI2cMode => 10,
48            TemperatureBrickletFunction::GetI2cMode => 11,
49            TemperatureBrickletFunction::GetIdentity => 255,
50            TemperatureBrickletFunction::CallbackTemperature => 8,
51            TemperatureBrickletFunction::CallbackTemperatureReached => 9,
52        }
53    }
54}
55pub const TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OFF: char = 'x';
56pub const TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE: char = 'o';
57pub const TEMPERATURE_BRICKLET_THRESHOLD_OPTION_INSIDE: char = 'i';
58pub const TEMPERATURE_BRICKLET_THRESHOLD_OPTION_SMALLER: char = '<';
59pub const TEMPERATURE_BRICKLET_THRESHOLD_OPTION_GREATER: char = '>';
60pub const TEMPERATURE_BRICKLET_I2C_MODE_FAST: u8 = 0;
61pub const TEMPERATURE_BRICKLET_I2C_MODE_SLOW: u8 = 1;
62
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
64pub struct TemperatureCallbackThreshold {
65    pub option: char,
66    pub min: i16,
67    pub max: i16,
68}
69impl FromByteSlice for TemperatureCallbackThreshold {
70    fn bytes_expected() -> usize {
71        5
72    }
73    fn from_le_byte_slice(bytes: &[u8]) -> TemperatureCallbackThreshold {
74        TemperatureCallbackThreshold {
75            option: <char>::from_le_byte_slice(&bytes[0..1]),
76            min: <i16>::from_le_byte_slice(&bytes[1..3]),
77            max: <i16>::from_le_byte_slice(&bytes[3..5]),
78        }
79    }
80}
81
82#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
83pub struct Identity {
84    pub uid: String,
85    pub connected_uid: String,
86    pub position: char,
87    pub hardware_version: [u8; 3],
88    pub firmware_version: [u8; 3],
89    pub device_identifier: u16,
90}
91impl FromByteSlice for Identity {
92    fn bytes_expected() -> usize {
93        25
94    }
95    fn from_le_byte_slice(bytes: &[u8]) -> Identity {
96        Identity {
97            uid: <String>::from_le_byte_slice(&bytes[0..8]),
98            connected_uid: <String>::from_le_byte_slice(&bytes[8..16]),
99            position: <char>::from_le_byte_slice(&bytes[16..17]),
100            hardware_version: <[u8; 3]>::from_le_byte_slice(&bytes[17..20]),
101            firmware_version: <[u8; 3]>::from_le_byte_slice(&bytes[20..23]),
102            device_identifier: <u16>::from_le_byte_slice(&bytes[23..25]),
103        }
104    }
105}
106
107/// Measures ambient temperature with 0.5°C accuracy
108#[derive(Clone)]
109pub struct TemperatureBricklet {
110    device: Device,
111}
112impl TemperatureBricklet {
113    pub const DEVICE_IDENTIFIER: u16 = 216;
114    pub const DEVICE_DISPLAY_NAME: &'static str = "Temperature Bricklet";
115    /// Creates an object with the unique device ID `uid`. This object can then be used after the IP Connection `ip_connection` is connected.
116    pub fn new(uid: Uid, connection: AsyncIpConnection) -> TemperatureBricklet {
117        let mut result = TemperatureBricklet { device: Device::new([2, 0, 10], uid, connection, Self::DEVICE_DISPLAY_NAME) };
118        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetTemperature) as usize] = ResponseExpectedFlag::AlwaysTrue;
119        result.device.response_expected[u8::from(TemperatureBrickletFunction::SetTemperatureCallbackPeriod) as usize] =
120            ResponseExpectedFlag::True;
121        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetTemperatureCallbackPeriod) as usize] =
122            ResponseExpectedFlag::AlwaysTrue;
123        result.device.response_expected[u8::from(TemperatureBrickletFunction::SetTemperatureCallbackThreshold) as usize] =
124            ResponseExpectedFlag::True;
125        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetTemperatureCallbackThreshold) as usize] =
126            ResponseExpectedFlag::AlwaysTrue;
127        result.device.response_expected[u8::from(TemperatureBrickletFunction::SetDebouncePeriod) as usize] = ResponseExpectedFlag::True;
128        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetDebouncePeriod) as usize] =
129            ResponseExpectedFlag::AlwaysTrue;
130        result.device.response_expected[u8::from(TemperatureBrickletFunction::SetI2cMode) as usize] = ResponseExpectedFlag::False;
131        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetI2cMode) as usize] = ResponseExpectedFlag::AlwaysTrue;
132        result.device.response_expected[u8::from(TemperatureBrickletFunction::GetIdentity) as usize] = ResponseExpectedFlag::AlwaysTrue;
133        result
134    }
135
136    /// Returns the response expected flag for the function specified by the function ID parameter.
137    /// It is true if the function is expected to send a response, false otherwise.
138    ///
139    /// For getter functions this is enabled by default and cannot be disabled, because those
140    /// functions will always send a response. For callback configuration functions it is enabled
141    /// by default too, but can be disabled by [`set_response_expected`](crate::temperature_bricklet::TemperatureBricklet::set_response_expected).
142    /// For setter functions it is disabled by default and can be enabled.
143    ///
144    /// Enabling the response expected flag for a setter function allows to detect timeouts
145    /// and other error conditions calls of this setter as well. The device will then send a response
146    /// for this purpose. If this flag is disabled for a setter function then no response is sent
147    /// and errors are silently ignored, because they cannot be detected.
148    ///
149    /// See [`set_response_expected`](crate::temperature_bricklet::TemperatureBricklet::set_response_expected) for the list of function ID constants available for this function.
150    pub fn get_response_expected(&mut self, fun: TemperatureBrickletFunction) -> Result<bool, GetResponseExpectedError> {
151        self.device.get_response_expected(u8::from(fun))
152    }
153
154    /// Changes the response expected flag of the function specified by the function ID parameter.
155    /// This flag can only be changed for setter (default value: false) and callback configuration
156    /// functions (default value: true). For getter functions it is always enabled.
157    ///
158    /// Enabling the response expected flag for a setter function allows to detect timeouts and
159    /// other error conditions calls of this setter as well. The device will then send a response
160    /// for this purpose. If this flag is disabled for a setter function then no response is sent
161    /// and errors are silently ignored, because they cannot be detected.
162    pub fn set_response_expected(
163        &mut self,
164        fun: TemperatureBrickletFunction,
165        response_expected: bool,
166    ) -> Result<(), SetResponseExpectedError> {
167        self.device.set_response_expected(u8::from(fun), response_expected)
168    }
169
170    /// Changes the response expected flag for all setter and callback configuration functions of this device at once.
171    pub fn set_response_expected_all(&mut self, response_expected: bool) {
172        self.device.set_response_expected_all(response_expected)
173    }
174
175    /// Returns the version of the API definition (major, minor, revision) implemented by this API bindings.
176    /// This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.
177    pub fn get_api_version(&self) -> [u8; 3] {
178        self.device.api_version
179    }
180
181    /// This receiver is triggered periodically with the period that is set by
182    /// [`set_temperature_callback_period`]. The parameter is the
183    /// temperature of the sensor.
184    ///
185    /// The [`get_temperature_callback_receiver`] receiver is only triggered if the temperature has changed
186    /// since the last triggering.
187    ///
188    /// [`set_temperature_callback_period`]: #method.set_temperature_callback_period
189    /// [`get_temperature_callback_receiver`]: #method.get_temperature_callback_receiver
190    pub async fn get_temperature_callback_receiver(&mut self) -> impl Stream<Item = i16> {
191        self.device
192            .get_callback_receiver(u8::from(TemperatureBrickletFunction::CallbackTemperature))
193            .await
194            .map(|p| i16::from_le_byte_slice(p.body()))
195    }
196
197    /// This receiver is triggered when the threshold as set by
198    /// [`set_temperature_callback_threshold`] is reached.
199    /// The parameter is the temperature of the sensor.
200    ///
201    /// If the threshold keeps being reached, the receiver is triggered periodically
202    /// with the period as set by [`set_debounce_period`].
203    pub async fn get_temperature_reached_callback_receiver(&mut self) -> impl Stream<Item = i16> {
204        self.device
205            .get_callback_receiver(u8::from(TemperatureBrickletFunction::CallbackTemperatureReached))
206            .await
207            .map(|p| i16::from_le_byte_slice(p.body()))
208    }
209
210    /// Returns the temperature of the sensor.
211    ///
212    /// If you want to get the temperature periodically, it is recommended
213    /// to use the [`get_temperature_callback_receiver`] receiver and set the period with
214    /// [`set_temperature_callback_period`].
215    pub async fn get_temperature(&mut self) -> Result<i16, TinkerforgeError> {
216        let payload = [0; 0];
217
218        #[allow(unused_variables)]
219        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetTemperature), &payload).await?;
220        Ok(i16::from_le_byte_slice(result.body()))
221    }
222
223    /// Sets the period with which the [`get_temperature_callback_receiver`] receiver is triggered
224    /// periodically. A value of 0 turns the receiver off.
225    ///
226    /// The [`get_temperature_callback_receiver`] receiver is only triggered if the temperature has changed
227    /// since the last triggering.
228    pub async fn set_temperature_callback_period(&mut self, period: u32) -> Result<(), TinkerforgeError> {
229        let mut payload = [0; 4];
230        period.write_to_slice(&mut payload[0..4]);
231
232        #[allow(unused_variables)]
233        let result = self.device.set(u8::from(TemperatureBrickletFunction::SetTemperatureCallbackPeriod), &payload).await?;
234        Ok(())
235    }
236
237    /// Returns the period as set by [`set_temperature_callback_period`].
238    pub async fn get_temperature_callback_period(&mut self) -> Result<u32, TinkerforgeError> {
239        let payload = [0; 0];
240
241        #[allow(unused_variables)]
242        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetTemperatureCallbackPeriod), &payload).await?;
243        Ok(u32::from_le_byte_slice(result.body()))
244    }
245
246    /// Sets the thresholds for the [`get_temperature_reached_callback_receiver`] receiver.
247    ///
248    /// The following options are possible:
249    ///
250    ///  Option| Description
251    ///  --- | ---
252    ///  'x'|    Receiver is turned off
253    ///  'o'|    Receiver is triggered when the temperature is *outside* the min and max values
254    ///  'i'|    Receiver is triggered when the temperature is *inside* the min and max values
255    ///  '<'|    Receiver is triggered when the temperature is smaller than the min value (max is ignored)
256    ///  '>'|    Receiver is triggered when the temperature is greater than the min value (max is ignored)
257    ///
258    /// Associated constants:
259    /// * TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OFF
260    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE
261    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_INSIDE
262    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_SMALLER
263    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_GREATER
264    pub async fn set_temperature_callback_threshold(&mut self, option: char, min: i16, max: i16) -> Result<(), TinkerforgeError> {
265        let mut payload = [0; 5];
266        option.write_to_slice(&mut payload[0..1]);
267        min.write_to_slice(&mut payload[1..3]);
268        max.write_to_slice(&mut payload[3..5]);
269
270        #[allow(unused_variables)]
271        let result = self.device.set(u8::from(TemperatureBrickletFunction::SetTemperatureCallbackThreshold), &payload).await?;
272        Ok(())
273    }
274
275    /// Returns the threshold as set by [`set_temperature_callback_threshold`].
276    ///
277    /// Associated constants:
278    /// * TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OFF
279    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_OUTSIDE
280    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_INSIDE
281    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_SMALLER
282    ///	* TEMPERATURE_BRICKLET_THRESHOLD_OPTION_GREATER
283    pub async fn get_temperature_callback_threshold(&mut self) -> Result<TemperatureCallbackThreshold, TinkerforgeError> {
284        let payload = [0; 0];
285
286        #[allow(unused_variables)]
287        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetTemperatureCallbackThreshold), &payload).await?;
288        Ok(TemperatureCallbackThreshold::from_le_byte_slice(result.body()))
289    }
290
291    /// Sets the period with which the threshold receiver
292    ///
293    /// * [`get_temperature_reached_callback_receiver`]
294    ///
295    /// is triggered, if the threshold
296    ///
297    /// * [`set_temperature_callback_threshold`]
298    ///
299    /// keeps being reached.
300    pub async fn set_debounce_period(&mut self, debounce: u32) -> Result<(), TinkerforgeError> {
301        let mut payload = [0; 4];
302        debounce.write_to_slice(&mut payload[0..4]);
303
304        #[allow(unused_variables)]
305        let result = self.device.set(u8::from(TemperatureBrickletFunction::SetDebouncePeriod), &payload).await?;
306        Ok(())
307    }
308
309    /// Returns the debounce period as set by [`set_debounce_period`].
310    pub async fn get_debounce_period(&mut self) -> Result<u32, TinkerforgeError> {
311        let payload = [0; 0];
312
313        #[allow(unused_variables)]
314        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetDebouncePeriod), &payload).await?;
315        Ok(u32::from_le_byte_slice(result.body()))
316    }
317
318    /// Sets the I2C mode. Possible modes are:
319    ///
320    /// * 0: Fast (400kHz)
321    /// * 1: Slow (100kHz)
322    ///
323    /// If you have problems with obvious outliers in the
324    /// Temperature Bricklet measurements, they may be caused by EMI issues.
325    /// In this case it may be helpful to lower the I2C speed.
326    ///
327    /// It is however not recommended to lower the I2C speed in applications where
328    /// a high throughput needs to be achieved.
329    ///
330    ///
331    /// .. versionadded:: 2.0.1$nbsp;(Plugin)
332    ///
333    /// Associated constants:
334    /// * TEMPERATURE_BRICKLET_I2C_MODE_FAST
335    ///	* TEMPERATURE_BRICKLET_I2C_MODE_SLOW
336    pub async fn set_i2c_mode(&mut self, mode: u8) -> Result<(), TinkerforgeError> {
337        let mut payload = [0; 1];
338        mode.write_to_slice(&mut payload[0..1]);
339
340        #[allow(unused_variables)]
341        let result = self.device.set(u8::from(TemperatureBrickletFunction::SetI2cMode), &payload).await?;
342        Ok(())
343    }
344
345    /// Returns the I2C mode as set by [`set_i2c_mode`].
346    ///
347    ///
348    /// .. versionadded:: 2.0.1$nbsp;(Plugin)
349    ///
350    /// Associated constants:
351    /// * TEMPERATURE_BRICKLET_I2C_MODE_FAST
352    ///	* TEMPERATURE_BRICKLET_I2C_MODE_SLOW
353    pub async fn get_i2c_mode(&mut self) -> Result<u8, TinkerforgeError> {
354        let payload = [0; 0];
355
356        #[allow(unused_variables)]
357        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetI2cMode), &payload).await?;
358        Ok(u8::from_le_byte_slice(result.body()))
359    }
360
361    /// Returns the UID, the UID where the Bricklet is connected to,
362    /// the position, the hardware and firmware version as well as the
363    /// device identifier.
364    ///
365    /// The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
366    /// A Bricklet connected to an [Isolator Bricklet](isolator_bricklet) is always at
367    /// position 'z'.
368    ///
369    /// The device identifier numbers can be found [here](device_identifier).
370    /// |device_identifier_constant|
371    pub async fn get_identity(&mut self) -> Result<Identity, TinkerforgeError> {
372        let payload = [0; 0];
373
374        #[allow(unused_variables)]
375        let result = self.device.get(u8::from(TemperatureBrickletFunction::GetIdentity), &payload).await?;
376        Ok(Identity::from_le_byte_slice(result.body()))
377    }
378}