switchbot_api/
device.rs

1use std::{fmt::Display, rc::Rc};
2
3use super::*;
4
5#[derive(Debug, serde::Deserialize)]
6#[allow(non_snake_case)]
7pub struct Device {
8    deviceId: String,
9    deviceName: String,
10    #[serde(default)]
11    deviceType: String,
12    #[serde(default)]
13    remoteType: String,
14    hubDeviceId: String,
15
16    #[serde(skip)]
17    service: Rc<SwitchBotService>,
18}
19
20impl Device {
21    pub fn device_id(&self) -> &str {
22        &self.deviceId
23    }
24
25    pub fn device_name(&self) -> &str {
26        &self.deviceName
27    }
28
29    pub fn is_remote(&self) -> bool {
30        !self.remoteType.is_empty()
31    }
32
33    pub fn device_type(&self) -> &str {
34        &self.deviceType
35    }
36
37    pub fn remote_type(&self) -> &str {
38        &self.remoteType
39    }
40
41    pub fn hub_device_id(&self) -> &str {
42        &self.hubDeviceId
43    }
44
45    pub(crate) fn set_service(&mut self, service: Rc<SwitchBotService>) {
46        self.service = service;
47    }
48
49    pub async fn command(&self, command: &CommandRequest) -> anyhow::Result<()> {
50        self.service.command(self.device_id(), command).await
51    }
52}
53
54impl Display for Device {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        if f.alternate() {
57            writeln!(f, "Name: {}", self.device_name())?;
58            writeln!(f, "ID: {}", self.device_id())?;
59            if self.is_remote() {
60                write!(f, "Remote Type: {}", self.remote_type())?;
61            } else {
62                write!(f, "Type: {}", self.device_type())?;
63            }
64            return Ok(());
65        }
66        write!(
67            f,
68            "{} ({}, ID:{})",
69            self.deviceName,
70            if self.is_remote() {
71                self.remote_type()
72            } else {
73                self.device_type()
74            },
75            self.deviceId
76        )
77    }
78}