-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGPSController.py
More file actions
125 lines (95 loc) · 3.25 KB
/
GPSController.py
File metadata and controls
125 lines (95 loc) · 3.25 KB
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
122
123
124
125
import gps
import threading
import time
import subprocess
import os
import sys
class GPSController(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
gpsdPort = int(os.getenv('GPSD_PORT', 2947))
subprocess.call('pkill gpsd', shell=True)
subprocess.call(
'gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock -S %d' % gpsdPort,
shell=True)
self.gpsd = gps.gps("localhost", gpsdPort)
self.gpsd.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
self.file = None
self.fileName = None
# set current statement
self.running = False
self.is_logging = False
self.lastLoggedTime = None
def run(self):
# start running
self.running = True
while self.running:
try:
self.gpsd.next()
except StopIteration:
sys.stderr.write('self.gpsd.read() failed.\n')
continue
except json_error as error:
sys.stderr.write(
'json parse error: %s: %s\n' % (
error.explanation,
error.data))
continue
except:
sys.stderr.write(
'Unexpected error: %s: %s\n' % (
sys.exc_info()[0],
sys.exc_info()[1]))
continue
if self.is_logging:
currentTime = time.time()
if (not self.lastLoggedTime
or currentTime - self.lastLoggedTime >= 5):
self.writeLog()
self.lastLoggedTime = currentTime
def writeLog(self):
dataString = ','.join([self.utc,
str(self.fix.latitude),
str(self.fix.longitude),
str(self.fix.speed)])
file = open(self.fileName, 'a')
file.write(dataString + '\n')
file.close()
def stopController(self):
self.running = False
subprocess.call('pkill gpsd', shell=True)
def start_logging(self, fileName='gps_log.csv'):
self.fileName = fileName
self.is_logging = True
def stop_logging(self):
self.is_logging = False
@property
def fix(self):
return self.gpsd.fix
@property
def utc(self):
# self.gpsd.fix.time can be either float or an ISO8601 string
# Use self.gpsd.utc, instead.
return self.gpsd.utc
if __name__ == '__main__':
gpsController = GPSController()
try:
print('Locating...')
gpsController.start()
while (gpsController.isAlive()):
lat = gpsController.fix.latitude
lon = gpsController.fix.longitude
speed = gpsController.fix.speed
utc = gpsController.utc
dataString = ','.join([utc, str(lat), str(lon), str(speed)])
print(dataString)
time.sleep(3)
except KeyboardInterrupt:
print 'Cancelled'
except:
sys.stderr.write(
'Unexpected error: %s: %s\n', (
sys.exc_info()[0],
sys.exc_info()[1]))
finally:
gpsController.stopController()