1use super::{Context, Reading};
15use crate::reader::Reader;
16use crate::AddressBytes;
17
18use aes::Aes128;
19use ccm::aead::{Aead, KeyInit, Payload};
20use ccm::consts::{U13, U4};
21
22#[cfg(feature = "serde")]
23use serde::Serialize;
24
25pub const SERVICE_UUID: u16 = 0xfcd2;
27
28type BtHomeCcm = ccm::Ccm<Aes128, U4, U13>;
29
30#[derive(Debug, Clone, PartialEq, Default)]
32#[cfg_attr(feature = "serde", derive(Serialize))]
33pub struct BtHome {
34 pub encrypted: bool,
36 pub undecryptable: bool,
39 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
42 pub counter: Option<u32>,
43 pub trigger_based: bool,
45 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
47 pub packet_id: Option<u8>,
48 pub measurements: Vec<Measurement>,
50 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
52 pub events: Vec<Event>,
53 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
55 pub text: Vec<String>,
56 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
58 pub raw: Vec<String>,
59 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
61 pub device_type: Option<u16>,
62 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
64 pub firmware: Option<String>,
65 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
67 pub unknown_object: Option<u8>,
68 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "std::ops::Not::not"))]
70 pub truncated: bool,
71}
72
73#[derive(Debug, Clone, PartialEq)]
75#[cfg_attr(feature = "serde", derive(Serialize))]
76pub struct Measurement {
77 pub object_id: u8,
79 pub name: &'static str,
81 pub value: f64,
83 pub unit: &'static str,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[cfg_attr(feature = "serde", derive(Serialize))]
90pub struct Event {
91 pub kind: &'static str,
93 pub event: &'static str,
95 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
97 pub steps: Option<u8>,
98 pub index: u8,
100}
101
102#[derive(Clone, Copy)]
104enum Kind {
105 Unsigned(u8),
106 Signed(u8),
107}
108
109const OBJECTS: &[(u8, &str, Kind, f64, &str)] = {
112 use Kind::{Signed as S, Unsigned as U};
113 &[
114 (0x01, "battery", U(1), 1.0, "%"),
115 (0x02, "temperature", S(2), 0.01, "°C"),
116 (0x03, "humidity", U(2), 0.01, "%"),
117 (0x04, "pressure", U(3), 0.01, "hPa"),
118 (0x05, "illuminance", U(3), 0.01, "lx"),
119 (0x06, "mass", U(2), 0.01, "kg"),
120 (0x07, "mass", U(2), 0.01, "lb"),
121 (0x08, "dewpoint", S(2), 0.01, "°C"),
122 (0x09, "count", U(1), 1.0, ""),
123 (0x0a, "energy", U(3), 0.001, "kWh"),
124 (0x0b, "power", U(3), 0.01, "W"),
125 (0x0c, "voltage", U(2), 0.001, "V"),
126 (0x0d, "pm2_5", U(2), 1.0, "µg/m³"),
127 (0x0e, "pm10", U(2), 1.0, "µg/m³"),
128 (0x0f, "generic_boolean", U(1), 1.0, ""),
129 (0x10, "power_on", U(1), 1.0, ""),
130 (0x11, "opening", U(1), 1.0, ""),
131 (0x12, "co2", U(2), 1.0, "ppm"),
132 (0x13, "tvoc", U(2), 1.0, "µg/m³"),
133 (0x14, "moisture", U(2), 0.01, "%"),
134 (0x15, "battery_low", U(1), 1.0, ""),
135 (0x16, "battery_charging", U(1), 1.0, ""),
136 (0x17, "carbon_monoxide", U(1), 1.0, ""),
137 (0x18, "cold", U(1), 1.0, ""),
138 (0x19, "connectivity", U(1), 1.0, ""),
139 (0x1a, "door", U(1), 1.0, ""),
140 (0x1b, "garage_door", U(1), 1.0, ""),
141 (0x1c, "gas_detected", U(1), 1.0, ""),
142 (0x1d, "heat", U(1), 1.0, ""),
143 (0x1e, "light", U(1), 1.0, ""),
144 (0x1f, "lock", U(1), 1.0, ""),
145 (0x20, "moisture_detected", U(1), 1.0, ""),
146 (0x21, "motion", U(1), 1.0, ""),
147 (0x22, "moving", U(1), 1.0, ""),
148 (0x23, "occupancy", U(1), 1.0, ""),
149 (0x24, "plug", U(1), 1.0, ""),
150 (0x25, "presence", U(1), 1.0, ""),
151 (0x26, "problem", U(1), 1.0, ""),
152 (0x27, "running", U(1), 1.0, ""),
153 (0x28, "safety", U(1), 1.0, ""),
154 (0x29, "smoke", U(1), 1.0, ""),
155 (0x2a, "sound", U(1), 1.0, ""),
156 (0x2b, "tamper", U(1), 1.0, ""),
157 (0x2c, "vibration", U(1), 1.0, ""),
158 (0x2d, "window", U(1), 1.0, ""),
159 (0x2e, "humidity", U(1), 1.0, "%"),
160 (0x2f, "moisture", U(1), 1.0, "%"),
161 (0x3d, "count", U(2), 1.0, ""),
162 (0x3e, "count", U(4), 1.0, ""),
163 (0x3f, "rotation", S(2), 0.1, "°"),
164 (0x40, "distance", U(2), 1.0, "mm"),
165 (0x41, "distance", U(2), 0.1, "m"),
166 (0x42, "duration", U(3), 0.001, "s"),
167 (0x43, "current", U(2), 0.001, "A"),
168 (0x44, "speed", U(2), 0.01, "m/s"),
169 (0x45, "temperature", S(2), 0.1, "°C"),
170 (0x46, "uv_index", U(1), 0.1, ""),
171 (0x47, "volume", U(2), 0.1, "L"),
172 (0x48, "volume", U(2), 1.0, "mL"),
173 (0x49, "volume_flow_rate", U(2), 0.001, "m³/h"),
174 (0x4a, "voltage", U(2), 0.1, "V"),
175 (0x4b, "gas", U(3), 0.001, "m³"),
176 (0x4c, "gas", U(4), 0.001, "m³"),
177 (0x4d, "energy", U(4), 0.001, "kWh"),
178 (0x4e, "volume", U(4), 0.001, "L"),
179 (0x4f, "water", U(4), 0.001, "L"),
180 (0x50, "timestamp", U(4), 1.0, "s"),
181 (0x51, "acceleration", U(2), 0.001, "m/s²"),
182 (0x52, "gyroscope", U(2), 0.001, "°/s"),
183 (0x55, "volume_storage", U(4), 0.001, "L"),
184 (0x56, "conductivity", U(2), 1.0, "µS/cm"),
185 (0x57, "temperature", S(1), 1.0, "°C"),
186 (0x58, "temperature", S(1), 0.35, "°C"),
187 (0x59, "count", S(1), 1.0, ""),
188 (0x5a, "count", S(2), 1.0, ""),
189 (0x5b, "count", S(4), 1.0, ""),
190 (0x5c, "power", S(4), 0.01, "W"),
191 (0x5d, "current", S(2), 0.001, "A"),
192 (0x5e, "direction", U(2), 0.01, "°"),
193 (0x5f, "precipitation", U(2), 0.1, "mm"),
194 (0x60, "channel", U(1), 1.0, ""),
195 (0x61, "rotational_speed", U(2), 1.0, "rpm"),
196 ]
197};
198
199const BUTTON_EVENTS: [&str; 7] = [
200 "none",
201 "press",
202 "double_press",
203 "triple_press",
204 "long_press",
205 "long_double_press",
206 "long_triple_press",
207];
208
209pub fn decode(data: &[u8], ctx: &Context) -> Option<BtHome> {
211 let (&info, body) = data.split_first()?;
212 if info >> 5 != 2 {
213 return None;
214 }
215 let mut out = BtHome {
216 encrypted: info & 0x01 != 0,
217 trigger_based: info & 0x04 != 0,
218 ..BtHome::default()
219 };
220 if !out.encrypted {
221 objects(body, &mut out);
222 return Some(out);
223 }
224 if body.len() < 8 {
226 out.undecryptable = true;
227 out.truncated = true;
228 return Some(out);
229 }
230 let (ct, tail) = body.split_at(body.len() - 8);
231 let counter = [tail[0], tail[1], tail[2], tail[3]];
232 out.counter = Some(u32::from_le_bytes(counter));
233 let key = ctx
234 .address
235 .and_then(|a| ctx.bthome_keys.get(&a).map(|k| (a, k)));
236 match key.and_then(|(addr, key)| {
237 let mut sealed = ct.to_vec();
238 sealed.extend_from_slice(&tail[4..]);
239 BtHomeCcm::new(key.into())
240 .decrypt(
241 (&nonce(&addr, info, counter)).into(),
242 Payload {
243 msg: &sealed,
244 aad: &[],
245 },
246 )
247 .ok()
248 }) {
249 Some(plain) => objects(&plain, &mut out),
250 None => out.undecryptable = true,
251 }
252 Some(out)
253}
254
255fn nonce(addr: &AddressBytes, info: u8, counter: [u8; 4]) -> [u8; 13] {
256 let mut n = [0u8; 13];
257 for (i, b) in addr.iter().rev().enumerate() {
258 n[i] = *b;
259 }
260 n[6..8].copy_from_slice(&SERVICE_UUID.to_le_bytes());
261 n[8] = info;
262 n[9..].copy_from_slice(&counter);
263 n
264}
265
266pub fn encrypt(
270 addr: &AddressBytes,
271 key: &[u8; 16],
272 info: u8,
273 counter: u32,
274 objects: &[u8],
275) -> Vec<u8> {
276 let info = info | 0x01;
277 let c = counter.to_le_bytes();
278 let sealed = BtHomeCcm::new(key.into())
279 .encrypt(
280 (&nonce(addr, info, c)).into(),
281 Payload {
282 msg: objects,
283 aad: &[],
284 },
285 )
286 .unwrap_or_default();
287 let (ct, mic) = sealed.split_at(sealed.len().saturating_sub(4));
288 let mut v = vec![info];
289 v.extend_from_slice(ct);
290 v.extend_from_slice(&c);
291 v.extend_from_slice(mic);
292 v
293}
294
295fn objects(data: &[u8], out: &mut BtHome) {
296 let mut r = Reader::new(data);
297 let (mut buttons, mut dimmers) = (0u8, 0u8);
298 while let Some(id) = r.u8() {
299 let ok = match id {
300 0x00 => r.u8().map(|v| out.packet_id = Some(v)).is_some(),
301 0x3a => r
302 .u8()
303 .map(|e| {
304 buttons = buttons.saturating_add(1);
305 out.events.push(Event {
306 kind: "button",
307 event: match e {
308 0x80 => "hold_press",
309 e => BUTTON_EVENTS
310 .get(usize::from(e))
311 .copied()
312 .unwrap_or("unknown"),
313 },
314 steps: None,
315 index: buttons,
316 });
317 })
318 .is_some(),
319 0x3c => match (r.u8(), r.u8()) {
320 (Some(e), Some(steps)) => {
321 dimmers = dimmers.saturating_add(1);
322 out.events.push(Event {
323 kind: "dimmer",
324 event: match e {
325 0 => "none",
326 1 => "rotate_left",
327 2 => "rotate_right",
328 _ => "unknown",
329 },
330 steps: Some(steps),
331 index: dimmers,
332 });
333 true
334 }
335 _ => false,
336 },
337 0x53 | 0x54 => match r.u8().and_then(|n| r.take(usize::from(n))) {
338 Some(b) if id == 0x53 => {
339 out.text.push(String::from_utf8_lossy(b).into_owned());
340 true
341 }
342 Some(b) => {
343 out.raw.push(hex::encode(b));
344 true
345 }
346 None => false,
347 },
348 0xf0 => r.u16_le().map(|v| out.device_type = Some(v)).is_some(),
349 0xf1 => r
350 .array::<4>()
351 .map(|v| out.firmware = Some(format!("{}.{}.{}.{}", v[3], v[2], v[1], v[0])))
352 .is_some(),
353 0xf2 => r
354 .array::<3>()
355 .map(|v| out.firmware = Some(format!("{}.{}.{}", v[2], v[1], v[0])))
356 .is_some(),
357 _ => {
358 let Ok(i) = OBJECTS.binary_search_by_key(&id, |o| o.0) else {
359 out.unknown_object = Some(id);
360 return;
361 };
362 let (_, name, kind, factor, unit) = OBJECTS[i];
363 let raw = match kind {
364 Kind::Unsigned(n) => r.uint_le(usize::from(n)).map(f64::from),
365 Kind::Signed(n) => r.sint_le(usize::from(n)).map(f64::from),
366 };
367 match raw {
368 Some(v) => {
369 out.measurements.push(Measurement {
370 object_id: id,
371 name,
372 value: round(v * factor, factor),
373 unit,
374 });
375 true
376 }
377 None => false,
378 }
379 }
380 };
381 if !ok {
382 out.truncated = true;
383 return;
384 }
385 }
386}
387
388fn round(v: f64, factor: f64) -> f64 {
390 let digits = (-factor.log10()).ceil().max(0.0) as i32 + 1;
391 let p = 10f64.powi(digits);
392 (v * p).round() / p
393}
394
395impl BtHome {
396 pub(crate) fn readings(&self) -> Vec<Reading> {
397 let mut seen: Vec<(&str, u32)> = Vec::new();
398 let mut v = Vec::new();
399 for m in &self.measurements {
400 let n = match seen.iter_mut().find(|(k, _)| *k == m.name) {
401 Some((_, c)) => {
402 *c += 1;
403 *c
404 }
405 None => {
406 seen.push((m.name, 1));
407 1
408 }
409 };
410 let key = if n == 1 {
411 m.name.to_string()
412 } else {
413 format!("{}_{n}", m.name)
414 };
415 v.push(Reading::new(key, m.value, m.unit));
416 }
417 v
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 #[test]
426 fn plain_frame() {
427 let data = hex::decode("40 00 0f 02ca09 03bf13 015d 1a01 3a01".replace(' ', "")).unwrap();
429 let b = decode(&data, &Context::default()).unwrap();
430 assert!(!b.encrypted);
431 assert_eq!(b.packet_id, Some(15));
432 let names: Vec<_> = b.measurements.iter().map(|m| (m.name, m.value)).collect();
433 assert_eq!(
434 names,
435 vec![
436 ("temperature", 25.06),
437 ("humidity", 50.55),
438 ("battery", 93.0),
439 ("door", 1.0)
440 ]
441 );
442 assert_eq!(b.events[0].event, "press");
443 assert!(b.unknown_object.is_none());
444 }
445
446 #[test]
447 fn stops_at_unknown_and_truncated() {
448 let b = decode(&[0x40, 0x02, 0x01, 0xee, 0x01], &Context::default()).unwrap();
449 assert!(b.truncated || b.unknown_object.is_some());
450 let b = decode(&[0x40, 0x01, 0x10, 0xee, 0x01], &Context::default()).unwrap();
451 assert_eq!(b.unknown_object, Some(0xee));
452 assert_eq!(b.measurements.len(), 1);
453 assert!(decode(&[0x20], &Context::default()).is_none());
454 assert!(decode(&[], &Context::default()).is_none());
455 }
456
457 #[test]
458 fn encrypted_round_trip() {
459 let addr: AddressBytes = [0xa5, 0x80, 0x8f, 0xe6, 0x48, 0x54];
460 let key = [0x23u8; 16];
461 let data = encrypt(
462 &addr,
463 &key,
464 0x40,
465 0x0011_2233,
466 &hex::decode("02ca0903bf13").unwrap(),
467 );
468 let mut ctx = Context::for_address(addr);
469 let locked = decode(&data, &ctx).unwrap();
470 assert!(locked.encrypted && locked.undecryptable);
471 ctx.bthome_keys.insert(addr, key);
472 let b = decode(&data, &ctx).unwrap();
473 assert!(!b.undecryptable);
474 assert_eq!(b.counter, Some(0x0011_2233));
475 assert_eq!(b.measurements[0].value, 25.06);
476 ctx.bthome_keys.insert(addr, [0x24; 16]);
477 assert!(decode(&data, &ctx).unwrap().undecryptable);
478 }
479
480 #[test]
481 fn objects_are_sorted() {
482 assert!(OBJECTS.windows(2).all(|w| w[0].0 < w[1].0));
483 }
484}