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 }
45
46 /// Returns a list of [`Device`]s.
47 /// This list is empty initially.
48 /// Call [`SwitchBot::load_devices()`] to populate the list.
49 pub fn devices(&self) -> &DeviceList {
50 &self.devices
51 }
52
53 /// Load the device list from the SwitchBot API.
54 pub async fn load_devices(&mut self) -> anyhow::Result<()> {
55 let devices = self.service.load_devices().await?;
56 self.devices = devices;
57 Ok(())
58 }
59}