switchbot_api2/
device.rs

1use anyhow::Result;
2use serde::Deserialize;
3
4use crate::{Hub2Status, IOThermoHygrometerStatus, SwitchBot};
5
6/// A single device.
7#[derive(Clone, Debug, Deserialize, PartialEq)]
8pub struct Device {
9    /// Unique device identifier.
10    #[serde(rename = "deviceId")]
11    pub id: String,
12
13    /// Human readable device name.
14    #[serde(rename = "deviceName")]
15    pub name: String,
16
17    /// Device type.
18    #[serde(rename = "deviceType")]
19    pub typ: Dev,
20
21    /// ID of the hub the device is connected to.
22    #[serde(rename = "hubDeviceId")]
23    pub hub: String,
24}
25
26/// A list of devices.
27#[derive(Clone, Debug, Deserialize, PartialEq)]
28pub struct Devices {
29    /// Devices.
30    #[serde(rename = "deviceList")]
31    pub devices: Vec<Device>,
32}
33
34/// Device type.
35#[derive(Clone, Debug, Deserialize, PartialEq)]
36#[serde(field_identifier)]
37pub enum Dev {
38    /// Hub 2.
39    #[serde(rename = "Hub 2")]
40    Hub2,
41
42    /// Thermo-hygrometer.
43    #[serde(rename = "WoIOSensor")]
44    IOThermoHygrometer,
45
46    /// Other device type.
47    Other(String),
48}
49
50/// Device status.
51#[derive(Clone, Debug, Deserialize, PartialEq)]
52pub enum DevStatus {
53    Hub2(Hub2Status),
54    IOThermoHygrometer(IOThermoHygrometerStatus),
55    Other,
56}
57
58impl SwitchBot {
59    /// Get all devices.
60    pub async fn get_devices(&self) -> Result<Vec<Device>> {
61        Ok(self.get::<Devices>("v1.1/devices").await?.devices)
62    }
63
64    /// Get device status.
65    pub async fn get_status(&self, dev: &Device) -> Result<DevStatus> {
66        match dev.typ {
67            Dev::Hub2 => Ok(DevStatus::Hub2(self.get_hub2_status(&dev.id).await?)),
68            Dev::IOThermoHygrometer => Ok(DevStatus::IOThermoHygrometer(
69                self.get_io_thermo_hygrometer_status(&dev.id).await?,
70            )),
71            Dev::Other(_) => Ok(DevStatus::Other),
72        }
73    }
74}