2 * Copyright (c) 2019 Tilman Sauerbeck (tilman at code-monkey de)
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 type Fixed = fixed15_49::Fixed15_49;
37 unix_date: u32, // Number of days passed since 1970-01-01
41 checksum_is_valid: bool,
45 #[derive(Clone, Copy)]
46 pub struct TimeAndPos {
49 pub latitude: i32, // Positive means north, negative means south.
50 pub longitude: i32, // Positive means east, negative means west.
51 pub latitude_rad: Fixed, // Positive means north, negative means south.
52 pub longitude_rad: Fixed, // Positive means east, negative means west.
56 pub fn new() -> TimeAndPos {
62 latitude_rad: Fixed::from_i64(0),
63 longitude_rad: Fixed::from_i64(0),
68 fn to_lower(c: u8) -> u8 {
72 fn parse_coordinate(s: &[u8]) -> i32 {
73 // Find the position of the decimal separator for the minutes.
74 let dot_position = s.iter().enumerate().find(|(_, &c)| {
76 }).and_then(|(i, _)| {
80 if dot_position.is_none() {
84 // Minutes take two digits before the decimal separator.
85 let num_degree_digits = dot_position.unwrap() - 2;
89 for c in s[0..num_degree_digits].iter() {
91 degrees += (c - b'0') as i32;
96 for c in s[num_degree_digits..dot_position.unwrap()].iter() {
98 minutes += (c - b'0') as i32;
101 minutes += degrees * 60;
103 for c in s[dot_position.unwrap() + 1..].iter() {
105 minutes += (c - b'0') as i32;
111 fn parse_coordinate_q(s: &[u8]) -> Fixed {
112 // Find the position of the decimal separator for the minutes.
113 let dot_position_o = s.iter().enumerate().find(|(_, &c)| {
115 }).and_then(|(i, _)| {
119 if dot_position_o.is_none() {
120 return Fixed::from_i64(0);
123 let dot_position = dot_position_o.unwrap();
125 // Minutes take two digits before the decimal separator.
126 let num_degree_digits = dot_position - 2;
128 let degrees = s[0..num_degree_digits].iter().fold(0, |d, c| {
129 (d * 10) + (c - b'0') as i32
132 let minutes = s[num_degree_digits..dot_position].iter().fold(0, |d, c| {
133 (d * 10) + (c - b'0') as i32
136 let decimal_minutes = s[dot_position + 1..].iter().fold(0, |d, c| {
137 (d * 10) + (c - b'0') as i32
140 let mut result = Fixed::from_i64(decimal_minutes.into());
141 result /= Fixed::from_i64(10000);
143 result += Fixed::from_i64(minutes.into());
144 result /= Fixed::from_i64(60);
146 result += Fixed::from_i64(degrees.into());
151 // Only works for 2016 onwards.
152 fn is_leap_year(year: u32) -> bool {
156 fn parse_d2(s: &[u8]) -> u32 {
157 let a = (s[0] - b'0') as u32;
158 let b = (s[1] - b'0') as u32;
163 struct FieldIter<'a> {
168 impl<'a> Iterator for FieldIter<'a> {
169 type Item = &'a [u8];
171 fn next(&mut self) -> Option<&'a [u8]> {
172 let delimiter = b',';
174 if self.offset == self.command.len() {
180 if self.offset > self.command.len() {
184 if self.command[self.offset] == delimiter {
190 let mut start : Option<usize> = None;
192 // Find the start of the substring.
193 for o in self.offset..self.command.len() {
194 if self.command[o] != delimiter {
200 start.and_then(|start2| {
201 let mut end : Option<usize> = None;
203 // Find the end of the substring.
204 for o in start2..self.command.len() {
205 if self.command[o] == delimiter {
212 end.and_then(|end2| {
215 self.offset = end3 + 1;
217 Some(&self.command[start2..end3])
223 const SUM_EXTRA_DAYS_UNTIL_MONTH : [u32; 11] = [
224 0x03, 0x03, 0x06, 0x08, 0x0b, 0x0d,
225 0x10, 0x13, 0x15, 0x18, 0x1a,
229 pub fn new() -> Gps {
233 state: ParseState::Start,
235 checksum_is_valid: false,
240 pub fn update<F>(&mut self, tap: &mut TimeAndPos, mut read_func: F) -> bool
241 where F: FnMut() -> Option<u8>
243 let hexdigits = b"0123456789abcdef";
245 while let Some(received) = read_func() {
246 if received == b'$' {
247 self.state = ParseState::InPacket;
249 self.checksum = 0x00;
255 ParseState::Start => {
258 ParseState::InPacket => {
259 if received == b'*' {
260 self.state = ParseState::InChecksum1;
261 self.checksum_is_valid = true;
263 // Check if message fits in buffer. We subtract one
264 // because we will need to write the sentinel later.
265 } else if self.offset == self.line.len() - 1 {
266 self.state = ParseState::Start;
268 self.checksum ^= received;
269 self.line[self.offset] = received;
273 ParseState::InChecksum1 => {
274 let expected = hexdigits[(self.checksum >> 4) as usize & 0xf];
276 if to_lower(received) != expected {
277 self.checksum_is_valid = false;
280 self.state = ParseState::InChecksum2;
282 ParseState::InChecksum2 => {
283 let expected = hexdigits[(self.checksum >> 0) as usize & 0xf];
285 if to_lower(received) != expected {
286 self.checksum_is_valid = false;
289 self.state = ParseState::Start;
291 if self.checksum_is_valid {
292 // Terminate and dispatch.
293 self.line[self.offset] = b'\0';
306 fn parse(&mut self, tap: &mut TimeAndPos) -> bool {
307 let line_copy : [u8; 256] = self.line;
309 let mut field_iter = FieldIter {
310 command: &line_copy[0..self.offset],
314 match field_iter.next() {
316 self.parse_rmc(&mut field_iter);
320 self.parse_gga(&mut field_iter, tap)
329 fn parse_rmc(&mut self, field_iter: &mut FieldIter) {
330 let f8 = field_iter.nth(8);
332 if let Some(date) = f8 {
334 let days = parse_d2(&date[0..2]);
335 let months = parse_d2(&date[2..4]);
336 let years = 2000 + parse_d2(&date[4..6]);
338 let years_in_epoch = years - 1970;
340 // This only works until 2100.
342 (years_in_epoch * 365) + ((years_in_epoch + 1) / 4);
344 // Add the number of days passed in this year,
345 // excluding the current month.
347 unix_date += 28 * (months - 1);
348 unix_date += SUM_EXTRA_DAYS_UNTIL_MONTH[(months - 2) as usize];
351 if months >= 3 && is_leap_year(years) {
356 unix_date += days - 1;
359 self.unix_date = unix_date;
364 fn parse_gga(&mut self, field_iter: &mut FieldIter, tap: &mut TimeAndPos) -> bool {
365 let f0 = field_iter.next();
366 let f1 = field_iter.next();
367 let f2 = field_iter.next();
368 let f3 = field_iter.next();
369 let f4 = field_iter.next();
370 let f5 = field_iter.next();
372 match (f0, f1, f2, f3, f4, f5) {
378 Some(pos_fix_indicator),
380 if self.unix_date == 0 {
384 match pos_fix_indicator {
386 // Valid standard GPS fix (low resolution).
389 // Valid differential GPS fix (high resolution).
396 if utc_time.len() < 6 {
400 let hours = parse_d2(&utc_time[0..2]);
401 let minutes = parse_d2(&utc_time[2..4]);
402 let seconds = parse_d2(&utc_time[4..6]);
404 let mut unix_time = self.unix_date;
405 unix_time *= 24; // Days to hours.
407 unix_time *= 60; // Hours to minutes.
408 unix_time += minutes;
409 unix_time *= 60; // Minutes to seconds.
410 unix_time += seconds;
412 tap.system_time = systick::now();
413 tap.unix_time = unix_time;
414 tap.latitude = parse_coordinate(latitude);
415 tap.longitude = parse_coordinate(longitude);
416 tap.latitude_rad = parse_coordinate_q(latitude).to_radians();
417 tap.longitude_rad = parse_coordinate_q(longitude).to_radians();
419 if north_south == b"S" {
420 tap.latitude = -tap.latitude;
421 tap.latitude_rad = -tap.latitude_rad;
424 if east_west == b"W" {
425 tap.longitude = -tap.longitude;
426 tap.longitude_rad = -tap.longitude_rad;