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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use hyper::Client;
use hyper::client::Body;
use std::io::Read;
use serde_json::{to_vec, from_reader};
use errors::{Result, HueError};
use ::hue::*;
use ::json::*;
#[cfg(feature = "nupnp")]
pub fn discover() -> Result<Vec<Discovery>> {
Client::new()
.get("https://www.meethue.com/api/nupnp")
.send()
.map_err(HueError::from)
.and_then(|ref mut r| from_reader(r).map_err(From::from))
}
#[cfg(feature = "ssdp")]
pub fn discover_upnp() -> ::std::result::Result<Vec<String>, ::ssdp::SSDPError> {
use ssdp::header::{HeaderMut, Man, MX, ST};
use ssdp::message::SearchRequest;
use ssdp::FieldMap;
let mut request = SearchRequest::new();
request.set(Man);
request.set(MX(5));
request.set(ST::Target(FieldMap::upnp("IpBridge")));
request.multicast().map(|r| {
r.into_iter()
.map(|(_, src)| src.ip().to_string())
.collect()
})
}
pub fn register_user(ip: &str, devicetype: &str) -> Result<String> {
let client = Client::new();
let body = format!("{{\"devicetype\": {:?}}}", devicetype);
let body = body.as_bytes();
let url = format!("http://{}/api", ip);
let mut resp = client.post(&url)
.body(Body::BufBody(body, body.len()))
.send()?;
from_reader::<_, Vec<HueResponse<User>>>(&mut resp)?
.pop()
.unwrap()
.into_result()
.map(|u| u.username)
}
#[derive(Debug)]
pub struct Bridge {
client: Client,
url: String,
}
fn send_with_body<'a, T: Deserialize>(rb: RequestBuilder<'a>, body: &'a [u8]) -> Result<T> {
send(rb.body(Body::BufBody(body, body.len())))
}
fn send<T: Deserialize>(rb: RequestBuilder) -> Result<T> {
rb.send()
.map_err(HueError::from)
.and_then(|ref mut resp| {
let mut buf = Vec::new();
resp.read_to_end(&mut buf).map_err(::serde_json::Error::from)?;
match from_reader::<_, T>(&mut &*buf) {
Ok(t) => Ok(t),
Err(_) => from_reader::<_, Vec<HueResponse<T>>>(&mut &*buf)?
.into_iter()
.next()
.ok_or_else(|| "Malformed response".into())
.and_then(HueResponse::into_result)
}
})
}
#[test]
fn get_ip_and_username() {
let b = Bridge::new("test", "hello");
assert_eq!(b.get_ip(), "test");
assert_eq!(b.get_username(), "hello");
}
pub type SuccessVec = Vec<Map<String, JsonValue>>;
use serde::Deserialize;
use hyper::client::RequestBuilder;
fn extract<T: Deserialize>(responses: Vec<HueResponse<T>>) -> Result<Vec<T>> {
let mut res_v = Vec::with_capacity(responses.len());
for val in responses {
res_v.push(val.into_result()?)
}
Ok(res_v)
}
impl Bridge {
pub fn new<S: Into<String>, U: Into<String>>(ip: S, username: U) -> Self {
Bridge {
client: Client::new(),
url: format!("http://{}/api/{}/", ip.into(), username.into()),
}
}
pub fn get_ip(&self) -> &str {
self.url.split('/').nth(2).unwrap()
}
pub fn get_username(&self) -> &str {
self.url.split('/').nth(4).unwrap()
}
pub fn get_all_lights(&self) -> Result<Map<usize, Light>> {
send(self.client.get(&format!("{}lights", self.url)))
}
pub fn get_light(&self, id: usize) -> Result<Light> {
send(self.client.get(&format!("{}lights/{}", self.url, id)))
}
pub fn get_new_lights(&self) -> Result<Map<usize, Light>> {
send(self.client.get(&format!("{}lights/new", self.url)))
}
pub fn search_for_new_lights(&self) -> Result<SuccessVec> {
send(self.client.post(&format!("{}lights", self.url))).and_then(extract)
}
pub fn set_light_state(&self, id: usize, command: &LightCommand) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}lights/{}/state", self.url, id)),
&to_vec(command)?)
.and_then(extract)
}
pub fn rename_light(&self, id: usize, name: String) -> Result<SuccessVec> {
let mut name_map = Map::new();
name_map.insert("name".to_owned(), name);
send_with_body(self.client.put(&format!("{}lights/{}", self.url, id)),
&to_vec(&name_map)?)
.and_then(extract)
}
pub fn delete_light(&self, id: usize) -> Result<SuccessVec> {
send(self.client.delete(&format!("{}lights/{}", self.url, id))).and_then(extract)
}
pub fn get_all_groups(&self) -> Result<Map<usize, Group>> {
send(self.client.get(&format!("{}groups", self.url)))
}
pub fn create_group(&self, name: String, lights: Vec<usize>, group_type: GroupType, room_class: Option<RoomClass>) -> Result<usize> {
let g = Group {
name: name,
lights: lights,
group_type: group_type,
class: room_class,
state: None,
action: None,
};
let r: HueResponse<Id<usize>> = send_with_body(self.client.post(&format!("{}groups", self.url)),
&to_vec(&g)?)?;
r.into_result().map(|g| g.id)
}
pub fn get_group_attributes(&self, id: usize) -> Result<Group> {
send(self.client.get(&format!("{}groups/{}", self.url, id)))
}
pub fn set_group_attributes(&self, id: usize, attr: &GroupCommand) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}groups/{}", self.url, id)),
&to_vec(attr)?)
.and_then(extract)
}
pub fn set_group_state(&self, id: usize, state: &LightCommand) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}groups/{}/action", self.url, id)),
&to_vec(state)?)
.and_then(extract)
}
pub fn delete_group(&self, id: usize) -> Result<Vec<String>> {
send(self.client.delete(&format!("{}groups/{}", self.url, id))).and_then(extract)
}
pub fn get_configuration(&self) -> Result<Configuration> {
send(self.client.get(&format!("{}config", self.url)))
}
pub fn modify_configuration(&self, command: &ConfigurationModifier) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}config", self.url)),
&to_vec(command)?)
.and_then(extract)
}
pub fn delete_user(&self, username: &str) -> Result<Vec<String>> {
send(self.client.delete(&format!("{}config/whitelist/{}", self.url, username)))
.and_then(extract)
}
pub fn get_full_state(&self) -> Result<FullState> {
send(self.client.get(&self.url))
}
pub fn recall_scene_in_group(&self, group_id: usize, scene_id: &str) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}groups/{}/action", self.url, group_id)),
&to_vec(&SceneRecall{scene: scene_id})?)
.and_then(extract)
}
pub fn get_all_scenes(&self) -> Result<Map<String, Scene>> {
send(self.client.get(&format!("{}scenes", self.url)))
}
pub fn create_scene(&self, scene: &SceneCreater) -> Result<String> {
let r: HueResponse<Id<String>> = send_with_body(self.client.post(&format!("{}scenes", self.url)),
&to_vec(scene)?)?;
r.into_result().map(|g| g.id)
}
pub fn modify_scene(&self, id: &str, scene: &SceneModifier) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}scenes/{}", self.url, id)), &to_vec(scene)?)
.and_then(extract)
}
pub fn set_light_state_in_scene(&self, scene_id: &str, light_id: usize,
state: &LightStateChange) -> Result<SuccessVec> {
send_with_body(self.client.put(&format!("{}scenes/{}/lightstates/{}", self.url,
scene_id, light_id)), &to_vec(state)?).and_then(extract)
}
pub fn delete_scene(&self, id: &str) -> Result<Vec<String>> {
send(self.client.delete(&format!("{}scenes/{}", self.url, id))).and_then(extract)
}
pub fn get_scene_with_states(&self, id: &str) -> Result<Scene> {
send(self.client.get(&format!("{}scenes/{}", self.url, id)))
}
}