switchbot_api/
switch_bot_service.rs

1use base64::{Engine as _, engine::general_purpose::STANDARD};
2use hmac::{Hmac, Mac};
3use sha2::Sha256;
4use std::{rc::Rc, time::SystemTime};
5use uuid::Uuid;
6
7use super::*;
8
9#[derive(Debug, Default)]
10pub struct SwitchBotService {
11    client: reqwest::Client,
12    token: String,
13    secret: String,
14}
15
16impl SwitchBotService {
17    const HOST: &str = "https://api.switch-bot.com";
18
19    pub fn new(token: &str, secret: &str) -> Rc<Self> {
20        Rc::new(SwitchBotService {
21            client: reqwest::Client::new(),
22            token: token.to_string(),
23            secret: secret.to_string(),
24        })
25    }
26
27    pub async fn load_devices(self: &Rc<SwitchBotService>) -> anyhow::Result<DeviceList> {
28        let url = format!("{}/v1.1/devices", Self::HOST);
29        // let url = format!("https://www.google.com");
30        let json: serde_json::Value = self
31            .add_headers(self.client.get(url))?
32            // .header("Content-Type", "application/json")
33            .send()
34            .await?
35            .json()
36            .await?;
37        log::trace!("devices.json: {json:#?}");
38        let response: SwitchBotResponse<DeviceListResponse> = serde_json::from_value(json)?;
39        // log::trace!("devices: {response:#?}");
40        let mut devices = response.body.deviceList;
41        devices.extend(response.body.infraredRemoteList);
42        for device in devices.iter_mut() {
43            device.set_service(Rc::clone(self));
44        }
45        Ok(devices)
46    }
47
48    pub(crate) async fn command(
49        &self,
50        device_id: &str,
51        command: &CommandRequest,
52    ) -> anyhow::Result<()> {
53        let url = format!("{}/v1.1/devices/{device_id}/commands", Self::HOST);
54        let body = serde_json::to_value(command)?;
55        log::debug!("command.request: {body}");
56        let json: serde_json::Value = self
57            .add_headers(self.client.post(url))?
58            .header("Content-Type", "application/json")
59            .json(&body)
60            .send()
61            .await?
62            .json()
63            .await?;
64        log::trace!("command.response: {json}");
65        Ok(())
66    }
67
68    fn add_headers(
69        &self,
70        builder: reqwest::RequestBuilder,
71    ) -> anyhow::Result<reqwest::RequestBuilder> {
72        let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
73        let t = duration_since_epoch.as_millis().to_string();
74        let nonce = Uuid::new_v4().to_string();
75
76        let mut mac = Hmac::<Sha256>::new_from_slice(self.secret.as_bytes())?;
77        mac.update(self.token.as_bytes());
78        mac.update(t.as_bytes());
79        mac.update(nonce.as_bytes());
80        let result = mac.finalize();
81        let sign = STANDARD.encode(result.into_bytes());
82
83        Ok(builder
84            .header("Authorization", self.token.clone())
85            .header("t", t)
86            .header("sign", sign)
87            .header("nonce", nonce))
88    }
89}
90
91#[derive(Debug, serde::Deserialize)]
92#[allow(non_snake_case)]
93pub struct SwitchBotResponse<T> {
94    #[allow(dead_code)]
95    pub statusCode: u16,
96    #[allow(dead_code)]
97    pub message: String,
98    pub body: T,
99}
100
101#[derive(Debug, serde::Deserialize)]
102#[allow(non_snake_case)]
103pub struct DeviceListResponse {
104    pub deviceList: DeviceList,
105    pub infraredRemoteList: DeviceList,
106}
107
108#[derive(Debug, serde::Serialize)]
109pub struct CommandRequest {
110    pub command: String,
111    pub parameter: String,
112    #[serde(rename = "commandType")]
113    pub command_type: String,
114}
115
116impl Default for CommandRequest {
117    fn default() -> Self {
118        Self {
119            command: String::default(),
120            parameter: "default".into(),
121            command_type: "command".into(),
122        }
123    }
124}