tinkerforge_async/bindings/
piezo_speaker_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//! Creates beep with configurable frequency.
12//!
13//! See also the documentation [here](https://www.tinkerforge.com/en/doc/Software/Bricklets/PiezoSpeaker_Bricklet_Rust.html).
14#[allow(unused_imports)]
15use crate::{
16    base58::Uid, byte_converter::*, converting_receiver::BrickletError, device::*, error::TinkerforgeError,
17    ip_connection::async_io::AsyncIpConnection, low_level_traits::LowLevelRead,
18};
19#[allow(unused_imports)]
20use futures_core::Stream;
21#[allow(unused_imports)]
22use tokio_stream::StreamExt;
23pub enum PiezoSpeakerBrickletFunction {
24    Beep,
25    MorseCode,
26    Calibrate,
27    GetIdentity,
28    CallbackBeepFinished,
29    CallbackMorseCodeFinished,
30}
31impl From<PiezoSpeakerBrickletFunction> for u8 {
32    fn from(fun: PiezoSpeakerBrickletFunction) -> Self {
33        match fun {
34            PiezoSpeakerBrickletFunction::Beep => 1,
35            PiezoSpeakerBrickletFunction::MorseCode => 2,
36            PiezoSpeakerBrickletFunction::Calibrate => 3,
37            PiezoSpeakerBrickletFunction::GetIdentity => 255,
38            PiezoSpeakerBrickletFunction::CallbackBeepFinished => 4,
39            PiezoSpeakerBrickletFunction::CallbackMorseCodeFinished => 5,
40        }
41    }
42}
43pub const PIEZO_SPEAKER_BRICKLET_BEEP_DURATION_OFF: u32 = 0;
44pub const PIEZO_SPEAKER_BRICKLET_BEEP_DURATION_INFINITE: u32 = 4_294_967_295;
45
46#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
47pub struct Identity {
48    pub uid: String,
49    pub connected_uid: String,
50    pub position: char,
51    pub hardware_version: [u8; 3],
52    pub firmware_version: [u8; 3],
53    pub device_identifier: u16,
54}
55impl FromByteSlice for Identity {
56    fn bytes_expected() -> usize {
57        25
58    }
59    fn from_le_byte_slice(bytes: &[u8]) -> Identity {
60        Identity {
61            uid: <String>::from_le_byte_slice(&bytes[0..8]),
62            connected_uid: <String>::from_le_byte_slice(&bytes[8..16]),
63            position: <char>::from_le_byte_slice(&bytes[16..17]),
64            hardware_version: <[u8; 3]>::from_le_byte_slice(&bytes[17..20]),
65            firmware_version: <[u8; 3]>::from_le_byte_slice(&bytes[20..23]),
66            device_identifier: <u16>::from_le_byte_slice(&bytes[23..25]),
67        }
68    }
69}
70
71/// Creates beep with configurable frequency
72#[derive(Clone)]
73pub struct PiezoSpeakerBricklet {
74    device: Device,
75}
76impl PiezoSpeakerBricklet {
77    pub const DEVICE_IDENTIFIER: u16 = 242;
78    pub const DEVICE_DISPLAY_NAME: &'static str = "Piezo Speaker Bricklet";
79    /// Creates an object with the unique device ID `uid`. This object can then be used after the IP Connection `ip_connection` is connected.
80    pub fn new(uid: Uid, connection: AsyncIpConnection) -> PiezoSpeakerBricklet {
81        let mut result = PiezoSpeakerBricklet { device: Device::new([2, 0, 10], uid, connection, Self::DEVICE_DISPLAY_NAME) };
82        result.device.response_expected[u8::from(PiezoSpeakerBrickletFunction::Beep) as usize] = ResponseExpectedFlag::False;
83        result.device.response_expected[u8::from(PiezoSpeakerBrickletFunction::MorseCode) as usize] = ResponseExpectedFlag::False;
84        result.device.response_expected[u8::from(PiezoSpeakerBrickletFunction::Calibrate) as usize] = ResponseExpectedFlag::AlwaysTrue;
85        result.device.response_expected[u8::from(PiezoSpeakerBrickletFunction::GetIdentity) as usize] = ResponseExpectedFlag::AlwaysTrue;
86        result
87    }
88
89    /// Returns the response expected flag for the function specified by the function ID parameter.
90    /// It is true if the function is expected to send a response, false otherwise.
91    ///
92    /// For getter functions this is enabled by default and cannot be disabled, because those
93    /// functions will always send a response. For callback configuration functions it is enabled
94    /// by default too, but can be disabled by [`set_response_expected`](crate::piezo_speaker_bricklet::PiezoSpeakerBricklet::set_response_expected).
95    /// For setter functions it is disabled by default and can be enabled.
96    ///
97    /// Enabling the response expected flag for a setter function allows to detect timeouts
98    /// and other error conditions calls of this setter as well. The device will then send a response
99    /// for this purpose. If this flag is disabled for a setter function then no response is sent
100    /// and errors are silently ignored, because they cannot be detected.
101    ///
102    /// See [`set_response_expected`](crate::piezo_speaker_bricklet::PiezoSpeakerBricklet::set_response_expected) for the list of function ID constants available for this function.
103    pub fn get_response_expected(&mut self, fun: PiezoSpeakerBrickletFunction) -> Result<bool, GetResponseExpectedError> {
104        self.device.get_response_expected(u8::from(fun))
105    }
106
107    /// Changes the response expected flag of the function specified by the function ID parameter.
108    /// This flag can only be changed for setter (default value: false) and callback configuration
109    /// functions (default value: true). For getter functions it is always enabled.
110    ///
111    /// Enabling the response expected flag for a setter function allows to detect timeouts and
112    /// other error conditions calls of this setter as well. The device will then send a response
113    /// for this purpose. If this flag is disabled for a setter function then no response is sent
114    /// and errors are silently ignored, because they cannot be detected.
115    pub fn set_response_expected(
116        &mut self,
117        fun: PiezoSpeakerBrickletFunction,
118        response_expected: bool,
119    ) -> Result<(), SetResponseExpectedError> {
120        self.device.set_response_expected(u8::from(fun), response_expected)
121    }
122
123    /// Changes the response expected flag for all setter and callback configuration functions of this device at once.
124    pub fn set_response_expected_all(&mut self, response_expected: bool) {
125        self.device.set_response_expected_all(response_expected)
126    }
127
128    /// Returns the version of the API definition (major, minor, revision) implemented by this API bindings.
129    /// This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.
130    pub fn get_api_version(&self) -> [u8; 3] {
131        self.device.api_version
132    }
133
134    /// This receiver is triggered if a beep set by [`beep`] is finished
135    ///
136    /// [`beep`]: #method.beep
137    pub async fn get_beep_finished_callback_receiver(&mut self) -> impl Stream<Item = ()> {
138        self.device.get_callback_receiver(u8::from(PiezoSpeakerBrickletFunction::CallbackBeepFinished)).await.map(|_p| ())
139    }
140
141    /// This receiver is triggered if the playback of the morse code set by
142    /// [`morse_code`] is finished.
143    pub async fn get_morse_code_finished_callback_receiver(&mut self) -> impl Stream<Item = ()> {
144        self.device.get_callback_receiver(u8::from(PiezoSpeakerBrickletFunction::CallbackMorseCodeFinished)).await.map(|_p| ())
145    }
146
147    /// Beeps with the given frequency for the given duration.
148    ///
149    /// .. versionchanged:: 2.0.2$nbsp;(Plugin)
150    ///    A duration of 0 stops the current beep if any, the frequency parameter is
151    ///    ignored. A duration of 4294967295 results in an infinite beep.
152    ///
153    /// The Piezo Speaker Bricklet can only approximate the frequency, it will play
154    /// the best possible match by applying the calibration (see [`calibrate`]).
155    ///
156    /// Associated constants:
157    /// * PIEZO_SPEAKER_BRICKLET_BEEP_DURATION_OFF
158    ///	* PIEZO_SPEAKER_BRICKLET_BEEP_DURATION_INFINITE
159    pub async fn beep(&mut self, duration: u32, frequency: u16) -> Result<(), TinkerforgeError> {
160        let mut payload = [0; 6];
161        duration.write_to_slice(&mut payload[0..4]);
162        frequency.write_to_slice(&mut payload[4..6]);
163
164        #[allow(unused_variables)]
165        let result = self.device.set(u8::from(PiezoSpeakerBrickletFunction::Beep), &payload).await?;
166        Ok(())
167    }
168
169    /// Sets morse code that will be played by the piezo buzzer. The morse code
170    /// is given as a string consisting of . (dot), - (minus) and   (space)
171    /// for *dits*, *dahs* and *pauses*. Every other character is ignored.
172    ///
173    /// For example: If you set the string ...---..., the piezo buzzer will beep
174    /// nine times with the durations short short short long long long short
175    /// short short.
176    pub async fn morse_code(&mut self, morse: String, frequency: u16) -> Result<(), TinkerforgeError> {
177        let mut payload = [0; 62];
178        morse.try_write_to_slice(60, &mut payload)?;
179        frequency.write_to_slice(&mut payload[60..62]);
180
181        #[allow(unused_variables)]
182        let result = self.device.set(u8::from(PiezoSpeakerBrickletFunction::MorseCode), &payload).await?;
183        Ok(())
184    }
185
186    /// The Piezo Speaker Bricklet can play 512 different tones. This function
187    /// plays each tone and measures the exact frequency back. The result is a
188    /// mapping between setting value and frequency. This mapping is stored
189    /// in the EEPROM and loaded on startup.
190    ///
191    /// The Bricklet should come calibrated, you only need to call this
192    /// function (once) every time you reflash the Bricklet plugin.
193    ///
194    /// Returns *true* after the calibration finishes.
195    pub async fn calibrate(&mut self) -> Result<bool, TinkerforgeError> {
196        let payload = [0; 0];
197
198        #[allow(unused_variables)]
199        let result = self.device.get(u8::from(PiezoSpeakerBrickletFunction::Calibrate), &payload).await?;
200        Ok(bool::from_le_byte_slice(result.body()))
201    }
202
203    /// Returns the UID, the UID where the Bricklet is connected to,
204    /// the position, the hardware and firmware version as well as the
205    /// device identifier.
206    ///
207    /// The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
208    /// A Bricklet connected to an [Isolator Bricklet](isolator_bricklet) is always at
209    /// position 'z'.
210    ///
211    /// The device identifier numbers can be found [here](device_identifier).
212    /// |device_identifier_constant|
213    pub async fn get_identity(&mut self) -> Result<Identity, TinkerforgeError> {
214        let payload = [0; 0];
215
216        #[allow(unused_variables)]
217        let result = self.device.get(u8::from(PiezoSpeakerBrickletFunction::GetIdentity), &payload).await?;
218        Ok(Identity::from_le_byte_slice(result.body()))
219    }
220}