-
Notifications
You must be signed in to change notification settings - Fork 37
/
ip.rs
286 lines (241 loc) · 9.29 KB
/
ip.rs
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
use async_trait::async_trait;
use futures::{
future::{BoxFuture, FutureExt},
lock::Mutex,
};
use log::{error, info};
use std::sync::Arc;
use crate::{
accessory::HapAccessory,
config::Config,
event::{Event, EventEmitter},
pointer,
server::Server,
storage::{accessory_database::AccessoryDatabase, Storage},
transport::{http::server::Server as HttpServer, mdns::MdnsResponder},
BonjourStatusFlag,
Result,
};
/// HAP Server via TCP/IP.
#[derive(Clone)]
pub struct IpServer {
config: pointer::Config,
storage: pointer::Storage,
accessory_database: pointer::AccessoryDatabase,
http_server: HttpServer,
mdns_responder: pointer::MdnsResponder,
aid_cache: Arc<Mutex<Vec<u64>>>,
}
impl IpServer {
/// Creates a new [`IpServer`](IpServer).
///
/// # Examples
/// ```no_run
/// use tokio;
///
/// use hap::{
/// accessory::{lightbulb::LightbulbAccessory, AccessoryCategory, AccessoryInformation},
/// server::{IpServer, Server},
/// storage::{FileStorage, Storage},
/// Config,
/// MacAddress,
/// Pin,
/// Result,
/// };
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// let lightbulb = LightbulbAccessory::new(1, AccessoryInformation {
/// name: "Acme Lightbulb".into(),
/// ..Default::default()
/// })?;
///
/// let mut storage = FileStorage::current_dir().await?;
///
/// let config = match storage.load_config().await {
/// Ok(mut config) => {
/// config.redetermine_local_ip();
/// storage.save_config(&config).await?;
/// config
/// },
/// Err(_) => {
/// let config = Config {
/// pin: Pin::new([1, 1, 1, 2, 2, 3, 3, 3])?,
/// name: "Acme Lightbulb".into(),
/// device_id: MacAddress::from([10, 20, 30, 40, 50, 60]),
/// category: AccessoryCategory::Lightbulb,
/// ..Default::default()
/// };
/// storage.save_config(&config).await?;
/// config
/// },
/// };
///
/// let mut server = IpServer::new(config, storage).await?;
/// server.add_accessory(lightbulb).await?;
///
/// let handle = server.run_handle();
///
/// std::env::set_var("RUST_LOG", "hap=info");
/// env_logger::init();
///
/// handle.await
/// }
/// ```
pub async fn new<S: Storage + Send + Sync + 'static>(config: Config, storage: S) -> Result<Self> {
let config = Arc::new(Mutex::new(config));
let storage: pointer::Storage = Arc::new(Mutex::new(Box::new(storage)));
let config_ = config.clone();
let storage_ = storage.clone();
let mut event_emitter = EventEmitter::new();
let mut s = storage_.lock().await;
if s.count_pairings().await? > 0 {
info!("1 or more controllers paired; setting Bonjour status flag to `Zero`");
let mut c = config_.lock().await;
c.status_flag = BonjourStatusFlag::Zero;
s.save_config(&c).await?;
} else {
info!("0 controllers paired; setting Bonjour status flag to `Not Paired`");
let mut c = config_.lock().await;
c.status_flag = BonjourStatusFlag::NotPaired;
s.save_config(&c).await?;
}
drop(s);
let mdns_responder = Arc::new(Mutex::new(MdnsResponder::new(config.clone()).await));
let mdns_responder_ = mdns_responder.clone();
event_emitter.add_listener(Box::new(move |event| {
let config_ = config_.clone();
let storage_ = storage_.clone();
let mdns_responder_ = mdns_responder_.clone();
async move {
match *event {
Event::ControllerPaired { id } => {
info!("controller {} paired", id);
let pairing_count = storage_.lock().await.count_pairings().await;
if let Ok(count) = pairing_count {
if count > 0 {
info!("1 or more controllers paired; setting Bonjour status flag to `Zero`");
let mut c = config_.lock().await;
c.status_flag = BonjourStatusFlag::Zero;
storage_
.lock()
.await
.save_config(&c)
.await
.map_err(|e| error!("error saving the config: {:?}", e))
.ok();
drop(c);
mdns_responder_.lock().await.update_records().await;
}
}
},
Event::ControllerUnpaired { id } => {
info!("controller {} unpaired", id);
let pairing_count = storage_.lock().await.count_pairings().await;
// TODO - `pairing_count` is an Err
if let Ok(count) = pairing_count {
if count == 0 {
info!("0 controllers paired; setting Bonjour status flag to `Not Paired`");
let mut c = config_.lock().await;
c.status_flag = BonjourStatusFlag::NotPaired;
storage_
.lock()
.await
.save_config(&c)
.await
.map_err(|e| error!("error saving the config: {:?}", e))
.ok();
drop(c);
mdns_responder_.lock().await.update_records().await;
}
}
},
_ => {},
}
}
.boxed()
}));
let event_emitter = Arc::new(Mutex::new(event_emitter));
let accessory_database = Arc::new(Mutex::new(AccessoryDatabase::new(event_emitter.clone())));
let http_server = HttpServer::new(
config.clone(),
storage.clone(),
accessory_database.clone(),
event_emitter,
mdns_responder.clone(),
);
let mut storage_lock = storage.lock().await;
let aid_cache = Arc::new(Mutex::new(match storage_lock.load_aid_cache().await {
Ok(aid_cache) => aid_cache,
Err(_) => {
storage_lock.delete_aid_cache().await.ok();
let aid_cache = Vec::new();
storage_lock.save_aid_cache(&aid_cache).await?;
aid_cache
},
}));
drop(storage_lock);
let server = IpServer {
config,
storage,
accessory_database,
http_server,
mdns_responder,
aid_cache,
};
Ok(server)
}
}
#[async_trait]
impl Server for IpServer {
fn run_handle(&self) -> BoxFuture<Result<()>> {
let http_handle = self.http_server.run_handle();
let mdns_responder = self.mdns_responder.clone();
let handle = async move {
let mdns_handle = mdns_responder.lock().await.run_handle();
futures::try_join!(http_handle, mdns_handle.map(|_| Ok(())))?;
Ok(())
}
.boxed();
Box::pin(handle)
}
fn config_pointer(&self) -> pointer::Config { self.config.clone() }
fn storage_pointer(&self) -> pointer::Storage { self.storage.clone() }
async fn add_accessory<A: HapAccessory + 'static>(&self, accessory: A) -> Result<pointer::Accessory> {
let aid = accessory.get_id();
let accessory = self
.accessory_database
.lock()
.await
.add_accessory(Box::new(accessory))?;
let mut aid_cache = self.aid_cache.lock().await;
if !aid_cache.contains(&aid) {
aid_cache.push(aid);
self.storage.lock().await.save_aid_cache(&aid_cache).await?;
let mut config = self.config.lock().await;
config.configuration_number += 1;
self.storage.lock().await.save_config(&config).await?;
}
Ok(accessory)
}
async fn remove_accessory(&self, accessory: &pointer::Accessory) -> Result<()> {
let aid = accessory.lock().await.get_id();
self.accessory_database
.lock()
.await
.remove_accessory(&accessory)
.await?;
let mut aid_cache = self.aid_cache.lock().await;
if aid_cache.contains(&aid) {
aid_cache.retain(|id| *id != aid);
self.storage.lock().await.save_aid_cache(&aid_cache).await?;
let mut config = self.config.lock().await;
config.configuration_number += 1;
}
Ok(())
}
// async fn factory_reset(&mut self) -> Result<()> {
// unimplemented!();
// Ok(())
// }
}