Transform into library

Signed-off-by: Thomas Klaehn <thomas.klaehn@perinet.io>
This commit is contained in:
Thomas Klaehn
2025-01-15 10:16:54 +01:00
parent 95fdc03e2b
commit 4e601d553c
6 changed files with 461 additions and 139 deletions

72
src/lib.rs Normal file
View File

@@ -0,0 +1,72 @@
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use chrono::{DateTime, Utc};
use nmea_parser::*;
#[derive(Debug)]
pub struct ParseResult {
lat: f64,
lon: f64,
timestamp: DateTime<Utc>,
speed: f64
}
pub struct GpsParser {
gps_file: String,
}
impl GpsParser {
pub fn new(gps_device: &str) -> GpsParser{
GpsParser {
gps_file: format!("{}",gps_device),
}
}
pub fn parse_nmea(&mut self) -> Result<ParseResult, ParseError> {
let f = match File::open(&self.gps_file) {
Ok(f) => f,
Err(error) => panic!("Error: {error:?}"),
};
let mut reader = BufReader::new(f);
let mut line = String::new();
let mut parser = NmeaParser::new();
let mut res = ParseResult {
lat: 0.0,
lon: 0.0,
timestamp: Utc::now(),
speed: 0.0,
};
let mut parsing_complete = false;
let mut parsed_gga:bool = false;
let mut parsed_vtg:bool = false;
while !parsing_complete {
let len = match reader.read_line(&mut line) {
Ok(len) => len,
Err(_) => 0,
};
if len > 1 {
match parser.parse_sentence(&line)? {
ParsedMessage::Gga(gga) => {
parsed_gga = true;
res.lat = gga.latitude.unwrap();
res.lon = gga.longitude.unwrap();
res.timestamp = gga.timestamp.unwrap();
},
ParsedMessage::Vtg(vtg) => {
parsed_vtg = true;
res.speed = vtg.sog_kph.unwrap();
},
_ => {
}
}
}
if parsed_gga && parsed_vtg {
parsing_complete = true;
}
line.clear();
}
Ok(res)
}
}