diff --git a/src/main.rs b/src/main.rs index b727863..a36df56 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,10 @@ -pub mod parser; +mod parser; -pub use crate::parser::*; +use crate::parser::*; use std::io; -//use std::sync::Arc; use tokio::net::TcpListener; -//use tokio::sync::RwLock; const ADDR: &'static str = "0.0.0.0:7700"; const BUFSIZE: usize = 1024; @@ -14,12 +12,9 @@ const BUFSIZE: usize = 1024; #[tokio::main] async fn main() { apiserver().await.unwrap(); - loop { - std::thread::sleep(std::time::Duration::from_secs(1)); - } } -pub async fn apiserver() -> io::Result<()> { +async fn apiserver() -> io::Result<()> { let listener = match TcpListener::bind(ADDR).await { Ok(o) => o, Err(e) => { @@ -38,9 +33,17 @@ pub async fn apiserver() -> io::Result<()> { Ok(_) => { match socket.try_read(&mut buf) { Ok(_) => match handle(&buf) { - Some(o) => { - let _ = socket.try_write(&o).unwrap(); - } + Some(o) => match socket.try_write(&o) { + Ok(_) => {} + Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => { + println!("broken pipe: {e}"); + break; + } + Err(e) => { + println!("error: {e}"); + break; + } + }, None => { break; } @@ -70,7 +73,7 @@ pub async fn apiserver() -> io::Result<()> { } } -pub fn handle(buf: &Vec) -> Option> { +fn handle(buf: &Vec) -> Option> { let mut rawdata = InboundDataWrapper::new(buf.to_vec()); let reply = match parse_inbound_msg(&mut rawdata) { Ok(o) => { @@ -89,7 +92,7 @@ pub fn handle(buf: &Vec) -> Option> { Some(o) => { println!("reply: {}", o); //println!("raw reply {:X?}", o.to_raw()); - println!("\n"); + println!("--------------"); return Some(o.to_raw().into()); } None => { diff --git a/src/parser/body.rs b/src/parser/body.rs index aab58bf..1ce2573 100644 --- a/src/parser/body.rs +++ b/src/parser/body.rs @@ -3,6 +3,8 @@ use bitvec::prelude::*; use chrono::prelude::*; use encoding_rs::*; +#[allow(dead_code)] + pub trait BodyMessage { fn build(&self) {} @@ -17,6 +19,7 @@ pub trait BodyMessage { fn to_raw(&self) -> Vec { vec![] } + fn parse(&mut self, rawbody: &Vec) {} } @@ -162,6 +165,7 @@ impl std::fmt::Display for TerminalRegistration { } } +#[allow(dead_code)] enum TerminalRegistrationResult { Success = 0x00, VehicleRegistered, @@ -348,16 +352,16 @@ impl LocationInformationReport { res } - fn parse_latitude(&self, lat: u32) -> f64 { - let mut res = lat as f64 / 1_000_000f64; + fn parse_latitude(&self, latitude: u32) -> f64 { + let mut res = latitude as f64 / 1_000_000.; if self.status.south { res = -res }; res } - fn parse_longitude(&self, long: u32) -> f64 { - let mut res = long as f64 / 1_000_000f64; + fn parse_longitude(&self, longitude: u32) -> f64 { + let mut res = longitude as f64 / 1_000_000.; if self.status.west { res = -res }; @@ -367,7 +371,9 @@ impl LocationInformationReport { impl BodyMessage for LocationInformationReport { fn parse(&mut self, rawbody: &Vec) { + let res: bool; let mut bd = rawbody.into_iter(); + //let z: [u8; 4] = bd.take(4).collect::>().try_into().unwrap(); self.alert_mark = u32::from_be_bytes( vec![ *bd.next().unwrap(), @@ -428,13 +434,18 @@ impl BodyMessage for LocationInformationReport { for i in 0..tmptime.len() { tmptime[i] = *bd.next().unwrap(); } - println!("{:X?}", rawbody); - println!("{:?}", tmptime); let code = BcdNumber::try_from(&tmptime as &[u8]).unwrap(); - println!("{}", code); let time = format!("{}", code.to_u64().unwrap()); - println!("{}", time); - self.time = NaiveDateTime::parse_from_str(time.as_str(), "%y%m%d%H%M%S").unwrap(); + match NaiveDateTime::parse_from_str(time.as_str(), "%y%m%d%H%M%S") { + Ok(o) => { + self.time = o; + } + Err(e) => { + println!("{tmptime:?} {code} {time} {e}"); + } + }; + res = true; + () } } @@ -509,7 +520,6 @@ impl BCDTime { pub fn parse() {} } */ - macro_rules! generate_impl { ($($t:ty),*) => { $( diff --git a/src/parser/error.rs b/src/parser/error.rs index 59dd0cb..643c2d9 100644 --- a/src/parser/error.rs +++ b/src/parser/error.rs @@ -2,13 +2,13 @@ pub struct MessageError; impl std::fmt::Debug for MessageError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "invalid protocol") + write!(f, "invalid message") } } impl std::fmt::Display for MessageError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "invalid protocol") + write!(f, "invalid message") } } diff --git a/src/parser/header.rs b/src/parser/header.rs index 8782048..d145c4b 100644 --- a/src/parser/header.rs +++ b/src/parser/header.rs @@ -16,8 +16,8 @@ pub struct MessageHeader { properties: u16, pub bodylength: u8, encryption: u8, - pub encrypted: bool, - pub subcontract: bool, + encrypted: bool, + subcontract: bool, reserved: u16, raw_terminal_id: [u8; 6], pub terminal_id: u64, diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 32634c9..3ed8b7d 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -70,7 +70,10 @@ impl Iterator for InboundDataWrapper { Some(o) => match o { 0x02 => res = Some(FLAG_DELIMITER), 0x01 => res = Some(FLAG_DELIMITER_ESCAPE), - _ => self.escaped = Some(o), + _ => { + self.escaped = Some(o); + self.ended = true; + } }, None => {} } @@ -109,6 +112,7 @@ impl Message { let msg = Self::default(); return msg; } + fn parse_header( &mut self, rawdata: &mut InboundDataWrapper, @@ -315,14 +319,18 @@ impl Message { } pub fn to_raw(&self) -> VecDeque { - let mut resp: VecDeque = vec![].into(); + let mut resp: VecDeque = VecDeque::new(); for b in self.header.to_raw() { - resp.push_back(b); + for i in Self::escape_outbound(b) { + resp.push_back(i); + } } for b in self.content.to_raw() { - resp.push_back(b); + for i in Self::escape_outbound(b) { + resp.push_back(i); + } } resp.push_back(self.checksum); @@ -331,6 +339,18 @@ impl Message { resp.push_back(FLAG_DELIMITER); resp } + + fn escape_outbound(in_data: u8) -> Vec { + let mut res: Vec = Vec::new(); + match in_data { + FLAG_DELIMITER => res = vec![FLAG_DELIMITER_ESCAPE, 0x02], + FLAG_DELIMITER_ESCAPE => res = vec![FLAG_DELIMITER_ESCAPE, 0x01], + _ => { + res.push(in_data); + } + } + res + } } impl std::fmt::Display for Message {