-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgpsd.py
executable file
·211 lines (180 loc) · 5.49 KB
/
gpsd.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/python
# FIlename: gpsd.py
'''
Created on 17 Dec 2013
@author: rmamba@gmail.com
'''
from daemon import Daemon
from decimal import Decimal
import sys
import time
import math
import json
import requests
#RaspberryPi: sudo apt-get install python-serial
#OpenSuse: zypper install python-serial
import serial
class MyDaemon(Daemon):
def _writeLog(self, msg, isDate=True):
sys.stdout.write("%s: %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg))
sys.stdout.flush()
def _writeErr(self, msg, isDate=True):
sys.stderr.write("%s: %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg))
sys.stderr.flush()
def _isNoneOrEmptry(self, val):
if (val==None) or (val==""):
return True
return False
def _toDoubleLatLong(self, latlon, side):
val = None
if (self._isNoneOrEmptry(latlon) or self._isNoneOrEmptry(side)):
return None
try:
tmp = float(latlon)
tmp /= 100
val = math.floor(tmp)
tmp = (tmp - val) * 100
val += tmp/60
tmp -= math.floor(tmp)
tmp *= 60
if ((side.upper() == "S") or (side.upper()=="W")):
val *= -1
except ValueError:
self._writeErr("Can't calculate from {0} side {1}".format(latlon, side))
val = None
return val
def _toFloat(self, value):
val = None
if self._isNoneOrEmptry(value):
return None
try:
val = float(value)
except ValueError:
self._writeErr("Can't convert to float: {0}".format(value))
val = None
return val
def _toInt(self, value):
val = None
if self._isNoneOrEmptry(value):
return None
try:
val = int(value)
except ValueError:
self._writeErr("Can't convert to int: {0}".format(value))
val = None
return val
def run(self):
while True:
isChanged = False
if self.__ser.inWaiting()>40:
line = self.__ser.readline()
if (self.__hislog != None):
self.__hislog.write(line)
if (line.startswith('$GPGGA')):
GGA = line.split(',')
self.GPS['DateTime']['time'] = self._toFloat(GGA[1])
self.GPS['Lat'] = self._toDoubleLatLong(GGA[2], GGA[3])
self.GPS['Lon'] = self._toDoubleLatLong(GGA[4], GGA[5])
self.GPS['Url']['GoogleMaps'] = 'https://maps.google.com?q={Lat},{Lon}&z=17'.format(**self.GPS)
self.GPS['Satellites'] = self._toInt(GGA[7])
self.GPS['Dilution'] = self._toFloat(GGA[8])
self.GPS['Alt'] = self._toFloat(GGA[9])
isChanged = True
if (line.startswith('$GPRMC')):
RMC = line.split(',')
self.GPS['DateTime']['utc'] = self._toFloat(RMC[1])
self.GPS['Warning'] = RMC[2]
_knots = self._toFloat(RMC[7])
self.GPS['Speed']['knots'] = self.GPS['Speed']['kmh'] = self.GPS['Speed']['mph'] = self.GPS['Speed']['mps'] = None
if _knots != None:
self.GPS['Speed']['knots'] = _knots
self.GPS['Speed']['kmh'] = _knots * 1.85200000
self.GPS['Speed']['mph'] = _knots * 1.15077945
self.GPS['Speed']['mps'] = _knots * 0.51444444
self.GPS['Direction'] = self._toFloat(RMC[8])
self.GPS['DateTime']['date'] = self._toInt(RMC[9])
isChanged = True
#if isChanged:
r = requests.post(self.restDbUrl+'/post/GPS', data=json.dumps(self.GPS), headers={'Content-Type': 'application/json'})
if r.status_code != 200:
self._writeErr(r.text)
time.sleep(.2)
def begin(self):
self._writeLog("Starting(%s)..." % self.pidfile)
try:
self.__hislog = None
if (self.history != None):
self.__hislog = open(self.history, 'w')
except:
self._writeErr("Exception creating history file %s" % self.history)
self.stop()
try:
self._writeLog("Opening port %s" % self.device)
self.__ser = serial.Serial(port=self.device, baudrate=self.baud, timeout=self.timeout)
if (self.__ser != None):
self._writeLog("Opened...")
except:
self._writeErr("Exception opening port %s" % self.device)
self.stop()
def end(self):
if (self.__ser != None):
self.__ser.close()
if (self.__hislog != None):
self.__hislog.close()
del self.__ser
del self.__hislog
self._writeLog("Exiting...")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: %s start|stop|restart|gmaps|json|pjson|location" % sys.argv[0])
sys.exit(2)
f = open('gpsd.config', 'r')
s = f.read()
__config = json.loads(s)
f.close()
__device = '/dev/ttyUSB0'
if 'device' in __config:
__device = __config['device']
__baud = 4800
if 'baud' in __config:
__baud = __config['baud']
__log = '/var/log/gpsd.log'
if 'log' in __config:
__log = __config['log']
__errlog = '/var/log/gpsd.error.log'
if 'errlog' in __config:
__errlog = __config['errlog']
__history = None
if 'history' in __config:
__history = __config['history']
__dbUrl = '127.0.0.1:666'
if 'RestDB' in __config:
__dbUrl = 'http://' + __config['RestDB']
__dbUrlPass = None
daemon = MyDaemon('/var/run/gpsd.pid', '/dev/null', __log, __errlog, __device, __baud, __history, __dbUrl, __dbUrlPass)
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
elif 'gmaps' == sys.argv[1]:
r = requests.get(__dbUrl+'/GPS')
_json = json.loads(r.text)
url = 'https://maps.google.com?q={Lat},{Lon}'.format(**_json)
print url
elif 'location' == sys.argv[1]:
r = requests.get(__dbUrl+'/GPS')
_json = json.loads(r.text)
loc = "Lat: {Lat}\r\nLon: {Lon}\r\nAlt: {Alt}".format(**_json)
print loc
elif 'json' == sys.argv[1]:
r = requests.get(__dbUrl+'/GPS')
print r.text
elif 'pjson' == sys.argv[1]:
r = requests.get(__dbUrl+'/GPS?pjson')
print r.text
else:
print("Unknown command")
sys.exit(2)
sys.exit(0)