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.
34 unix_date: u32, // Number of days passed since 1970-01-01
38 checksum_is_valid: bool,
42 #[derive(Clone, Copy)]
43 pub struct TimeAndPos {
46 pub latitude: i32, // Positive means north, negative means south.
47 pub longitude: i32, // Positive means east, negative means west.
51 pub fn new() -> TimeAndPos {
61 fn to_lower(c: u8) -> u8 {
65 fn parse_coordinate(s: &[u8]) -> i32 {
66 // Find the position of the decimal separator for the minutes.
67 let dot_position = s.iter().enumerate().find(|(_, &c)| {
69 }).and_then(|(i, _)| {
73 if dot_position.is_none() {
77 // Minutes take two digits before the decimal separator.
78 let num_degree_digits = dot_position.unwrap() - 2;
82 for c in s[0..num_degree_digits].iter() {
84 degrees += (c - b'0') as i32;
89 for c in s[num_degree_digits..dot_position.unwrap()].iter() {
91 minutes += (c - b'0') as i32;
94 minutes += degrees * 60;
96 for c in s[dot_position.unwrap() + 1..].iter() {
98 minutes += (c - b'0') as i32;
104 // Only works for 2016 onwards.
105 fn is_leap_year(year: u32) -> bool {
109 fn parse_d2(s: &[u8]) -> u32 {
110 let a = (s[0] - b'0') as u32;
111 let b = (s[1] - b'0') as u32;
116 struct FieldIter<'a> {
121 impl<'a> Iterator for FieldIter<'a> {
122 type Item = &'a [u8];
124 fn next(&mut self) -> Option<&'a [u8]> {
125 let delimiter = b',';
127 if self.offset == self.command.len() {
133 if self.offset > self.command.len() {
137 if self.command[self.offset] == delimiter {
143 let mut start : Option<usize> = None;
145 // Find the start of the substring.
146 for o in self.offset..self.command.len() {
147 if self.command[o] != delimiter {
153 start.and_then(|start2| {
154 let mut end : Option<usize> = None;
156 // Find the end of the substring.
157 for o in start2..self.command.len() {
158 if self.command[o] == delimiter {
165 end.and_then(|end2| {
168 self.offset = end3 + 1;
170 Some(&self.command[start2..end3])
176 const SUM_EXTRA_DAYS_UNTIL_MONTH : [u32; 11] = [
177 0x03, 0x03, 0x06, 0x08, 0x0b, 0x0d,
178 0x10, 0x13, 0x15, 0x18, 0x1a,
182 pub fn new() -> Gps {
186 state: ParseState::Start,
188 checksum_is_valid: false,
193 pub fn update<F>(&mut self, tap: &mut TimeAndPos, mut read_func: F) -> bool
194 where F: FnMut() -> Option<u8>
196 let hexdigits = b"0123456789abcdef";
198 while let Some(received) = read_func() {
199 if received == b'$' {
200 self.state = ParseState::InPacket;
202 self.checksum = 0x00;
208 ParseState::Start => {
211 ParseState::InPacket => {
212 if received == b'*' {
213 self.state = ParseState::InChecksum1;
214 self.checksum_is_valid = true;
216 // Check if message fits in buffer. We subtract one
217 // because we will need to write the sentinel later.
218 } else if self.offset == self.line.len() - 1 {
219 self.state = ParseState::Start;
221 self.checksum ^= received;
222 self.line[self.offset] = received;
226 ParseState::InChecksum1 => {
227 let expected = hexdigits[(self.checksum >> 4) as usize & 0xf];
229 if to_lower(received) != expected {
230 self.checksum_is_valid = false;
233 self.state = ParseState::InChecksum2;
235 ParseState::InChecksum2 => {
236 let expected = hexdigits[(self.checksum >> 0) as usize & 0xf];
238 if to_lower(received) != expected {
239 self.checksum_is_valid = false;
242 self.state = ParseState::Start;
244 if self.checksum_is_valid {
245 // Terminate and dispatch.
246 self.line[self.offset] = b'\0';
259 fn parse(&mut self, tap: &mut TimeAndPos) -> bool {
260 let line_copy : [u8; 256] = self.line;
262 let mut field_iter = FieldIter {
263 command: &line_copy[0..self.offset],
267 match field_iter.next() {
269 self.parse_rmc(&mut field_iter);
273 self.parse_gga(&mut field_iter, tap)
282 fn parse_rmc(&mut self, field_iter: &mut FieldIter) {
283 let f8 = field_iter.nth(8);
285 if let Some(date) = f8 {
287 let days = parse_d2(&date[0..2]);
288 let months = parse_d2(&date[2..4]);
289 let years = 2000 + parse_d2(&date[4..6]);
291 let years_in_epoch = years - 1970;
293 // This only works until 2100.
295 (years_in_epoch * 365) + ((years_in_epoch + 1) / 4);
297 // Add the number of days passed in this year,
298 // excluding the current month.
300 unix_date += 28 * (months - 1);
301 unix_date += SUM_EXTRA_DAYS_UNTIL_MONTH[(months - 2) as usize];
304 if months >= 3 && is_leap_year(years) {
309 unix_date += days - 1;
312 self.unix_date = unix_date;
317 fn parse_gga(&mut self, field_iter: &mut FieldIter, tap: &mut TimeAndPos) -> bool {
318 let f0 = field_iter.next();
319 let f1 = field_iter.next();
320 let f2 = field_iter.next();
321 let f3 = field_iter.next();
322 let f4 = field_iter.next();
323 let f5 = field_iter.next();
325 match (f0, f1, f2, f3, f4, f5) {
331 Some(pos_fix_indicator),
333 if self.unix_date == 0 {
337 match pos_fix_indicator {
339 // Valid standard GPS fix (low resolution).
342 // Valid differential GPS fix (high resolution).
349 if utc_time.len() < 6 {
353 let hours = parse_d2(&utc_time[0..2]);
354 let minutes = parse_d2(&utc_time[2..4]);
355 let seconds = parse_d2(&utc_time[4..6]);
357 let mut unix_time = self.unix_date;
358 unix_time *= 24; // Days to hours.
360 unix_time *= 60; // Hours to minutes.
361 unix_time += minutes;
362 unix_time *= 60; // Minutes to seconds.
363 unix_time += seconds;
365 tap.system_time = systick::now();
366 tap.unix_time = unix_time;
367 tap.latitude = parse_coordinate(latitude);
368 tap.longitude = parse_coordinate(longitude);
370 if north_south == b"S" {
371 tap.latitude = -tap.latitude;
374 if east_west == b"W" {
375 tap.longitude = -tap.longitude;