1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
extern crate serde;
extern crate serde_json;
use serde_json::value::Value;
pub struct Bridge {
pub ip: String,
pub key: String,
pub client: reqwest::Client,
pub base_url: String,
}
impl Bridge {
pub fn link(ip: String, key: String) -> Self {
let client = reqwest::Client::new();
let base_url = format!("http://{}/api/{}/", ip, key);
Bridge {
ip,
key,
client,
base_url,
}
}
pub fn send(
&self,
endpoint: &str,
req_type: RequestType,
params: Option<&serde_json::value::Value>,
) -> Result<reqwest::Response, Box<dyn std::error::Error>> {
let target = format!("{}{}", self.base_url, endpoint);
let response = match req_type {
RequestType::Post => self.client.post(&target).json(¶ms).send()?,
RequestType::Get => self.client.get(&target).send()?,
RequestType::Put => self.client.put(&target).json(¶ms).send()?,
};
Ok(response)
}
pub fn state(&self, light: u8, state: &Value) -> Result<(), Box<dyn std::error::Error>> {
self.send(
&format!("lights/{}/state", light),
RequestType::Put,
Some(state),
)?;
Ok(())
}
pub fn state_mult(
&self,
lights: Vec<u8>,
state: &Value,
) -> Result<(), Box<dyn std::error::Error>> {
for light in lights.iter() {
self.state(*light, state)?;
}
Ok(())
}
}
#[derive(PartialEq)]
pub enum RequestType {
Get,
Post,
Put,
}