diff --git a/src/main.rs b/src/main.rs index da6e571..0d9268e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -60,6 +60,12 @@ pub async fn apiserver() -> io::Result<()> { pub fn handle(buf: &Vec) { let mut rawdata = buf.to_vec(); - let msg = parse_inbound_msg(&mut rawdata); - println!("{}", msg); + match parse_inbound_msg(&mut rawdata) { + Ok(o) => { + println!("msg: {}", o); + } + Err(e) => { + println!("parse inbound message error: {}", e); + } + }; } diff --git a/src/parser/error.rs b/src/parser/error.rs new file mode 100644 index 0000000..59dd0cb --- /dev/null +++ b/src/parser/error.rs @@ -0,0 +1,27 @@ +pub struct MessageError; + +impl std::fmt::Debug for MessageError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "invalid protocol") + } +} + +impl std::fmt::Display for MessageError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "invalid protocol") + } +} + +pub struct NotOurProtocolError; + +impl std::fmt::Debug for NotOurProtocolError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "invalid protocol") + } +} + +impl std::fmt::Display for NotOurProtocolError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "invalid protocol") + } +} diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 4e19dc2..1914b6a 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,7 +1,8 @@ mod body; +mod error; use body::*; -use std::fmt::*; +use error::*; use bcd_convert::BcdNumber; @@ -16,13 +17,20 @@ const PROPS_RESERVED_MASK: u16 = 0xC000; #[allow(dead_code)] const PROPS_DATAENCRYPTION_MASK: u16 = 0x0E00; -pub fn parse_inbound_msg(rawdata: &mut Vec) -> Message { +pub fn parse_inbound_msg(rawdata: &mut Vec) -> std::result::Result { let mut msg: Message = Message::default(); - msg.parse_header(rawdata); - msg.check(rawdata); + match msg.parse_header(rawdata) { + Ok(_) => { + msg.check(rawdata); + } + Err(e) => { + println!("error parsing header {e}"); + return Err(MessageError); + } + }; - msg + Ok(msg) } #[derive(Default, Debug)] @@ -45,11 +53,14 @@ impl std::fmt::Display for Message { } impl Message { - pub fn parse_header(&mut self, rawdata: &mut Vec) { + pub fn parse_header( + &mut self, + rawdata: &mut Vec, + ) -> std::result::Result<(), NotOurProtocolError> { let mut data = rawdata.clone().into_iter(); let first_byte = data.next().unwrap(); - if first_byte == FLAGDELIMITER { - println!("first flag ok"); + if first_byte != FLAGDELIMITER { + return Err(NotOurProtocolError); }; let mut tmpid = vec![]; tmpid.push(data.next().unwrap()); @@ -74,12 +85,11 @@ impl Message { self.checksum = data.next().unwrap(); - if data.next().unwrap() == FLAGDELIMITER { - println!("end flag ok"); - } else { - println!("error with endflag"); + if data.next().unwrap() != FLAGDELIMITER { + return Err(NotOurProtocolError); } self.parse_body(); + Ok(()) } pub fn parse_properties(&mut self) {