pub mod altbeacon;
pub mod bthome;
pub mod eddystone;
pub mod ibeacon;
pub mod kkm;
pub mod ruuvi;
use std::collections::HashMap;
use crate::{AddressBytes, Advertisement};
#[cfg(feature = "serde")]
use serde::Serialize;
#[derive(Debug, Clone, Default)]
pub struct Context {
pub address: Option<AddressBytes>,
pub bthome_keys: HashMap<AddressBytes, [u8; 16]>,
pub kkm_passwords: HashMap<AddressBytes, String>,
}
impl Context {
pub fn for_address(address: AddressBytes) -> Self {
Context {
address: Some(address),
..Context::default()
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize),
serde(tag = "format", rename_all = "snake_case")
)]
#[non_exhaustive]
pub enum Beacon {
IBeacon(ibeacon::IBeacon),
AltBeacon(altbeacon::AltBeacon),
Eddystone(eddystone::Eddystone),
BtHome(bthome::BtHome),
Kkm(kkm::Kkm),
Ruuvi(ruuvi::Ruuvi),
}
impl Beacon {
pub fn format(&self) -> &'static str {
match self {
Beacon::IBeacon(_) => "i_beacon",
Beacon::AltBeacon(_) => "alt_beacon",
Beacon::Eddystone(_) => "eddystone",
Beacon::BtHome(_) => "bt_home",
Beacon::Kkm(_) => "kkm",
Beacon::Ruuvi(_) => "ruuvi",
}
}
pub fn readings(&self) -> Vec<Reading> {
match self {
Beacon::BtHome(b) => b.readings(),
Beacon::Kkm(k) => k.readings(),
Beacon::Ruuvi(r) => r.readings(),
Beacon::Eddystone(e) => e.readings(),
Beacon::IBeacon(_) | Beacon::AltBeacon(_) => Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Reading {
pub key: String,
pub value: f64,
pub unit: &'static str,
}
impl Reading {
pub(crate) fn new(key: impl Into<String>, value: f64, unit: &'static str) -> Self {
Reading {
key: key.into(),
value,
unit,
}
}
}
pub fn decode(adv: &Advertisement, ctx: &Context) -> Vec<Beacon> {
let mut out = Vec::new();
for m in &adv.manufacturer_data {
if let Some(b) = ibeacon::decode(m.company_id, &m.data) {
out.push(Beacon::IBeacon(b));
}
if let Some(b) = altbeacon::decode(m.company_id, &m.data) {
out.push(Beacon::AltBeacon(b));
}
if let Some(b) = kkm::decode_manufacturer(m.company_id, &m.data, ctx) {
out.push(Beacon::Kkm(b));
}
if let Some(b) = ruuvi::decode(m.company_id, &m.data) {
out.push(Beacon::Ruuvi(b));
}
}
for s in &adv.service_data {
match s.uuid.as_u16() {
Some(eddystone::SERVICE_UUID) => {
if let Some(e) = eddystone::decode(&s.data) {
out.push(Beacon::Eddystone(e));
} else if let Some(k) = kkm::decode_service_data(&s.data, ctx) {
out.push(Beacon::Kkm(k));
}
}
Some(bthome::SERVICE_UUID) => {
if let Some(b) = bthome::decode(&s.data, ctx) {
out.push(Beacon::BtHome(b));
}
}
_ => {}
}
}
out
}