Skip to main content

bluetooth_adv/beacon/
ruuvi.rs

1//! Ruuvi sensors (manufacturer data 0x0499), decoded by the
2//! [`ruuvi_sensor_protocol`] crate, used as published; this module only
3//! maps its values to readings.
4
5use super::Reading;
6use ruuvi_sensor_protocol::{
7    Acceleration, BatteryPotential, CarbonDioxide, Humidity, Luminosity, MacAddress,
8    MeasurementSequenceNumber, MovementCounter, NitrogenOxides, ParticulateMatter, Pressure,
9    SensorValues, Temperature, TransmitterPower, VolatileOrganicCompounds,
10};
11
12#[cfg(feature = "serde")]
13use serde::Serialize;
14
15/// Ruuvi Innovations' company identifier.
16pub const COMPANY_ID: u16 = 0x0499;
17
18/// A Ruuvi frame's values, in SI-ish units.
19#[derive(Debug, Clone, PartialEq, Default)]
20#[cfg_attr(feature = "serde", derive(Serialize))]
21pub struct Ruuvi {
22    /// Temperature, °C.
23    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
24    pub temperature: Option<f64>,
25    /// Relative humidity, %.
26    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
27    pub humidity: Option<f64>,
28    /// Pressure, hPa.
29    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
30    pub pressure: Option<f64>,
31    /// Acceleration, mg, x y z.
32    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
33    pub acceleration: Option<[i16; 3]>,
34    /// Battery, V.
35    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
36    pub battery: Option<f64>,
37    /// TX power, dBm.
38    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
39    pub tx_power: Option<i8>,
40    /// Movement counter.
41    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
42    pub movement_counter: Option<u32>,
43    /// Measurement sequence number.
44    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
45    pub sequence: Option<u32>,
46    /// PM2.5, µg/m³.
47    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
48    pub pm2_5: Option<f64>,
49    /// CO2, ppm.
50    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
51    pub co2: Option<u16>,
52    /// VOC index.
53    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
54    pub voc_index: Option<u16>,
55    /// NOx index.
56    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
57    pub nox_index: Option<u16>,
58    /// Illuminance, lux.
59    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
60    pub illuminance: Option<f64>,
61    /// The MAC address the tag reports, as printed.
62    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
63    pub mac: Option<String>,
64}
65
66/// Decodes Ruuvi manufacturer data (after the company identifier).
67pub fn decode(company_id: u16, data: &[u8]) -> Option<Ruuvi> {
68    if company_id != COMPANY_ID {
69        return None;
70    }
71    let v = SensorValues::from_manufacturer_specific_data(company_id, data).ok()?;
72    Some(Ruuvi {
73        temperature: v
74            .temperature_as_millicelsius()
75            .map(|t| f64::from(t) / 1000.0),
76        humidity: v.humidity_as_ppm().map(|h| f64::from(h) / 10_000.0),
77        pressure: v.pressure_as_pascals().map(|p| f64::from(p) / 100.0),
78        acceleration: v.acceleration_vector_as_milli_g().map(|a| [a.0, a.1, a.2]),
79        battery: v
80            .battery_potential_as_millivolts()
81            .map(|b| f64::from(b) / 1000.0),
82        tx_power: v.tx_power_as_dbm(),
83        movement_counter: v.movement_counter(),
84        sequence: v.measurement_sequence_number(),
85        pm2_5: v
86            .pm2_5_as_nanograms_per_cubic_meter()
87            .map(|p| f64::from(p) / 1000.0),
88        co2: v.carbon_dioxide_as_ppm(),
89        voc_index: v.voc_index(),
90        nox_index: v.nox_index(),
91        illuminance: v.luminosity_as_millilux().map(|l| f64::from(l) / 1000.0),
92        mac: v.mac_address().map(|m| {
93            m.iter()
94                .map(|b| format!("{b:02X}"))
95                .collect::<Vec<_>>()
96                .join(":")
97        }),
98    })
99}
100
101impl Ruuvi {
102    pub(crate) fn readings(&self) -> Vec<Reading> {
103        let mut v = Vec::new();
104        let mut push = |k: &str, x: Option<f64>, u: &'static str| {
105            if let Some(x) = x {
106                v.push(Reading::new(k, x, u));
107            }
108        };
109        push("temperature", self.temperature, "°C");
110        push("humidity", self.humidity, "%");
111        push("pressure", self.pressure, "hPa");
112        push("voltage", self.battery, "V");
113        push("pm2_5", self.pm2_5, "µg/m³");
114        push("co2", self.co2.map(f64::from), "ppm");
115        push("voc_index", self.voc_index.map(f64::from), "");
116        push("nox_index", self.nox_index.map(f64::from), "");
117        push("illuminance", self.illuminance, "lx");
118        push("movement_counter", self.movement_counter.map(f64::from), "");
119        v
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn data_format_5() {
129        // Ruuvi's own test vector for data format 5 (RAWv2).
130        let data = hex::decode("0512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F").unwrap();
131        let r = decode(COMPANY_ID, &data).unwrap();
132        assert_eq!(r.temperature, Some(24.3));
133        assert_eq!(r.pressure, Some(1000.44));
134        assert_eq!(r.mac.as_deref(), Some("CB:B8:33:4C:88:4F"));
135        assert!(decode(COMPANY_ID, &[0x05]).is_none());
136    }
137}