Skip to content

Commit

Permalink
starting to improve parsing further
Browse files Browse the repository at this point in the history
  • Loading branch information
maebli committed Jun 9, 2024
1 parent a9813e7 commit c3857fc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
12 changes: 12 additions & 0 deletions examples/example_full_parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use m_bus_parser::MbusData;
fn main() {
let example = vec![
0x68, 0x3C, 0x3C, 0x68, 0x08, 0x08, 0x72, 0x78, 0x03, 0x49, 0x11, 0x77, 0x04, 0x0E, 0x16,
0x0A, 0x00, 0x00, 0x00, 0x0C, 0x78, 0x78, 0x03, 0x49, 0x11, 0x04, 0x13, 0x31, 0xD4, 0x00,
0x00, 0x42, 0x6C, 0x00, 0x00, 0x44, 0x13, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6D, 0x0B, 0x0B,
0xCD, 0x13, 0x02, 0x27, 0x00, 0x00, 0x09, 0xFD, 0x0E, 0x02, 0x09, 0xFD, 0x0F, 0x06, 0x0F,
0x00, 0x01, 0x75, 0x13, 0xD3, 0x16,
];
let mbus_data = MbusData::try_from(example.as_slice()).unwrap();
println!("{:?}", mbus_data);
}
52 changes: 52 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,24 @@
//! 0x1F, 0xB3, 0x16,
//! ];
//!
//! // Parse the frame
//! let frame = Frame::try_from(example.as_slice()).unwrap();
//!
//! if let Frame::LongFrame { function, address, data :_} = frame {
//! assert_eq!(function, Function::RspUd{acd: false, dfc:false});
//! assert_eq!(address, Address::Primary(1));
//! }
//!
//! // Alternatively, parse the frame and user data in one go
//! let mbus_data = m_bus_parser::MbusData::try_from(example.as_slice()).unwrap();
//!
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

use frames::FrameError;
use user_data::ApplicationLayerError;

#[cfg(feature = "std")]
extern crate std;

Expand All @@ -48,3 +56,47 @@ extern crate core;

pub mod frames;
pub mod user_data;

#[derive(Debug)]
pub struct MbusData<'a> {
pub frame: frames::Frame<'a>,
pub user_data: Option<user_data::UserDataBlock<'a>>,
}

#[derive(Debug)]
pub enum MbusError {
FrameError(FrameError),
ApplicationLayerError(ApplicationLayerError),
}

impl From<FrameError> for MbusError {
fn from(error: FrameError) -> MbusError {
MbusError::FrameError(error)
}
}

impl From<ApplicationLayerError> for MbusError {
fn from(error: ApplicationLayerError) -> MbusError {
match error {
_ => MbusError::ApplicationLayerError(error),
}
}
}

impl<'a> TryFrom<&'a [u8]> for MbusData<'a> {
type Error = MbusError;

fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
let frame = frames::Frame::try_from(data)?;

let user_data = match &frame {
frames::Frame::LongFrame { data, .. } => {
Some(user_data::UserDataBlock::try_from(*data)?)
}
frames::Frame::SingleCharacter { .. } => None,
frames::Frame::ShortFrame { .. } | frames::Frame::ControlFrame { .. } => None,
};

Ok(MbusData { frame, user_data })
}
}

0 comments on commit c3857fc

Please sign in to comment.