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
use crate::{
ble::{self, PeripheralOps},
proto, Cube,
};
use anyhow::{anyhow, Context, Result};
pub struct Searcher {
searcher: ble::Searcher,
}
impl Searcher {
pub fn new() -> Self {
Self {
searcher: ble::searcher(),
}
}
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()
.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)
.await
.context("Error on searching cubes")?)
}
}