From bf53cb2fd4bcb76122c42cfbace9e4149aa5eae0 Mon Sep 17 00:00:00 2001 From: Pablo Canseco Date: Thu, 13 Apr 2023 01:52:57 -0600 Subject: [PATCH] [gps] make the date available in addition to the time (#532) gps: also parse the date from an RMC sentence. Add coverage to unit test so it also asserts on time and date. --- gps/gpsparser.go | 16 ++++++++++++++++ gps/gpsparser_test.go | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/gps/gpsparser.go b/gps/gpsparser.go index 6cd76d5..0cae7d2 100644 --- a/gps/gpsparser.go +++ b/gps/gpsparser.go @@ -95,6 +95,8 @@ func (parser *Parser) Parse(sentence string) (Fix, error) { fix.Longitude = findLongitude(fields[5], fields[6]) fix.Speed = findSpeed(fields[7]) fix.Heading = findHeading(fields[8]) + date := findDate(fields[9]) + fix.Time = fix.Time.AddDate(date.Year(), int(date.Month()), date.Day()) return fix, nil } @@ -177,6 +179,20 @@ func findSatellites(val string) (n int16) { return 0 } +// findDate returns the date from an RMC NMEA sentence. +func findDate(val string) time.Time { + if len(val) < 6 { + return time.Time{} + } + + d, _ := strconv.ParseInt(val[0:2], 10, 8) + m, _ := strconv.ParseInt(val[2:4], 10, 8) + y, _ := strconv.ParseInt(val[4:6], 10, 8) + t := time.Date(int(2000+y), time.Month(m), int(d), 0, 0, 0, 0, time.UTC) + + return t +} + // findSpeed returns the speed from an RMC NMEA sentence. func findSpeed(val string) float32 { if len(val) > 0 { diff --git a/gps/gpsparser_test.go b/gps/gpsparser_test.go index 73f4591..17c5dd9 100644 --- a/gps/gpsparser_test.go +++ b/gps/gpsparser_test.go @@ -76,6 +76,12 @@ func TestParseRMC(t *testing.T) { t.Error("should have parsed") } + c.Assert(fix.Time.Year(), qt.Equals, 2022) + c.Assert(fix.Time.Month(), qt.Equals, time.May) + c.Assert(fix.Time.Day(), qt.Equals, 13) + c.Assert(fix.Time.Hour(), qt.Equals, 20) + c.Assert(fix.Time.Minute(), qt.Equals, 35) + c.Assert(fix.Time.Second(), qt.Equals, 22) c.Assert(fix.Latitude, qt.Equals, float32(51.15043640136719)) c.Assert(fix.Longitude, qt.Equals, float32(-114.03067779541016)) }