forked from EVNotify/EVNotiPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpspoller.py
140 lines (125 loc) · 5.33 KB
/
gpspoller.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
""" Interface to gpsd """
from threading import Thread
from time import sleep, strptime
from calendar import timegm
import json
import logging
import socket
def empty_fix():
""" Return an empty fix so all fields are guaranteed to exist. """
return {
'device': None,
'mode': 0,
'latitude': None,
'longitude': None,
'speed': None,
'altitude': None,
'heading': None,
'time': None,
'xdop': None,
'ydop': None,
'vdop': None,
'tdop': None,
'hdop': None,
'gdop': None,
'pdop': None,
}
class GpsPoller:
""" Thread that continously reads data from gpsd. """
def __init__(self, store=None):
""" store: json file to store last valid fix on shutdown """
self._log = logging.getLogger("EVNotiPi/GPSPoller")
self._thread = None
self._gpsd = ('localhost', 2947)
self._last_fix = empty_fix()
self._store = store
self._running = False
def run(self):
""" The reader thread. """
self._running = True
gps_sock = None
while self._running:
try:
if gps_sock:
data = gps_sock.recv(4096)
for line in data.split(b'\r\n'):
if len(line) == 0:
continue
try:
self._log.debug("GPS line: {}".format(line))
fix = json.loads(line)
if 'class' not in fix:
continue
if fix['class'] == 'TPV' and fix['mode'] > 1:
fix_time = timegm(strptime(fix['time'],
"%Y-%m-%dT%H:%M:%S.%fZ"))
self._log.debug("GPS fix at: {}".format(fix_time))
self._last_fix.update({
'device': fix['device'],
'mode': fix['mode'],
'latitude': fix.get('lat'),
'longitude': fix.get('lon'),
'speed': fix.get('speed'),
'altitude': fix.get('altMSL'),
'heading': fix.get('track'),
'time': fix_time,
})
if (self._last_fix['speed'] is not None and
0 < self._last_fix['speed'] < 1):
self._last_fix['speed'] = 0
elif fix['class'] == 'SKY':
self._last_fix.update({
'xdop': fix.get('xdop', None),
'ydop': fix.get('ydop', None),
'vdop': fix.get('vdop', None),
'tdop': fix.get('tdop', None),
'hdop': fix.get('hdop', None),
'gdop': fix.get('gdop', None),
'pdop': fix.get('pdop', None),
})
except json.decoder.JSONDecodeError:
self._log.error("JSONDecodeError %s", line)
else:
gps_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gps_sock.connect(self._gpsd)
gps_sock.settimeout(1)
gps_sock.recv(1024)
gps_sock.sendall(b'?WATCH={"enable":true,"json":true};')
except socket.timeout:
sleep(0.1)
except (StopIteration, ConnectionResetError, OSError) as err:
self._log.info('Problem encountered. Resetting socket. (%s)', err)
gps_sock.close()
gps_sock = None
self._last_fix = empty_fix()
sleep(1)
def fix(self):
""" Return the last fix. """
return self._last_fix
def start(self):
""" Start the poller thread. """
if self._store:
try:
with open(self._store, encoding='utf-8') as store_file:
new_fix = json.load(store_file)
self._last_fix['latitude'] = new_fix['latitude']
self._last_fix['longitude'] = new_fix['longitude']
self._last_fix['altitude'] = new_fix['altitude']
except FileNotFoundError:
self._log.warn('File not found (%s)', self._store)
self._running = True
self._thread = Thread(target=self.run, name="EVNotiPi/GPS")
self._thread.start()
def stop(self):
""" Stop the poller thread. """
self._running = False
self._thread.join()
if self._store:
try:
with open(self._store, 'w', encoding='utf-8') as store_file:
json.dump(self._last_fix, store_file)
except FileNotFoundError:
self._log.warn('File not found (%s)', self._store)
def check_thread(self):
""" Return running state if the poller thread. """
return self._thread.is_alive()