forked from deviceplug/btleplug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent_driven_discovery.rs
67 lines (59 loc) · 2.43 KB
/
event_driven_discovery.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
// See the "macOS permissions note" in README.md before running this on macOS
// Big Sur or later.
use btleplug::api::{bleuuid::BleUuid, Central, CentralEvent, Manager as _, ScanFilter};
use btleplug::platform::{Adapter, Manager};
use futures::stream::StreamExt;
use std::error::Error;
async fn get_central(manager: &Manager) -> Adapter {
let adapters = manager.adapters().await.unwrap();
adapters.into_iter().nth(0).unwrap()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let manager = Manager::new().await?;
// get the first bluetooth adapter
// connect to the adapter
let central = get_central(&manager).await;
// Each adapter has an event stream, we fetch via events(),
// simplifying the type, this will return what is essentially a
// Future<Result<Stream<Item=CentralEvent>>>.
let mut events = central.events().await?;
// start scanning for devices
central.start_scan(ScanFilter::default()).await?;
// Print based on whatever the event receiver outputs. Note that the event
// receiver blocks, so in a real program, this should be run in its own
// thread (not task, as this library does not yet use async channels).
while let Some(event) = events.next().await {
match event {
CentralEvent::DeviceDiscovered(id) => {
println!("DeviceDiscovered: {:?}", id);
}
CentralEvent::DeviceConnected(id) => {
println!("DeviceConnected: {:?}", id);
}
CentralEvent::DeviceDisconnected(id) => {
println!("DeviceDisconnected: {:?}", id);
}
CentralEvent::ManufacturerDataAdvertisement {
id,
manufacturer_data,
} => {
println!(
"ManufacturerDataAdvertisement: {:?}, {:?}",
id, manufacturer_data
);
}
CentralEvent::ServiceDataAdvertisement { id, service_data } => {
println!("ServiceDataAdvertisement: {:?}, {:?}", id, service_data);
}
CentralEvent::ServicesAdvertisement { id, services } => {
let services: Vec<String> =
services.into_iter().map(|s| s.to_short_string()).collect();
println!("ServicesAdvertisement: {:?}, {:?}", id, services);
}
_ => {}
}
}
Ok(())
}