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
|
use std::collections::HashMap;
use std::process;
use std::sync::{mpsc::channel, Arc};
use std::time::{SystemTime, UNIX_EPOCH};
use rumble;
use rumble::api::{BDAddr, Central, CentralEvent, Peripheral};
use rumble::bluez::adapter::ConnectedAdapter;
use failure::Error;
use ruuvi_sensor_protocol::{ParseError, SensorValues};
use serde::{Deserialize, Serialize};
use serde_json;
use docopt;
use reqwest;
#[derive(Serialize)]
struct Measurement {
address: String,
// Unix timestamp.
timestamp: u64,
// Relative humidity, percent.
humidity: Option<f64>,
// Temperature, Celcius.
temperature: Option<f64>,
// Pressure, kPa.
pressure: Option<f64>,
// Battery potential, volts.
battery_potential: Option<f64>,
}
impl Measurement {
fn new(address: BDAddr, values: SensorValues) -> Measurement {
Measurement {
address: format!("{}", address),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs(),
humidity: values.humidity.map(|x| f64::from(x) / 10000.0),
temperature: values.temperature.map(|x| f64::from(x) / 1000.0),
pressure: values.pressure.map(|x| f64::from(x) / 1000.0),
battery_potential: values.battery_potential.map(|x| f64::from(x) / 1000.0),
}
}
}
const USAGE: &str = "
ruuvitag-upload
A tool for collecting a set of ruuvitag sensor measurements
and uploading them for further processing.
The measurements are formatted as JSON with the following
structure
{
\"<ALIAS>\": {
\"address\": \"XX:XX:XX:XX:XX:XX\",
\"timestamp\": <seconds since unix epoch>,
\"humidity\": <0-100%>,
\"pressure\": <kPa>,
\"temperature\": <Celcius>,
\"battery_potential\": <volts>
},
...
}
where ALIAS will either be the address of the sensor, or
an alias that you can define.
USAGE:
ruuvitag-upload [--url=URL] <sensor>...
ruuvitag-upload -h | --help
ruuvitag-upload --version
ARGUMENTS:
<sensor>...
A sensor address and optionally a human-readable
alias. You can either specify the address as
XX:XX:XX:XX:XX:XX or you can attach a human-
readable alias to the address
XX:XX:XX:XX:XX:XX=mysensor.
OPTIONS:
-u URL, --url=URL
Where the measurements are uploaded to. If you don't
specify this, the measurements are written to stdout.
-h, --help
Show this message.
--version
Show the version number.
";
#[derive(Deserialize)]
struct Args {
arg_sensor: Vec<String>,
flag_url: Option<String>,
}
fn parse_sensor(s: &str) -> (&str, &str) {
let mut it = s.split('=');
let address = it.next().unwrap();
let alias = if let Some(s) = it.next() { s } else { address };
(address, alias)
}
fn main() {
if let Err(e) = run() {
eprintln!("error: {}", e);
process::exit(1);
}
}
fn run() -> Result<(), Error> {
let version = format!(
"{}.{}.{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH")
);
let args: Args = docopt::Docopt::new(USAGE)
.and_then(|d| d.help(true).version(Some(version)).deserialize())
.unwrap_or_else(|e| e.exit());
let sensors: HashMap<String, String> = args
.arg_sensor
.iter()
.map(|x| parse_sensor(x))
.map(|(address, alias)| (address.to_string(), alias.to_string()))
.collect();
let manager = rumble::bluez::manager::Manager::new()?;
let mut adapter = manager.adapters()?.into_iter().nth(0).unwrap();
adapter = manager.down(&adapter)?;
adapter = manager.up(&adapter)?;
let central = Arc::new(adapter.connect()?);
let central_clone = central.clone();
let (meas_tx, meas_rx) = channel();
central.on_event(Box::new(move |event| {
if let Some(result) = on_event(¢ral_clone, event) {
if let Ok(measurement) = result {
let _ = meas_tx.send(measurement);
}
}
}));
central.start_scan()?;
let mut measurements = HashMap::new();
loop {
let measurement = meas_rx.recv()?;
if let Some(alias) = sensors.get(&measurement.address) {
measurements.insert(alias.clone(), measurement);
if measurements.len() == sensors.len() {
break;
}
}
}
central.stop_scan()?;
if let Some(url) = args.flag_url {
let client = reqwest::Client::new();
client
.post(&url)
.json(&measurements)
.send()?
.error_for_status()?;
} else {
println!("{}", serde_json::to_string(&measurements).unwrap());
}
Ok(())
}
fn on_event(
central: &ConnectedAdapter,
event: CentralEvent,
) -> Option<Result<Measurement, ParseError>> {
match event {
CentralEvent::DeviceDiscovered(addr) => on_event_with_address(central, addr),
CentralEvent::DeviceUpdated(addr) => on_event_with_address(central, addr),
_ => None,
}
}
fn on_event_with_address(
central: &ConnectedAdapter,
address: BDAddr,
) -> Option<Result<Measurement, ParseError>> {
match central.peripheral(address) {
Some(peripheral) => match to_sensor_value(peripheral) {
Ok(values) => Some(Ok(Measurement::new(address, values))),
Err(e) => Some(Err(e)),
},
None => None,
}
}
fn to_sensor_value<T: Peripheral>(peripheral: T) -> Result<SensorValues, ParseError> {
match peripheral.properties().manufacturer_data {
Some(data) => from_manufacturer_data(&data),
None => Err(ParseError::EmptyValue),
}
}
fn from_manufacturer_data(data: &[u8]) -> Result<SensorValues, ParseError> {
if data.len() > 2 {
let id = u16::from(data[0]) + (u16::from(data[1]) << 8);
SensorValues::from_manufacturer_specific_data(id, &data[2..])
} else {
Err(ParseError::EmptyValue)
}
}
|