summaryrefslogtreecommitdiff
path: root/gps.py
blob: 6670195ad298178d1e144a30781f22fa3230b7c4 (plain)
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/env python
#
# gps.py -- Python interface to GPSD.
#
import time, socket, sys
from math import *

STATUS_NO_FIX = 0
STATUS_FIX = 1
STATUS_DGPS_FIX = 2
MODE_NO_FIX = 1
MODE_2D = 2
MODE_3D = 3
MAXCHANNELS = 12
SIGNAL_STRENGTH_UNKNOWN = -1

NMEA_MAX = 82

class gpsdata:
    "Position, track, velocity and status information returned by a GPS."

    class timestamp:
	def __init__(self, now):
	    self.last_refresh = now
	    self.changed = False
	def refresh(self):
	    self.last_refresh = time.time()
	def seen(self):
	    return self.last_refresh
	def __repr__(self):
	    return "{lr=%d, changed=%s}" % (self.last_refresh, self.changed)
    class satellite:
	def __init__(self, PRN, elevation, azimuth, ss, used=None):
	    self.PRN = PRN
	    self.elevation = elevation
	    self.azimuth = azimuth
	    self.ss = ss
	    self.used = used
	def __repr__(self):
	    return "PRN: %3d  E: %3d  Az: %3d  Ss: %d Used: %s" % (self.PRN,self.elevation,self.azimuth,self.ss,"ny"[self.used])

    def __init__(self):
	# Initialize all data members 
	self.online = False			# True if GPS on, False if not
	self.online_stamp = gps.timestamp(0)

        self.utc = ""

	self.latitude = self.longitude = 0.0
	self.latlon_stamp = gps.timestamp(0)

	self.altitude = 0.0			# Meters
	self.altitude_stamp = gps.timestamp(0)

	self.speed = 0.0			# Knots
	self.speed_stamp = gps.timestamp(0)

	self.track = 0.0			# Degrees from true north
	self.track_stamp = gps.timestamp(0)

	self.status = STATUS_NO_FIX
	self.status_stamp = gps.timestamp(0)

	self.mode = MODE_NO_FIX
	self.mode_stamp = gps.timestamp(0)

	self.satellites_used = 0		# Satellites used in last fix
	self.pdop = self.hdop = self.vdop = 0.0
	self.fix_quality_stamp = gps.timestamp(0)

	self.satellites = []			# satellite objects in view
	self.satellite_stamp = gps.timestamp(0)
        self.await = self.parts = 0

        self.gps_id = None

        self.profiling = False
        self.tag = ""
        self.length = 0
        self.d_recv_time = 0
        self.d_decode_time = 0
        self.emit_time = 0
        self.poll_time = 0
        self.c_recv_time = 0
        self.c_decode_time = 0
        self.baudrate = 0
        self.stopbits = 0
        self.cycle = 0

        __setattr__ = setattr

    def setattr(self, name, value):
        # Make sure the change stamp for each field is kept up to date
        group = {'online':'online_stamp',
	         #'latitude':'latlon_stamp'),
                 #'longitude':'latlon_stamp',
                 'altitude':'altitude_stamp',
                 'speed':'speed_stamp',
                 'track':'track_stamp',
                 'status':'status_stamp',
                 'mode':'mode_stamp',
                 #'pdop':'fix_quality_stamp',
                 #'hdop':'fix_quality_stamp',
                 #'vdop':'fix_quality_stamp',
                 'satellites':'satellite_stamp',
                 }
        if field in group:
            stamp = getattr(self, group[field])
            stamp.changed = (getattr(self, field) != value)
            stamp.refresh()
        self.__dict__[name] = value

    def __repr__(self):
	st = ""
	st += "Lat/lon:  %f %f " % (self.latitude, self.longitude)
	st += repr(self.latlon_stamp) + "\n"
	st += "Altitude: %f " % (self.altitude)
	st += repr(self.altitude_stamp) + "\n"
	st += "Speed:    %f " % (self.speed)
	st += repr(self.speed_stamp) + "\n"
	st += "Track:    %f " % (self.track)
	st += repr(self.track_stamp) + "\n"
	st += "Status:   STATUS_%s" % ("NO_FIX", "FIX","DGPS_FIX")[self.status]
	st += " " +repr(self.status_stamp) + "\n"
	st += "Mode:     MODE_" + ("ZERO", "NO_FIX", "2D","3D")[self.mode]
	st += " " + repr(self.mode_stamp) + "\n"
	st += "Quality:  %d p=%2.2f h=%2.2f v=%2.2f " % \
              (self.satellites_used, self.pdop, self.hdop, self.vdop)
	st += repr(self.fix_quality_stamp) + "\n"
	st += "Y: %s satellites in view:\n" % len(self.satellites)
	for sat in self.satellites:
	  st += "    " + repr(sat) + "\n"
	st += "    " + repr(self.satellite_stamp) + "\n"
	return st

class gps(gpsdata):
    "Client interface to a running gpsd instance."
    def __init__(self, host="localhost", port="2947", verbose=0):
	gpsdata.__init__(self)
	self.sock = None	# in case we blow up in connect
	self.sockfile = None
	self.connect(host, port)
        self.verbose = verbose
	self.raw_hook = None

    def connect(self, host, port):
        """Connect to a host on a given port.

        If the hostname ends with a colon (`:') followed by a number, and
        there is no port specified, that suffix will be stripped off and the
        number interpreted as the port number to use.
        """
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i+1:]
                try: port = int(port)
                except ValueError:
                    raise socket.error, "nonnumeric port"
        if not port: port = SMTP_PORT
        #if self.debuglevel > 0: print 'connect:', (host, port)
        msg = "getaddrinfo returns an empty list"
        self.sock = None
        self.sockfile = None
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                #if self.debuglevel > 0: print 'connect:', (host, port)
                self.sock.connect(sa)
                self.sockfile = self.sock.makefile()
            except socket.error, msg:
                #if self.debuglevel > 0: print 'connect fail:', (host, port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                self.sockfile = None
                continue
            break
        if not self.sock:
            raise socket.error, msg

    def set_raw_hook(self, hook):
        self.raw_hook = hook

    def __del__(self):
	if self.sock:
	    self.sock.close()
        self.sock = None
        self.sockfile = None

    def __unpack(self, buf):
	# unpack a daemon response into the instance members
        self.utc = "?"
	fields = buf.strip().split(",")
	if fields[0] == "GPSD":
	  for field in fields[1:]:
	    if not field or field[1] != '=':
	      continue
	    cmd = field[0]
	    data = field[2:]
	    if data[0] == "?":
		continue
	    if cmd in ('A', 'a'):
	      d1 = float(data)
	      self.altitude_stamp.changed = (self.altitude != d1)
	      self.altitude = d1
	      self.altitude_stamp.refresh()
	    elif cmd in ('B', 'b'):
              (f1, f2, f3, f4) = data.split()
              self.baudrate = int(f1)
              self.stopbits = int(f4)
	    elif cmd in ('C', 'c'):
	      self.cycle = int(data)
	    elif cmd in ('D', 'd'):
	      self.utc = data
	    elif cmd in ('I', 'i'):
	      self.gps_id = data
	    elif cmd in ('M', 'm'):
	      i1 = int(data)
	      self.mode_stamp.changed = (self.mode != i1)
	      self.mode = i1
	      self.mode_stamp.refresh()
	    elif cmd in ('P', 'p'):
	      (f1, f2) = map(float, data.split())
	      self.latlon_stamp.changed = (self.latitude != f1 or self.longitude != f2)
	      self.latitude = f1
	      self.longitude = f2
	      self.latlon_stamp.refresh()
	    elif cmd in ('Q', 'q'):
	      parts = data.split()
	      i1 = int(parts[0])
	      (f1, f2, f3) = map(float, parts[1:])
	      self.fix_quality_stamp.changed = (self.pdop != f1 or self.hdop != f2 or self.vdop != f3)
	      self.satellites_used = i1
	      self.pdop = f1
	      self.hdop = f2
	      self.vdop = f3
	      self.fix_quality_stamp.refresh()
	    elif cmd in ('S', 's'):
	      i1 = int(data)
	      self.status_stamp.changed = (self.status != i1)
	      self.status = i1
	      self.status_stamp.refresh()
	    elif cmd in ('T', 't'):
	      d1 = float(data)
	      self.track_stamp.changed = (self.track != d1)
	      self.track = d1
	      self.track_stamp.refresh()
	    elif cmd in ('V', 'v'):
	      d1 = float(data)
	      self.speed_stamp.changed = (self.speed != d1)
	      self.speed = d1
	      self.speed_stamp.refresh()
	    elif cmd in ('X', 'x'):
	      b1 = data[0] == '1'
	      self.online_stamp.changed = (b1 != self.online)
	      self.online = b1
	      self.online_stamp.refresh()
	    elif cmd in ('Y', 'y'):
	      satellites = data.split(":")
	      d1 = int(satellites.pop(0))
	      newsats = []
	      for i in range(d1):
		newsats.append(gps.satellite(*map(int, satellites[i].split())))
	      self.satellite_stamp.changed = (self.satellites) != newsats
	      self.satellites = newsats
	      self.satellite_stamp.refresh() 
	    elif cmd in ('Z', 'z'):
              self.profiling = (data[0] == '1')
            elif cmd == '$':
                  (self.tag, length, gps_time, xmit_time, recv_time, decode_time, poll_time, emit_time) = data.split()
                  self.length = int(length)
                  self.gps_time = float(gps_time)
                  self.d_xmit_time = float(xmit_time)
                  self.d_recv_time = float(recv_time)
                  self.d_decode_time = float(decode_time)
                  self.poll_time = float(poll_time)
                  self.emit_time = float(emit_time)
	if self.raw_hook:
	    self.raw_hook(buf);
	return self.online_stamp.changed \
	    or self.latlon_stamp.changed \
	    or self.altitude_stamp.changed \
	    or self.speed_stamp.changed \
	    or self.track_stamp.changed \
	    or self.fix_quality_stamp.changed \
	    or self.fix_quality_stamp.changed \
	    or self.status_stamp.changed \
	    or self.mode_stamp.changed \
	    or self.satellite_stamp.changed 

    def poll(self):
	"Wait for and read data being streamed from gpsd."
        data = self.sockfile.readline()
        if not data:
            return None
        if self.verbose:
            sys.stderr.write("GPS DATA %s\n" % repr(data))
        if self.profiling:
            self.c_recv_time = time.time()
	res = self.__unpack(data)
        if self.utc != "?":
            if self.profiling:
                self.c_decode_time = time.time()
                self.c_recv_time -= self.gps_time
                self.c_decode_time -= self.gps_time
        return res

    def query(self, commands):
	"Send a command, get back a response."
 	self.sockfile.write(commands)
 	self.sockfile.flush()
	return self.poll()

# some multipliers for interpreting GPS output
METERS_TO_FEET	= 3.2808399
METERS_TO_MILES	= 0.00062137119
KNOTS_TO_MPH	= 1.1507794

# EarthDistance code swiped from Kismet and corrected
# (As yet, this stuff is not in the libgps C library.)

def Deg2Rad(x):
    "Degrees to radians."
    return x * (pi/180)

def CalcRad(lat):
    "Radius of curvature in meters at specified latitude."
    a = 6378.137
    e2 = 0.081082 * 0.081082
    # the radius of curvature of an ellipsoidal Earth in the plane of a
    # meridian of latitude is given by
    #
    # R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2)
    #
    # where a is the equatorial radius,
    # b is the polar radius, and
    # e is the eccentricity of the ellipsoid = sqrt(1 - b^2/a^2)
    #
    # a = 6378 km (3963 mi) Equatorial radius (surface to center distance)
    # b = 6356.752 km (3950 mi) Polar radius (surface to center distance)
    # e = 0.081082 Eccentricity
    sc = sin(Deg2Rad(lat))
    x = a * (1.0 - e2)
    z = 1.0 - e2 * sc * sc
    y = pow(z, 1.5)
    r = x / y

    r = r * 1000.0	# Convert to meters
    return r

def EarthDistance((lat1, lon1), (lat2, lon2)):
    "Distance in meters between two points specified in degrees."
    x1 = CalcRad(lat1) * cos(Deg2Rad(lon1)) * sin(Deg2Rad(90-lat1))
    x2 = CalcRad(lat2) * cos(Deg2Rad(lon2)) * sin(Deg2Rad(90-lat2))
    y1 = CalcRad(lat1) * sin(Deg2Rad(lon1)) * sin(Deg2Rad(90-lat1))
    y2 = CalcRad(lat2) * sin(Deg2Rad(lon2)) * sin(Deg2Rad(90-lat2))
    z1 = CalcRad(lat1) * cos(Deg2Rad(90-lat1))
    z2 = CalcRad(lat2) * cos(Deg2Rad(90-lat2))
    a = (x1*x2 + y1*y2 + z1*z2)/pow(CalcRad((lat1+lat2)/2),2)
    # a should be in [1, -1] but can sometimes fall outside it by
    # a very small amount due to rounding errors in the preceding
    # calculations (this is prone to happen when the argument points
    # are very close together).  Thus we constrain it here.
    if abs(a) > 1: a = 1
    elif a < -1: a = -1
    return CalcRad((lat1+lat2) / 2) * acos(a)

def MeterOffset((lat1, lon1), (lat2, lon2)):
    "Return offset in meters of second arg from first."
    dx = EarthDistance((lat1, lon1), (lat1, lon2))
    dy = EarthDistance((lat1, lon1), (lat2, lon1))
    if lat1 < lat2: dy *= -1
    if lon1 < lon2: dx *= -1
    return (dx, dy)

def isotime(s):
    "Convert timestamps in ISO8661 format to and from Unix local time."
    if type(s) == type(1):
        return time.strftime(time.localtime(s), "%Y-%m-%dT%H:%M:%S")
    elif type(s) == type(1.0):
        date = int(s)
        msec = s - date
        date = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(s))
        return date + "." + `msec`[2:]
    elif type(s) == type(""):
        gmt = s[-1] == "Z"
        if gmt:
            s = s[:-1]
        if "." in s:
            (date, msec) = s.split(".")
        else:
            date = s
            msec = "0"
        unpacked = time.strptime(date, "%Y-%m-%dT%H:%M:%S")
        seconds = time.mktime(unpacked)
        if gmt:
            if time.daylight and time.localtime().tm_isdst:
                seconds -= time.altzone
            else:
                seconds -= time.timezone
        return seconds + float("0." + msec)
    else:
        raise TypeError

if __name__ == '__main__':
    import sys,readline
    print "This is the exerciser for the Python gps interface."
    session = gps()
    session.set_raw_hook(lambda s: sys.stdout.write(s + "\n"))
    try:
        while True:
            commands = raw_input("> ")
            session.query(commands)
            print session
    except EOFError:
        print "Goodbye!"
    del session

# gps.py ends here