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