Skip to main content

bluetooth_adv/beacon/
mod.rs

1//! Beacon and sensor formats found inside advertisements.
2//!
3//! | Format | Carried in | Module |
4//! |---|---|---|
5//! | iBeacon | Apple manufacturer data, type 0x02 | [`ibeacon`] |
6//! | AltBeacon | any company's manufacturer data, code 0xBEAC | [`altbeacon`] |
7//! | Eddystone UID, URL, TLM (plain and encrypted), EID | service data 0xFEAA | [`eddystone`] |
8//! | BTHome v2, plain and encrypted | service data 0xFCD2 | [`bthome`] |
9//! | KKM KBeacon sensor (v1, v2, encrypted) and system frames | service data 0xFEAA, manufacturer data 0x0A53 | [`kkm`] |
10//! | Ruuvi RAWv1, RAWv2 (5), 6, E1 | manufacturer data 0x0499 | [`ruuvi`], decoded by the `ruuvi-sensor-protocol` crate |
11//!
12//! [`decode`] tries every format and returns all that match: one
13//! advertisement can carry an iBeacon and an Eddystone TLM, say.
14
15pub mod altbeacon;
16pub mod bthome;
17pub mod eddystone;
18pub mod ibeacon;
19pub mod kkm;
20pub mod ruuvi;
21
22use std::collections::HashMap;
23
24use crate::{AddressBytes, Advertisement};
25
26#[cfg(feature = "serde")]
27use serde::Serialize;
28
29/// What a decoder may need beyond the advertisement itself.
30#[derive(Debug, Clone, Default)]
31pub struct Context {
32    /// The advertiser's address (least significant byte first): BTHome's
33    /// nonce and KKM's key derivation include it. Without it encrypted
34    /// frames are reported as encrypted but not decrypted.
35    pub address: Option<AddressBytes>,
36    /// BTHome bind keys by device address.
37    pub bthome_keys: HashMap<AddressBytes, [u8; 16]>,
38    /// KKM beacon passwords by device address (encrypted sensor frames).
39    pub kkm_passwords: HashMap<AddressBytes, String>,
40}
41
42impl Context {
43    /// A context for one advertiser, with no keys.
44    pub fn for_address(address: AddressBytes) -> Self {
45        Context {
46            address: Some(address),
47            ..Context::default()
48        }
49    }
50}
51
52/// A decoded beacon or sensor frame.
53#[derive(Debug, Clone, PartialEq)]
54#[cfg_attr(
55    feature = "serde",
56    derive(Serialize),
57    serde(tag = "format", rename_all = "snake_case")
58)]
59#[non_exhaustive]
60pub enum Beacon {
61    /// Apple iBeacon.
62    IBeacon(ibeacon::IBeacon),
63    /// AltBeacon.
64    AltBeacon(altbeacon::AltBeacon),
65    /// Eddystone.
66    Eddystone(eddystone::Eddystone),
67    /// BTHome v2.
68    BtHome(bthome::BtHome),
69    /// KKM KBeacon.
70    Kkm(kkm::Kkm),
71    /// Ruuvi.
72    Ruuvi(ruuvi::Ruuvi),
73}
74
75impl Beacon {
76    /// The format's name, as used in the JSON `format` field.
77    pub fn format(&self) -> &'static str {
78        match self {
79            Beacon::IBeacon(_) => "i_beacon",
80            Beacon::AltBeacon(_) => "alt_beacon",
81            Beacon::Eddystone(_) => "eddystone",
82            Beacon::BtHome(_) => "bt_home",
83            Beacon::Kkm(_) => "kkm",
84            Beacon::Ruuvi(_) => "ruuvi",
85        }
86    }
87
88    /// The measurements this frame carries, as (name, value, unit), for
89    /// publishing sensors without knowing every format.
90    pub fn readings(&self) -> Vec<Reading> {
91        match self {
92            Beacon::BtHome(b) => b.readings(),
93            Beacon::Kkm(k) => k.readings(),
94            Beacon::Ruuvi(r) => r.readings(),
95            Beacon::Eddystone(e) => e.readings(),
96            Beacon::IBeacon(_) | Beacon::AltBeacon(_) => Vec::new(),
97        }
98    }
99}
100
101/// One measurement from a sensor frame.
102#[derive(Debug, Clone, PartialEq)]
103#[cfg_attr(feature = "serde", derive(Serialize))]
104pub struct Reading {
105    /// A stable snake_case key, unique within the frame (`temperature`,
106    /// `button_2`, ...).
107    pub key: String,
108    /// The value.
109    pub value: f64,
110    /// The unit, as Home Assistant spells it (`°C`, `%`, `hPa`, ...), or empty.
111    pub unit: &'static str,
112}
113
114impl Reading {
115    pub(crate) fn new(key: impl Into<String>, value: f64, unit: &'static str) -> Self {
116        Reading {
117            key: key.into(),
118            value,
119            unit,
120        }
121    }
122}
123
124/// Every beacon format found in `adv`.
125pub fn decode(adv: &Advertisement, ctx: &Context) -> Vec<Beacon> {
126    let mut out = Vec::new();
127    for m in &adv.manufacturer_data {
128        if let Some(b) = ibeacon::decode(m.company_id, &m.data) {
129            out.push(Beacon::IBeacon(b));
130        }
131        if let Some(b) = altbeacon::decode(m.company_id, &m.data) {
132            out.push(Beacon::AltBeacon(b));
133        }
134        if let Some(b) = kkm::decode_manufacturer(m.company_id, &m.data, ctx) {
135            out.push(Beacon::Kkm(b));
136        }
137        if let Some(b) = ruuvi::decode(m.company_id, &m.data) {
138            out.push(Beacon::Ruuvi(b));
139        }
140    }
141    for s in &adv.service_data {
142        match s.uuid.as_u16() {
143            Some(eddystone::SERVICE_UUID) => {
144                if let Some(e) = eddystone::decode(&s.data) {
145                    out.push(Beacon::Eddystone(e));
146                } else if let Some(k) = kkm::decode_service_data(&s.data, ctx) {
147                    out.push(Beacon::Kkm(k));
148                }
149            }
150            Some(bthome::SERVICE_UUID) => {
151                if let Some(b) = bthome::decode(&s.data, ctx) {
152                    out.push(Beacon::BtHome(b));
153                }
154            }
155            _ => {}
156        }
157    }
158    out
159}