Skip to main content

bluetooth_adv/beacon/
kkm.rs

1//! KKM KBeacon frames, as KKM's own MIT-licensed SDK reads them
2//! (<https://github.com/kkmhogen/android_kbeaconlib2>, `KBAdvPackage`).
3//!
4//! | Frame | Carried in | First byte |
5//! |---|---|---|
6//! | Sensor v1: a 16-bit mask, then the readings it names | Eddystone service data (0xFEAA) | 0x21 |
7//! | Sensor v1, encrypted | manufacturer data 0x0A53 | 0x06 |
8//! | Sensor v2: a model byte, battery, then length-type-value records | manufacturer data 0x0A53 | 0x24 |
9//! | Sensor v2, encrypted | manufacturer data 0x0A53 | 0x07 |
10//! | System: model, battery %, MAC, firmware | Eddystone service data | 0x22 |
11//!
12//! Encrypted frames carry 16 bytes of AES-128-ECB ciphertext and a 4-byte
13//! UTC second count; the key is MD5(password padded to 16 bytes || MAC as
14//! printed || UTC seconds).
15
16use super::{Context, Reading};
17use crate::reader::Reader;
18use crate::AddressBytes;
19
20use aes::cipher::{BlockCipherDecrypt, KeyInit};
21use aes::Aes128;
22use md5::{Digest, Md5};
23
24#[cfg(feature = "serde")]
25use serde::Serialize;
26
27/// KKM's company identifier.
28pub const COMPANY_ID: u16 = 0x0a53;
29
30/// A KKM frame.
31#[derive(Debug, Clone, PartialEq, Default)]
32#[cfg_attr(feature = "serde", derive(Serialize))]
33pub struct Kkm {
34    /// `sensor` or `system`.
35    pub frame: &'static str,
36    /// Encrypted on the air.
37    pub encrypted: bool,
38    /// Encrypted, and no password (or no address) to decrypt it with. When
39    /// the password is wrong the readings are garbage: KKM's format has no
40    /// integrity check.
41    pub undecryptable: bool,
42    /// Device model (v2 sensor and system frames).
43    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
44    pub model: Option<u8>,
45    /// Battery voltage, mV (sensor frames).
46    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
47    pub battery_mv: Option<u16>,
48    /// Battery, percent (system frames).
49    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
50    pub battery_percent: Option<u8>,
51    /// Temperature, °C.
52    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
53    pub temperature: Option<f64>,
54    /// Relative humidity, %.
55    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
56    pub humidity: Option<f64>,
57    /// Three-axis reading (accelerometer in mg, or magnetometer on the S7S).
58    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
59    pub axis: Option<[i16; 3]>,
60    /// Alarm byte. Its bits are model specific; on the S7S parking sensor
61    /// bits 0-1 are park status and bits 4-5 radar status.
62    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
63    pub alarm: Option<u8>,
64    /// PIR indication.
65    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
66    pub pir: Option<u8>,
67    /// Illuminance, lux.
68    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
69    pub lux: Option<u16>,
70    /// VOC index, and seconds since it was measured.
71    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
72    pub voc: Option<(u16, u32)>,
73    /// NOx index.
74    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
75    pub nox: Option<u16>,
76    /// CO2, ppm, and seconds since it was measured.
77    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
78    pub co2: Option<(u16, u32)>,
79    /// New history records: record type and count.
80    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
81    pub new_records: Option<(u8, u16)>,
82    /// UTC seconds sent with an encrypted frame.
83    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
84    pub utc: Option<u32>,
85    /// The beacon's own MAC address, as printed (system frames).
86    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
87    pub mac: Option<String>,
88    /// Firmware version (system frames).
89    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
90    pub firmware: Option<String>,
91}
92
93const MASK_VOLTAGE: u16 = 0x0001;
94const MASK_TEMP: u16 = 0x0002;
95const MASK_HUMIDITY: u16 = 0x0004;
96const MASK_AXIS: u16 = 0x0008;
97const MASK_ALARM: u16 = 0x0010;
98const MASK_PIR: u16 = 0x0020;
99const MASK_LUX: u16 = 0x0040;
100const MASK_VOC: u16 = 0x0080;
101const MASK_CO2: u16 = 0x0200;
102const MASK_RECORDS: u16 = 0x0400;
103
104/// Decodes a frame in Eddystone service data (types 0x21 and 0x22).
105pub fn decode_service_data(data: &[u8], _ctx: &Context) -> Option<Kkm> {
106    let mut r = Reader::new(data);
107    match r.u8()? {
108        0x21 => {
109            let mask = r.u16_be()?;
110            Some(sensor_v1(mask, r.rest()))
111        }
112        0x22 => {
113            let _tag = r.u8()?;
114            let model = r.u8()?;
115            let battery = r.u8()?;
116            let mac: [u8; 6] = r.array()?;
117            let fw: [u8; 2] = r.array()?;
118            Some(Kkm {
119                frame: "system",
120                model: Some(model),
121                battery_percent: Some(battery.min(100)),
122                mac: Some(
123                    mac.iter()
124                        .map(|b| format!("{b:02X}"))
125                        .collect::<Vec<_>>()
126                        .join(":"),
127                ),
128                firmware: Some(format!("{}.{}", fw[0], fw[1])),
129                ..Kkm::default()
130            })
131        }
132        _ => None,
133    }
134}
135
136/// Decodes a frame in KKM's manufacturer data (types 0x06, 0x07 and 0x24).
137/// Encrypted frames are decrypted when `ctx` has the advertiser's address
138/// and a password for it.
139pub fn decode_manufacturer(company_id: u16, data: &[u8], ctx: &Context) -> Option<Kkm> {
140    if company_id != COMPANY_ID || data.len() < 3 {
141        return None;
142    }
143    match data[0] {
144        kind @ (0x06 | 0x07) => {
145            // type, mask (2) or model (1), ciphertext (16), UTC (4)
146            let header = if kind == 0x06 { 3 } else { 2 };
147            let utc: [u8; 4] = data.get(header + 16..header + 20)?.try_into().ok()?;
148            let password = ctx
149                .address
150                .and_then(|a| ctx.kkm_passwords.get(&a).map(|p| (a, p)));
151            match password {
152                Some((addr, p)) => decode_with_password(data, &addr, p),
153                None => Some(Kkm {
154                    frame: "sensor",
155                    encrypted: true,
156                    undecryptable: true,
157                    model: (kind == 0x07).then_some(data[1]),
158                    utc: Some(u32::from_be_bytes(utc)),
159                    ..Kkm::default()
160                }),
161            }
162        }
163        0x24 => {
164            let mut k = sensor_v2(&data[2..]);
165            k.model = Some(data[1]);
166            Some(k)
167        }
168        _ => None,
169    }
170}
171
172fn decode_with_password(data: &[u8], addr: &AddressBytes, password: &str) -> Option<Kkm> {
173    let mut r = Reader::new(data);
174    let kind = r.u8()?;
175    let (mask, model) = match kind {
176        0x06 => (Some(r.u16_be()?), None),
177        0x07 => (None, Some(r.u8()?)),
178        _ => return None,
179    };
180    let ct: [u8; 16] = r.array()?;
181    let utc_bytes: [u8; 4] = r.array()?;
182    let mut key_material = [0u8; 26];
183    let pwd = password.as_bytes();
184    let n = pwd.len().min(16);
185    key_material[..n].copy_from_slice(&pwd[..n]);
186    for (i, b) in addr.iter().rev().enumerate() {
187        key_material[16 + i] = *b;
188    }
189    key_material[22..].copy_from_slice(&utc_bytes);
190    let key: [u8; 16] = Md5::digest(key_material).into();
191    let mut block = aes::Block::from(ct);
192    Aes128::new(&key.into()).decrypt_block(&mut block);
193    let plain: [u8; 16] = block.into();
194    let mut k = match mask {
195        Some(mask) => sensor_v1(mask, &plain),
196        None => sensor_v2(&plain),
197    };
198    k.encrypted = true;
199    k.model = model;
200    k.utc = Some(u32::from_be_bytes(utc_bytes));
201    Some(k)
202}
203
204fn sensor_v1(mask: u16, data: &[u8]) -> Kkm {
205    let mut k = Kkm {
206        frame: "sensor",
207        ..Kkm::default()
208    };
209    let mut r = Reader::new(data);
210    // Fields appear in mask order; stop at the first one that does not fit,
211    // keeping those before it.
212    let _ = (|| -> Option<()> {
213        if mask & MASK_VOLTAGE != 0 {
214            k.battery_mv = Some(r.u16_be()?);
215        }
216        if mask & MASK_TEMP != 0 {
217            k.temperature = Some(fixed_8_8(r.i16_be()?));
218        }
219        if mask & MASK_HUMIDITY != 0 {
220            let h = r.array::<2>()?;
221            if (h[0] as i8) >= 0 {
222                k.humidity = Some(fixed_8_8(i16::from_be_bytes(h)));
223            } else if (h[0] as i8) < -2 {
224                // A wide-range thermometer: the high byte extends the temperature.
225                if let Some(t) = k.temperature {
226                    k.temperature = Some(f64::from(-20 - i32::from(h[0] as i8)) * 100.0 + t);
227                }
228            }
229        }
230        if mask & MASK_AXIS != 0 {
231            k.axis = Some([r.i16_be()?, r.i16_be()?, r.i16_be()?]);
232        }
233        if mask & MASK_ALARM != 0 {
234            k.alarm = Some(r.u8()?);
235        }
236        if mask & MASK_PIR != 0 {
237            k.pir = Some(r.u8()?);
238        }
239        if mask & MASK_LUX != 0 {
240            k.lux = Some(r.u16_be()?);
241        }
242        if mask & MASK_VOC != 0 {
243            let elapsed = u32::from(r.u8()?) * 10;
244            k.voc = Some((r.u16_be()?, elapsed));
245            k.nox = Some(r.u16_be()?);
246        }
247        if mask & MASK_CO2 != 0 {
248            let elapsed = u32::from(r.u8()?) * 10;
249            k.co2 = Some((r.u16_be()?, elapsed));
250        }
251        if mask & MASK_RECORDS != 0 {
252            k.new_records = Some((r.u8()?, r.u16_be()?));
253        }
254        Some(())
255    })();
256    k
257}
258
259fn sensor_v2(data: &[u8]) -> Kkm {
260    let mut k = Kkm {
261        frame: "sensor",
262        ..Kkm::default()
263    };
264    let mut r = Reader::new(data);
265    let Some(b) = r.u16_be() else { return k };
266    k.battery_mv = Some(b);
267    let Some(_t0) = r.u8() else { return k };
268    while r.remaining() >= 2 {
269        let (Some(len), Some(kind)) = (r.u8(), r.u8()) else {
270            break;
271        };
272        let Some(v) = r.take(usize::from(len.saturating_sub(1))) else {
273            break;
274        };
275        let mut f = Reader::new(v);
276        match kind {
277            0x02 => k.temperature = f.i16_be().map(|t| f64::from(t) / 10.0),
278            0x03 => {
279                k.temperature = f.i16_be().map(|t| f64::from(t) / 10.0);
280                k.humidity = f.i8().map(f64::from);
281            }
282            0x04 => {
283                if let (Some(x), Some(y), Some(z)) = (f.i16_be(), f.i16_be(), f.i16_be()) {
284                    k.axis = Some([x, y, z]);
285                }
286            }
287            0x05 => k.alarm = f.u8(),
288            0x06 => k.pir = f.u8(),
289            0x07 => k.lux = f.u16_be(),
290            0x08 => {
291                if let (Some(e), Some(voc), Some(nox)) = (f.u8(), f.u16_be(), f.u16_be()) {
292                    k.voc = Some((voc, u32::from(e) * 10));
293                    k.nox = Some(nox);
294                }
295            }
296            0x09 => {
297                if let (Some(e), Some(co2)) = (f.u8(), f.u16_be()) {
298                    k.co2 = Some((co2, u32::from(e) * 10));
299                }
300            }
301            0x0a => {
302                if let (Some(t), Some(n)) = (f.u8(), f.u16_be()) {
303                    k.new_records = Some((t, n));
304                }
305            }
306            _ => {}
307        }
308    }
309    k
310}
311
312fn fixed_8_8(v: i16) -> f64 {
313    (f64::from(v) / 256.0 * 100.0).round() / 100.0
314}
315
316impl Kkm {
317    pub(crate) fn readings(&self) -> Vec<Reading> {
318        let mut v = Vec::new();
319        if let Some(b) = self.battery_mv {
320            v.push(Reading::new("voltage", f64::from(b) / 1000.0, "V"));
321        }
322        if let Some(b) = self.battery_percent {
323            v.push(Reading::new("battery", f64::from(b), "%"));
324        }
325        if let Some(t) = self.temperature {
326            v.push(Reading::new("temperature", t, "°C"));
327        }
328        if let Some(h) = self.humidity {
329            v.push(Reading::new("humidity", h, "%"));
330        }
331        if let Some([x, y, z]) = self.axis {
332            v.push(Reading::new("x", f64::from(x), ""));
333            v.push(Reading::new("y", f64::from(y), ""));
334            v.push(Reading::new("z", f64::from(z), ""));
335        }
336        if let Some(a) = self.alarm {
337            v.push(Reading::new("alarm", f64::from(a), ""));
338        }
339        if let Some(p) = self.pir {
340            v.push(Reading::new("pir", f64::from(p), ""));
341        }
342        if let Some(l) = self.lux {
343            v.push(Reading::new("illuminance", f64::from(l), "lx"));
344        }
345        if let Some((voc, _)) = self.voc {
346            v.push(Reading::new("voc_index", f64::from(voc), ""));
347        }
348        if let Some(n) = self.nox {
349            v.push(Reading::new("nox_index", f64::from(n), ""));
350        }
351        if let Some((c, _)) = self.co2 {
352            v.push(Reading::new("co2", f64::from(c), "ppm"));
353        }
354        v
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn s7s_sensor_frame() {
364        // Mask: voltage, temperature, axis, alarm. 3000 mV, 25.5 °C, (-1, 2, 3), occupied.
365        let data = hex::decode("21 001b 0bb8 1980 ffff00020003 01".replace(' ', "")).unwrap();
366        let k = decode_service_data(&data, &Context::default()).unwrap();
367        assert_eq!(k.battery_mv, Some(3000));
368        assert_eq!(k.temperature, Some(25.5));
369        assert_eq!(k.axis, Some([-1, 2, 3]));
370        assert_eq!(k.alarm, Some(1));
371        // Truncated: what fits is kept.
372        let k = decode_service_data(&data[..7], &Context::default()).unwrap();
373        assert_eq!(k.temperature, Some(25.5));
374        assert_eq!(k.axis, None);
375    }
376
377    #[test]
378    fn system_frame() {
379        let data = hex::decode("22 00 07 64 bc5729000001 0638".replace(' ', "")).unwrap();
380        let k = decode_service_data(&data, &Context::default()).unwrap();
381        assert_eq!(k.frame, "system");
382        assert_eq!(k.mac.as_deref(), Some("BC:57:29:00:00:01"));
383        assert_eq!(k.firmware.as_deref(), Some("6.56"));
384        assert_eq!(k.battery_percent, Some(100));
385    }
386
387    #[test]
388    fn v2_records() {
389        // model 5, 3100 mV, t0, temp+humidity 21.5 °C 40 %, lux 300.
390        let data = hex::decode("24 05 0c1c 00 04 03 00d7 28 03 07 012c".replace(' ', "")).unwrap();
391        let k = decode_manufacturer(COMPANY_ID, &data, &Context::default()).unwrap();
392        assert_eq!(k.model, Some(5));
393        assert_eq!(k.battery_mv, Some(3100));
394        assert_eq!(k.temperature, Some(21.5));
395        assert_eq!(k.humidity, Some(40.0));
396        assert_eq!(k.lux, Some(300));
397    }
398
399    #[test]
400    fn encrypted_v1_decrypts_with_password() {
401        use aes::cipher::BlockCipherEncrypt;
402        let addr: AddressBytes = [0x01, 0x00, 0x00, 0x29, 0x57, 0xbc];
403        let utc = 1_700_000_000u32.to_be_bytes();
404        let mut km = [0u8; 26];
405        km[..4].copy_from_slice(b"1234");
406        km[16..22].copy_from_slice(&[0xbc, 0x57, 0x29, 0x00, 0x00, 0x01]);
407        km[22..].copy_from_slice(&utc);
408        let key: [u8; 16] = Md5::digest(km).into();
409        let mut plain = [0u8; 16];
410        plain[..4].copy_from_slice(&[0x0b, 0xb8, 0x19, 0x80]);
411        let mut block = aes::Block::from(plain);
412        Aes128::new(&key.into()).encrypt_block(&mut block);
413        let mut data = vec![0x06, 0x00, 0x03];
414        data.extend_from_slice(&<[u8; 16]>::from(block));
415        data.extend_from_slice(&utc);
416
417        let mut ctx = Context::for_address(addr);
418        let locked = decode_manufacturer(COMPANY_ID, &data, &ctx).unwrap();
419        assert!(locked.encrypted && locked.undecryptable);
420        ctx.kkm_passwords.insert(addr, "1234".into());
421        let k = decode_manufacturer(COMPANY_ID, &data, &ctx).unwrap();
422        assert!(!k.undecryptable);
423        assert_eq!(k.battery_mv, Some(3000));
424        assert_eq!(k.temperature, Some(25.5));
425    }
426}