-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.rs
144 lines (131 loc) · 5.71 KB
/
test.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
use btleplug::api::{Central, CentralEvent, Manager as _, Peripheral, ScanFilter};
use btleplug::platform::{Manager, PeripheralId};
use color_eyre::eyre::eyre;
use color_eyre::Result;
use futures::stream::StreamExt;
use futures::{ready, Stream};
use ruuvi_sensor_protocol::{BatteryPotential, Humidity, ParseError, SensorValues, Temperature};
use std::collections::HashMap;
use std::future::{ready, Future};
use std::pin::Pin;
use std::task::{Context, Poll};
// struct Payload {
// humdity: f64
// }
//
// struct SensorStream {
// events: Pin<Box<dyn Stream<Item=CentralEvent>+Send>>
// }
//
// impl Stream for SensorStream {
// type Item = CentralEvent;
//
// fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
//
// // Box::pin(BroadcastStream::new(receiver).filter_map(|x| async move {
// // if x.is_ok() {
// // Some(x.unwrap())
// // } else {
// // None
// // }
// // }))
//
// self.events.poll_next()
//
// }
//
// }
#[tokio::main]
async fn main() -> Result<()> {
let manager = Manager::new().await?;
let adapters = manager.adapters().await?;
let central = adapters.into_iter().next().ok_or(eyre!("No BT Adapter"))?;
let mut events = central.events().await?;
central.start_scan(ScanFilter::default()).await?;
// Store device names as we discover them.
let mut device_names = HashMap::<PeripheralId, String>::new();
while let Some(event) = events.next().await {
match event {
CentralEvent::DeviceDiscovered(id) => {
let peripheral = central.peripheral(&id).await?;
if let Some(prop) = peripheral.properties().await? {
if let Some(name) = prop.local_name {
device_names.insert(id, name);
}
}
}
CentralEvent::ServiceDataAdvertisement { id, service_data } => {
if let Some(decoded) = btsensor::Reading::decode(&service_data) {
match decoded {
btsensor::Reading::BtHomeV2(v2) => {
let s = v2
.elements
.iter()
.map(|e| {
let mut value = String::new();
if let Some(val_bool) = e.value_bool() {
value = val_bool.to_string()
}
if let Some(val_float) = e.value_float() {
value = val_float.to_string()
}
if let Some(val_int) = e.value_int() {
value = val_int.to_string()
}
format!("{}: {}{}", e.name(), value, e.unit())
})
.collect::<Vec<String>>()
.join("\t");
// Only print readings if we've discovered the device name.
if let Some(name) = device_names.get(&id) {
println!("{} {}", name, s)
}
}
_ => {
// Should probably handle bthomev1, pvvx, etc.
if let Some(name) = device_names.get(&id) {
println!("{} unknown service data", name)
} else {
println!("{} unknown service data", id)
}
}
}
}
}
CentralEvent::DeviceConnected(_id) => { /* println!("DeviceConnected: {:?}", id); */ }
CentralEvent::DeviceDisconnected(_id) => { /* println!("DeviceDisconnected: {:?}", id); */
}
CentralEvent::ManufacturerDataAdvertisement {
id: id,
manufacturer_data: data,
} => {
if let Some(name) = device_names.get(&id) {
for (id, data) in data.iter() {
if let Ok(parsed) =
SensorValues::from_manufacturer_specific_data(id.clone(), data)
{
let mut output = name.clone();
if let Some(humidity) = parsed.humidity_as_ppm() {
output =
format!("{output}\thumidity {}%", humidity as f32 / 10000.0);
}
if let Some(temp) = parsed.temperature_as_millicelsius() {
output =
format!("{output}\ttemperature {}°C", temp as f32 / 1000.0);
}
if let Some(batt) = parsed.battery_potential_as_millivolts() {
output = format!("{output}\tvoltage {}V", batt as f32 / 1000.0);
}
println!("{output}")
}
}
}
/* println!("ManufacturerDataAdvertisement: {:?} {:?}", id, data); */
}
CentralEvent::ServicesAdvertisement { id: _, services: _ } => { /* println!("ServicesAdvertisement: {:?}, {:?}", id, services); */
}
CentralEvent::DeviceUpdated(_) => {}
}
}
Ok(())
}