switchbot_api/
device.rs

1use std::{fmt::Display, rc::Rc};
2
3use super::*;
4
5/// Represents a device.
6///
7/// For the details of fields, please refer to the [devices] section
8/// of the API documentation.
9///
10/// [devices]: https://github.com/OpenWonderLabs/SwitchBotAPI?tab=readme-ov-file#devices
11#[derive(Debug, serde::Deserialize)]
12#[allow(non_snake_case)]
13pub struct Device {
14    deviceId: String,
15    deviceName: String,
16    #[serde(default)]
17    deviceType: String,
18    #[serde(default)]
19    remoteType: String,
20    hubDeviceId: String,
21
22    #[serde(skip)]
23    service: Rc<SwitchBotService>,
24}
25
26impl Device {
27    /// The device ID>
28    pub fn device_id(&self) -> &str {
29        &self.deviceId
30    }
31
32    /// The device name.
33    /// This is the name configured in the SwitchBot app.
34    pub fn device_name(&self) -> &str {
35        &self.deviceName
36    }
37
38    /// True if this device is an infrared remote device.
39    pub fn is_remote(&self) -> bool {
40        !self.remoteType.is_empty()
41    }
42
43    /// The device type.
44    /// This is empty if this is an infrared remote device.
45    pub fn device_type(&self) -> &str {
46        &self.deviceType
47    }
48
49    /// The device type for an infrared remote device.
50    pub fn remote_type(&self) -> &str {
51        &self.remoteType
52    }
53
54    /// The parent Hub ID.
55    pub fn hub_device_id(&self) -> &str {
56        &self.hubDeviceId
57    }
58
59    pub(crate) fn set_service(&mut self, service: Rc<SwitchBotService>) {
60        self.service = service;
61    }
62
63    /// Send the `command` to the [SwitchBot API].
64    ///
65    /// Please also see the [`CommandRequest`].
66    pub async fn command(&self, command: &CommandRequest) -> anyhow::Result<()> {
67        self.service.command(self.device_id(), command).await
68    }
69}
70
71impl Display for Device {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        if f.alternate() {
74            writeln!(f, "Name: {}", self.device_name())?;
75            writeln!(f, "ID: {}", self.device_id())?;
76            if self.is_remote() {
77                write!(f, "Remote Type: {}", self.remote_type())?;
78            } else {
79                write!(f, "Type: {}", self.device_type())?;
80            }
81            return Ok(());
82        }
83        write!(
84            f,
85            "{} ({}, ID:{})",
86            self.deviceName,
87            if self.is_remote() {
88                self.remote_type()
89            } else {
90                self.device_type()
91            },
92            self.deviceId
93        )
94    }
95}