seamapi_rs/
devices.rs

1use anyhow::{bail, Context, Result};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4pub struct Devices(pub String, pub String);
5
6#[derive(Serialize, Deserialize, Debug)]
7pub struct Device {
8    pub device_id: String,
9    pub device_type: String,
10    pub capabilities_supported: Vec<Value>,
11    pub properties: Properties,
12    pub location: Value,
13    pub connected_account_id: String,
14    pub workspace_id: String,
15    pub created_at: String,
16    pub errors: Vec<Value>,
17}
18
19#[derive(Serialize, Deserialize, Debug)]
20pub struct Properties {
21    pub locked: bool,
22    pub online: bool,
23    pub battery_level: f64,
24    pub schlage_metadata: Option<SchlageMetadata>,
25    pub august_metadata: Option<SchlageMetadata>,
26    pub name: String,
27}
28
29#[derive(Serialize, Deserialize, Debug)]
30pub struct SchlageMetadata {
31    pub device_id: String,
32    pub device_name: String,
33}
34
35impl Devices {
36    pub fn get(self, device_id: String) -> Result<Device> {
37        let url = format!("{}/devices/get?device_id={}", self.1, device_id);
38        let header = format!("Bearer {}", self.0);
39
40        let req = reqwest::blocking::Client::new()
41            .get(url)
42            .header("Authorization", header)
43            .send()
44            .context("Failed to send get request")?;
45
46        if req.status() == reqwest::StatusCode::NOT_FOUND {
47            bail!("device not found");
48        } else if req.status() != reqwest::StatusCode::OK {
49            bail!("{}", req.text().context("Really bad API failure")?)
50        }
51
52        let json: crate::Response = req.json().context("Failed to deserialize JSON")?;
53        Ok(json.device.unwrap())
54    }
55
56    pub fn list(self) -> Result<Vec<Device>> {
57        let url = format!("{}/devices/list", self.1);
58        let header = format!("Bearer {}", self.0);
59
60        let req = reqwest::blocking::Client::new()
61            .get(url)
62            .header("Authorization", header)
63            .send()
64            .context("Failed to send get request")?;
65
66        if req.status() != reqwest::StatusCode::OK {
67            bail!(
68                "{}",
69                req.text().context("Failed to turn response into text")?
70            );
71        }
72
73        let json: crate::Response = req.json().context("Failed to deserialize JSON")?;
74        Ok(json.devices.unwrap())
75    }
76}