switchbot_api/
switch_bot.rs

1use std::rc::Rc;
2
3use super::*;
4
5/// Represents a [SwitchBot API] server.
6///
7/// [SwitchBot API]: https://github.com/OpenWonderLabs/SwitchBotAPI
8#[derive(Debug, Default)]
9pub struct SwitchBot {
10    service: Rc<SwitchBotService>,
11    devices: DeviceList,
12}
13
14impl SwitchBot {
15    /// Construct a new instance with the default parameters.
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Construct a new instance with the authentication information.
21    /// This is equivalent to:
22    /// ```
23    /// # use switchbot_api::SwitchBot;
24    /// # fn test(token: &str, secret: &str) {
25    /// let mut switch_bot = SwitchBot::new();
26    /// switch_bot.set_authentication(token, secret);
27    /// # }
28    /// ```
29    pub fn new_with_authentication(token: &str, secret: &str) -> Self {
30        Self {
31            service: SwitchBotService::new(token, secret),
32            ..Default::default()
33        }
34    }
35
36    /// Set the authentication information.
37    ///
38    /// Please refer to the [SwitchBot documentation about
39    /// how to obtain the token and secret key][token-secret].
40    ///
41    /// [token-secret]: https://github.com/OpenWonderLabs/SwitchBotAPI?tab=readme-ov-file#open-token-and-secret-key
42    pub fn set_authentication(&mut self, token: &str, secret: &str) {
43        self.service = SwitchBotService::new(token, secret);
44        self.devices.clear();
45    }
46
47    /// Returns a list of [`Device`]s.
48    /// This list is empty initially.
49    /// Call [`SwitchBot::load_devices()`] to populate the list.
50    pub fn devices(&self) -> &DeviceList {
51        &self.devices
52    }
53
54    /// Load the device list from the SwitchBot API.
55    pub async fn load_devices(&mut self) -> anyhow::Result<()> {
56        let devices = self.service.load_devices().await?;
57        self.devices = devices;
58        Ok(())
59    }
60}