-
Notifications
You must be signed in to change notification settings - Fork 0
/
gps.py
executable file
·113 lines (77 loc) · 2.67 KB
/
gps.py
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
#! /usr/bin/env python3
import sys, argparse, traceback, serial, signal
class ETrexDriver(object):
""" """
def __init__(self, device, baud=4800, timeout=1):
"""
Initialize the driver object by configuring/opening serial interface.
"""
self.path = device
self.baud = baud
self.dev = serial.Serial(self.path, self.baud, timeout=timeout)
self.encoding = "utf-8"
self.running = False
self.numpkts = 0
# register ctrl-c signal handler
signal.signal(signal.SIGINT, self.__signal_handler)
def __del__(self):
"""
Cleanup driver resources.
"""
self.dev.close()
self.__dump_metrics()
def __dump_metrics(self):
"""
Print out useful metrics.
"""
print ("\n\n===== Metrics/Stats =====")
print ("number of packets received: " + str(self.numpkts))
def __signal_handler(self, signal, frame):
"""
Handle the Ctrl-C UNIX signal to shutdown the applcation.
"""
print("\n\nReceived signal" + str(signal) + ": shutting down etrex driver...")
self.running = False
def __process_data(self, data):
"""
Process raw GPS ascii data into something more meaningful.
"""
# decode the bytes literal
data = str(data, encoding=self.encoding).strip()
return data
def run(self):
"""
Beginning processing GPS data indefinitely.
"""
self.running = True
data = ""
while self.running:
try:
# read and process GPS bytes up to first newline character
data = self.__process_data(self.dev.readline())
# display raw ascii data to stdout
print ("GPS packet: " + str(data))
# increment metrics
self.numpkts += 1
except Exception as e:
print ("ERROR: " + str(e))
def main(argv=None):
""" main entry point """
device, baud = parse_args()
try:
gps = ETrexDriver(device, baud)
gps.run()
except Exception as e:
print ("\ndriver error -- " + format(e) + "\n")
sys.exit(0)
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description="Read serial data from an etrex GPS unit")
parser.add_argument("device", help="Path to GPS device file")
parser.add_argument("-b", "--baud", required=False, default=4800, type=int, help="Baud rate (optional, 4800 default)")
args = parser.parse_args()
return (args.device, args.baud)
if __name__ == "__main__":
sys.exit(main())