-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
gps.go
121 lines (104 loc) · 2.31 KB
/
gps.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package gps
import (
"bufio"
"fmt"
"io"
"strings"
"time"
nmea "github.com/adrianmo/go-nmea"
"github.com/cbrake/go-serial/serial"
"github.com/simpleiot/simpleiot/data"
)
// Gps represent a GPS receiver
type Gps struct {
portName string
baud uint
c chan data.GpsPos
debug bool
stop bool
port io.ReadWriteCloser
}
// NewGps is used to create a new Gps type
func NewGps(portName string, baud uint, c chan data.GpsPos) *Gps {
return &Gps{
portName: portName,
baud: baud,
c: c,
}
}
// SetDebug can be used to turn debugging on and off
func (gps *Gps) SetDebug(d bool) {
gps.debug = d
}
// Stop can be used to stop the GPS aquisition and close port
func (gps *Gps) Stop() {
gps.port.Close()
gps.stop = true
}
// Start is used to start reading the GPS, and data will be sent back
// through the handler
func (gps *Gps) Start() {
gps.stop = false
go func() {
options := serial.OpenOptions{
PortName: gps.portName,
BaudRate: gps.baud,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 1,
InterCharacterTimeout: 0,
}
for {
var err error
gps.port, err = serial.Open(options)
if err != nil {
if gps.debug {
fmt.Println("failed to open port: ", options.PortName)
}
// delay a bit before trying to open port again
time.Sleep(10 * time.Second)
continue
}
fmt.Println("GPS port opened: ", options.PortName)
reader := bufio.NewReader(gps.port)
for {
if gps.stop {
fmt.Println("Closing GPS")
return
}
line, err := reader.ReadString('\n')
if gps.debug {
fmt.Println(line)
}
if err != nil {
fmt.Println("Error reading gps, closing: ", err)
break
}
s, err := nmea.Parse(strings.TrimSpace(line))
if err == nil {
if s.DataType() == nmea.TypeGGA {
m := s.(nmea.GGA)
ret := data.GpsPos{
Lat: m.Latitude,
Long: m.Longitude,
Fix: m.FixQuality,
NumSat: m.NumSatellites,
}
gps.c <- ret
}
} else {
if gps.debug {
fmt.Println("Error parsing GPS data: ", err)
}
}
}
gps.port.Close()
if gps.stop {
fmt.Println("Closing GPS")
return
}
// delay a bit before trying to open port again
time.Sleep(10 * time.Second)
}
}()
}