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
use crate::{
ble::{self, PeripheralOps},
proto, Cube,
};
use anyhow::{anyhow, Context, Result};
use std::time::Duration;
pub struct Searcher {
searcher: ble::Searcher,
timeout: Duration,
}
impl Searcher {
pub fn new() -> Self {
Self::new_with_timeout(Duration::from_secs(3))
}
pub fn new_with_timeout(timeout: Duration) -> Self {
Self {
searcher: ble::searcher(),
timeout,
}
}
pub async fn all(&mut self) -> Result<Vec<Cube>> {
Ok(self
.do_search()
.await?
.into_iter()
.map(|a| Cube::new(a))
.collect())
}
pub async fn nearest(&mut self) -> Result<Cube> {
self.do_search()
.await?
.into_iter()
.map(|c| c)
.max_by(|a, b| a.rssi().cmp(&b.rssi()))
.map(|a| Cube::new(a))
.ok_or_else(|| anyhow!("No cube found"))
}
async fn do_search(&mut self) -> Result<Vec<ble::Peripheral>> {
Ok(self
.searcher
.search(&proto::UUID_SERVICE, self.timeout)
.await
.context("Error on searching cubes")?)
}
}