Skip to content

Commit

Permalink
WIP on events.
Browse files Browse the repository at this point in the history
  • Loading branch information
qwandor committed Jul 20, 2023
1 parent 5fd44c2 commit d9d226c
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 4 deletions.
39 changes: 35 additions & 4 deletions btsensor/src/bthome.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
//! Support for the [BTHome](https://bthome.io/) v1 format.

mod events;

use self::events::{ButtonEventType, DimmerEventType, Event};
use bluez_async::uuid_from_u16;
use num_enum::IntoPrimitive;
use std::fmt::{self, Display, Formatter};
Expand All @@ -21,6 +24,8 @@ pub enum DecodeError {
ExtraData(Vec<u8>),
#[error("Unsupported format {0:?}")]
UnsupportedFormat(DataType),
#[error("Invalid event type {0:#04x}")]
InvalidEventType(u8),
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand All @@ -44,6 +49,13 @@ impl Element {
}
}

pub fn new_event(event: Event) -> Self {
Self {
property: event.property(),
value,
}
}

pub fn float_value(&self) -> f64 {
f64::from(&self.value) / 10.0f64.powi(self.property.decimal_point())
}
Expand All @@ -55,6 +67,27 @@ impl Element {
None
}
}

fn decode(length: u8, format: DataType, data: &[u8]) -> Result<Self, DecodeError> {
let property = Property::try_from(data[0])?;
let value = &data[1..];
match property {
Property::ButtonEvent => {
let event_type = ButtonEventType::from_bytes(value)?;
let event = Event::Button(event_type);
Ok(Element {})
}
Property::DimmerEvent => {
let event_type = DimmerEventType::from_bytes(value)?;
let event = Event::Dimmer(event_type);
Ok(Element {})
}
_ => {
let value = Value::from_bytes(value, format)?;
Ok(Element { property, value })
}
}
}
}

impl Display for Element {
Expand Down Expand Up @@ -463,15 +496,13 @@ pub fn decode(mut data: &[u8]) -> Result<Vec<Element>, DecodeError> {
while data.len() > 2 {
let length_format = data[0];
let length = length_format & 0x1f;
let element_end = usize::from(length) + 1;
// length includes the measurement type byte but not the length/format byte.
if data.len() <= length.into() {
return Err(DecodeError::PrematureEnd);
}
let format = ((length_format & 0xe0) >> 5).try_into()?;
let property = data[1].try_into()?;
let element_end = usize::from(length) + 1;
let value = Value::from_bytes(&data[2..element_end], format)?;
elements.push(Element { property, value });
elements.push(Element::decode(length, format, &data[1..element_end])?);

data = &data[element_end..];
}
Expand Down
91 changes: 91 additions & 0 deletions btsensor/src/bthome/events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use super::{DecodeError, Property};
use num_enum::IntoPrimitive;
use std::fmt::{self, Display, Formatter};

#[derive(Copy, Clone, Debug, Eq, IntoPrimitive, PartialEq)]
#[repr(u8)]
pub enum ButtonEventType {
Press = 0x01,
DoublePress = 0x02,
TriplePress = 0x03,
LongPress = 0x04,
LongDoublePress = 0x05,
LongTriplePress = 0x06,
}

impl ButtonEventType {
pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Option<Self>, DecodeError> {
match bytes {
[0x00] => Ok(None),
[0x01] => Ok(Some(Self::Press)),
[0x02] => Ok(Some(Self::DoublePress)),
[0x03] => Ok(Some(Self::TriplePress)),
[0x04] => Ok(Some(Self::LongPress)),
[0x05] => Ok(Some(Self::LongDoublePress)),
[0x06] => Ok(Some(Self::LongTriplePress)),
[value] => Err(DecodeError::InvalidEventType(*value)),
[] => Err(DecodeError::PrematureEnd),
_ => Err(DecodeError::ExtraData(bytes.to_owned())),
}
}

pub fn as_str(&self) -> &'static str {
match self {
Self::Press => "press",
Self::DoublePress => "double press",
Self::TriplePress => "triple press",
Self::LongPress => "long press",
Self::LongDoublePress => "long double press",
Self::LongTriplePress => "long triple press",
}
}
}

impl Display for ButtonEventType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.as_str())
}
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DimmerEventType {
RotateLeft(u8),
RotateRight(u8),
}

impl DimmerEventType {
pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Option<Self>, DecodeError> {
match bytes {
[0x00] => Ok(None),
[0x01, steps] => Ok(Some(Self::RotateLeft(*steps))),
[0x02, steps] => Ok(Some(Self::RotateRight(*steps))),
[value] => Err(DecodeError::InvalidEventType(*value)),
[] => Err(DecodeError::PrematureEnd),
_ => Err(DecodeError::ExtraData(bytes.to_owned())),
}
}
}

impl Display for DimmerEventType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::RotateLeft(steps) => write!(f, "rotate left {} steps", steps),
Self::RotateRight(steps) => write!(f, "rotate right {} steps", steps),
}
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Event {
Button(Option<ButtonEventType>),
Dimmer(Option<DimmerEventType>),
}

impl Event {
pub fn property(&self) -> Property {
match self {
Self::Button(_) => Property::ButtonEvent,
Self::Dimmer(_) => Property::DimmerEvent,
}
}
}

0 comments on commit d9d226c

Please sign in to comment.