Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no_std #41

Merged
merged 14 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ edition = "2018"
nom = { version = "7.1.1", default-features = false }
elpiel marked this conversation as resolved.
Show resolved Hide resolved
chrono = { version = "0.4.19", default-features = false }
arrayvec = { version = "0.7.2", default-features = false }
heapless = "0.7.15"

[dev-dependencies]
quickcheck = { version = "1.0.3", default-features = false }
Expand Down
67 changes: 33 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
// limitations under the License.
//

// #![no_std]

mod parse;
mod sentences;

Expand All @@ -29,7 +31,8 @@ pub use crate::parse::{
};
use chrono::{NaiveDate, NaiveTime};
use core::{fmt, mem, ops::BitOr};
use std::{collections::VecDeque, convert::TryInto};
use core::convert::TryInto;
use heapless::Vec;

/// NMEA parser
/// This struct parses NMEA sentences, including checksum checks and sentence
Expand Down Expand Up @@ -62,7 +65,7 @@ pub struct Nmea {
pub pdop: Option<f32>,
/// Geoid separation in meters
pub geoid_separation: Option<f32>,
pub fix_satellites_prns: Option<Vec<u32>>,
pub fix_satellites_prns: Option<Vec<u32,12>>,
satellites_scan: [SatsPack; GnssType::COUNT],
required_sentences_for_nav: SentenceMask,
last_fix_time: Option<NaiveTime>,
Expand All @@ -72,7 +75,13 @@ pub struct Nmea {

#[derive(Debug, Clone, Default)]
struct SatsPack {
data: VecDeque<[Option<Satellite>; 4]>,
// max number of visible GNSS satellites per hemisphere, assuming global coverage
// GPS: 16
// GLONASS: 12
// BeiDou: 12 + 3 IGSO + 3 GEO
// Galileo: 12
// This number will never be reached, so Vec can be resized?
data: Vec<Option<Satellite>,18>,
max_len: usize,
}

Expand Down Expand Up @@ -147,15 +156,16 @@ impl<'a> Nmea {
}

/// Returns used sattelites
pub fn satellites(&self) -> Vec<Satellite> {
let mut ret = Vec::with_capacity(20);
pub fn satellites(&self) -> Vec<Satellite,18> {
let mut ret = Vec::<Satellite, 18>::new();
let sat_key = |sat: &Satellite| (sat.gnss_type() as u8, sat.prn());
for sns in &self.satellites_scan {
for sat_pack in sns.data.iter().rev() {
for sat in sat_pack.iter().flatten() {
// for sat_pack in sns.data.iter().rev() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not remove dead code?

for sat_pack in sns.data.iter() {
for sat in sat_pack.iter() {
match ret.binary_search_by_key(&sat_key(sat), sat_key) {
Ok(_pos) => {} //already setted
Err(pos) => ret.insert(pos, sat.clone()),
Ok(_pos) => {}, //already setted
Err(pos) => {ret.insert(pos, sat.clone()).unwrap()},
}
}
}
Expand All @@ -182,11 +192,14 @@ impl<'a> Nmea {
.try_into()
.map_err(|_| NmeaError::InvalidGsvSentenceNum)?;
d.max_len = full_pack_size.max(d.max_len);

d.data.push_back(data.sats_info);
if d.data.len() > d.max_len {
d.data.pop_front();
// d.data.resize_default(d.max_len);
for i in 0..d.max_len {
d.data.push(data.sats_info[i].clone()).unwrap();
}
// d.data.push_back(data.sats_info);
// if d.data.len() > d.max_len {
// d.data.pop_front();
// }
}

Ok(())
Expand Down Expand Up @@ -416,18 +429,10 @@ impl fmt::Display for Nmea {
write!(
f,
"{}: lat: {} lon: {} alt: {} {:?}",
self.fix_time
.map(|l| format!("{:?}", l))
.unwrap_or_else(|| "None".to_owned()),
self.latitude
.map(|l| format!("{:3.8}", l))
.unwrap_or_else(|| "None".to_owned()),
self.longitude
.map(|l| format!("{:3.8}", l))
.unwrap_or_else(|| "None".to_owned()),
self.altitude
.map(|l| format!("{:.3}", l))
.unwrap_or_else(|| "None".to_owned()),
format_args!("{:?}", self.fix_time),
format_args!("{:?}", self.latitude),
format_args!("{:?}", self.longitude),
format_args!("{:?}", self.altitude),
self.satellites()
)
}
Expand Down Expand Up @@ -473,15 +478,9 @@ impl fmt::Display for Satellite {
"{}: {} elv: {} ath: {} snr: {}",
self.gnss_type,
self.prn,
self.elevation
.map(|e| format!("{}", e))
.unwrap_or_else(|| "--".to_owned()),
self.azimuth
.map(|e| format!("{}", e))
.unwrap_or_else(|| "--".to_owned()),
self.snr
.map(|e| format!("{}", e))
.unwrap_or_else(|| "--".to_owned())
format_args!("{:?}", self.elevation),
format_args!("{:?}", self.azimuth),
format_args!("{:?}", self.snr),
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/sentences/bwc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fn do_parse_bwc(i: &[u8]) -> Result<BwcData, NmeaError> {
let (i, _) = char(',')(i)?;

// 12. Waypoint ID
let (_i, waypoint_id) = opt(map_res(is_not(",*"), std::str::from_utf8))(i)?;
let (_i, waypoint_id) = opt(map_res(is_not(",*"), core::str::from_utf8))(i)?;

// 13. FAA mode indicator (NMEA 2.3 and later, optional)

Expand Down
56 changes: 50 additions & 6 deletions src/sentences/gsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ use nom::branch::alt;
use nom::bytes::complete::take_while1;
use nom::character::complete::{char, one_of};
use nom::combinator::{all_consuming, opt, value};
use nom::multi::many0;
// use nom::multi::many0;
elpiel marked this conversation as resolved.
Show resolved Hide resolved
use nom::number::complete::float;
use nom::sequence::terminated;
use nom::IResult;
use nom::Err;
use nom::Parser;
use nom::error::ParseError;
use nom::InputLength;
use nom::error::ErrorKind;
use heapless::Vec;

use crate::parse::NmeaSentence;
use crate::{sentences::utils::number, NmeaError};
Expand All @@ -27,17 +33,46 @@ pub enum GsaMode2 {
pub struct GsaData {
pub mode1: GsaMode1,
pub mode2: GsaMode2,
pub fix_sats_prn: Vec<u32>,
pub fix_sats_prn: Vec<u32,12>,
pub pdop: Option<f32>,
pub hdop: Option<f32>,
pub vdop: Option<f32>,
}

fn gsa_prn_fields_parse(i: &[u8]) -> IResult<&[u8], Vec<Option<u32>>> {
fn many0<I, O, E, F>(mut f: F) -> impl FnMut(I) -> IResult<I, Vec<O,12>, E>
elpiel marked this conversation as resolved.
Show resolved Hide resolved
where
I: Clone + InputLength,
F: Parser<I, O, E>,
E: ParseError<I>,
O: core::fmt::Debug,
{
move |mut i: I| {
// let mut acc = crate::lib::std::vec::Vec::with_capacity(4);
let mut acc = Vec::<_,12>::new();
loop {
let len = i.input_len();
match f.parse(i.clone()) {
Err(Err::Error(_)) => return Ok((i, acc)),
Err(e) => return Err(e),
Ok((i1, o)) => {
// infinite loop check: the parser must always consume
if i1.input_len() == len {
return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0)));
}

i = i1;
acc.push(o).unwrap();
}
}
}
}
}

fn gsa_prn_fields_parse(i: &[u8]) -> IResult<&[u8], Vec<Option<u32>,12>> {
many0(terminated(opt(number::<u32>), char(',')))(i)
}

type GsaTail = (Vec<Option<u32>>, Option<f32>, Option<f32>, Option<f32>);
type GsaTail = (Vec<Option<u32>,12>, Option<f32>, Option<f32>, Option<f32>);

fn do_parse_gsa_tail(i: &[u8]) -> IResult<&[u8], GsaTail> {
let (i, prns) = gsa_prn_fields_parse(i)?;
Expand Down Expand Up @@ -65,7 +100,7 @@ fn do_parse_gsa(i: &[u8]) -> IResult<&[u8], GsaData> {
let (i, _) = char(',')(i)?;
let (i, mode2) = one_of("123")(i)?;
let (i, _) = char(',')(i)?;
let (i, mut tail) = alt((do_parse_empty_gsa_tail, do_parse_gsa_tail))(i)?;
let (i, tail) = alt((do_parse_empty_gsa_tail, do_parse_gsa_tail))(i)?;
Ok((
i,
GsaData {
Expand All @@ -80,7 +115,16 @@ fn do_parse_gsa(i: &[u8]) -> IResult<&[u8], GsaData> {
'3' => GsaMode2::Fix3D,
_ => unreachable!(),
},
fix_sats_prn: tail.0.drain(..).flatten().collect(),
fix_sats_prn: {
let mut fix_sats_prn = Vec::<u32,12>::new();
for sat in tail.0.iter() {
match sat {
Some(s) => fix_sats_prn.push(*s).unwrap(),
elpiel marked this conversation as resolved.
Show resolved Hide resolved
None => break,
};
}
fix_sats_prn
},
pdop: tail.1,
hdop: tail.2,
vdop: tail.3,
Expand Down
15 changes: 9 additions & 6 deletions src/sentences/gsv.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use nom::character::complete::char;
use nom::combinator::{cond, opt, rest_len};
use nom::IResult;
use heapless::Vec;

use crate::parse::NmeaSentence;
use crate::sentences::utils::number;
Expand All @@ -12,7 +13,8 @@ pub struct GsvData {
pub number_of_sentences: u16,
pub sentence_num: u16,
pub _sats_in_view: u16,
pub sats_info: [Option<Satellite>; 4],
// see SatPack in lib.rs
elpiel marked this conversation as resolved.
Show resolved Hide resolved
pub sats_info: Vec<Option<Satellite>,4>,
}

fn parse_gsv_sat_info(i: &[u8]) -> IResult<&[u8], Satellite> {
Expand Down Expand Up @@ -43,18 +45,19 @@ fn do_parse_gsv(i: &[u8]) -> IResult<&[u8], GsvData> {
let (i, _) = char(',')(i)?;
let (i, _sats_in_view) = number::<u16>(i)?;
let (i, _) = char(',')(i)?;
let (i, sat0) = opt(parse_gsv_sat_info)(i)?;
let (i, sat1) = opt(parse_gsv_sat_info)(i)?;
let (i, sat2) = opt(parse_gsv_sat_info)(i)?;
let (i, sat3) = opt(parse_gsv_sat_info)(i)?;
let mut sats = Vec::<Option<Satellite>,4>::new();
for iter in 0..sats.len() {
let (_i, sat) = opt(parse_gsv_sat_info)(i)?;
sats.insert(iter,sat).unwrap();
elpiel marked this conversation as resolved.
Show resolved Hide resolved
}
Ok((
i,
GsvData {
gnss_type: GnssType::Galileo,
number_of_sentences,
sentence_num,
_sats_in_view,
sats_info: [sat0, sat1, sat2, sat3],
sats_info: sats,
},
))
}
Expand Down