switchbot_api/
switch_bot.rs

1use std::sync::Arc;
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: Arc<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    ///
22    /// Please refer to the [SwitchBot documentation about
23    /// how to obtain the token and secret key][token-secret].
24    ///
25    /// [token-secret]: https://github.com/OpenWonderLabs/SwitchBotAPI#getting-started
26    ///
27    /// This function is equivalent to:
28    /// ```
29    /// # use switchbot_api::SwitchBot;
30    /// # fn test(token: &str, secret: &str) {
31    /// let mut switch_bot = SwitchBot::new();
32    /// switch_bot.set_authentication(token, secret);
33    /// # }
34    /// ```
35    pub fn new_with_authentication(token: &str, secret: &str) -> Self {
36        Self {
37            service: SwitchBotService::new(token, secret),
38            ..Default::default()
39        }
40    }
41
42    /// Construct an instance for testing.
43    /// The instance has the specified number of devices for testing.
44    pub fn new_for_test(num_devices: usize) -> Self {
45        let mut devices = DeviceList::new();
46        for i in 0..num_devices {
47            devices.push(Device::new_for_test(i + 1));
48        }
49        Self {
50            devices,
51            ..Default::default()
52        }
53    }
54
55    /// Set the authentication information.
56    ///
57    /// Please refer to the [SwitchBot documentation about
58    /// how to obtain the token and secret key][token-secret].
59    ///
60    /// [token-secret]: https://github.com/OpenWonderLabs/SwitchBotAPI#getting-started
61    pub fn set_authentication(&mut self, token: &str, secret: &str) {
62        self.service = SwitchBotService::new(token, secret);
63        self.devices.clear();
64    }
65
66    /// Returns a list of [`Device`]s.
67    /// This list is empty initially.
68    /// Call [`load_devices()`][SwitchBot::load_devices()] to populate the list.
69    pub fn devices(&self) -> &DeviceList {
70        &self.devices
71    }
72
73    /// Load the device list from the SwitchBot API.
74    pub async fn load_devices(&mut self) -> anyhow::Result<()> {
75        let devices = self.service.load_devices().await?;
76        self.devices = devices;
77        Ok(())
78    }
79}