summaryrefslogtreecommitdiff
path: root/gps.py
blob: fb5f99453a203567814e9834f0acba2299b704b9 (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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#!/usr/bin/env python
# $Id$
#
# gps.py -- Python interface to GPSD.
#
import time, calendar, math, socket, sys, select, json

api_major_version = 3   # bumped on incompatible changes
api_minor_version = 1   # bumped on compatible changes

NaN = float('nan')
def isnan(x): return str(x) == 'nan'

# Don't hand-hack this list, it's generated.
# Not all of these are actually used in the Python client code.
ONLINE_SET     	= 0x00000001
TIME_SET       	= 0x00000002
TIMERR_SET     	= 0x00000004
LATLON_SET     	= 0x00000008
ALTITUDE_SET   	= 0x00000010
SPEED_SET      	= 0x00000020
TRACK_SET      	= 0x00000040
CLIMB_SET      	= 0x00000080
STATUS_SET     	= 0x00000100
MODE_SET       	= 0x00000200
DOP_SET        	= 0x00000400
VERSION_SET    	= 0x00000800
HERR_SET       	= 0x00001000
VERR_SET       	= 0x00002000
PERR_SET       	= 0x00004000
POLICY_SET     	= 0x00020000
ERR_SET        	= (HERR_SET|VERR_SET|PERR_SET)
SATELLITE_SET  	= 0x00040000
RAW_SET        	= 0x00080000
USED_SET       	= 0x00100000
SPEEDERR_SET   	= 0x00200000
TRACKERR_SET   	= 0x00400000
CLIMBERR_SET   	= 0x00800000
DEVICE_SET     	= 0x01000000
DEVICELIST_SET 	= 0x02000000
DEVICEID_SET   	= 0x04000000
ERROR_SET      	= 0x08000000
RTCM2_SET      	= 0x10000000
RTCM3_SET      	= 0x20000000
AIS_SET        	= 0x40000000
FIX_SET        	= (TIME_SET|MODE_SET|TIMERR_SET|LATLON_SET|HERR_SET|ALTITUDE_SET|VERR_SET|TRACK_SET|TRACKERR_SET|SPEED_SET|SPEEDERR_SET|CLIMB_SET|CLIMBERR_SET)

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 = NaN

WATCH_DISABLE	= 0x00
WATCH_ENABLE	= 0x01
WATCH_NMEA	= 0x02
WATCH_RAW	= 0x04
WATCH_SCALED	= 0x08
WATCH_NEWSTYLE	= 0x10

GPSD_PORT = 2947

class gpstimings:
    def __init__(self):
        self.sentence_tag = ""
        self.sentence_length = 0
        self.sentence_time = 0.0
        self.d_xmit_time = 0.0
        self.d_recv_time = 0.0
        self.d_decode_time = 0.0
        self.emit_time = 0.0
        self.poll_time = 0.0
        self.c_recv_time = 0.0
        self.c_decode_time = 0.0
    def d_received(self):
        if self.sentence_time:
            return self.d_recv_time + self.sentence_time
        else:
            return self.d_recv_time + self.d_xmit_time
    def collect(self, tag, length, sentence_time, xmit_time, recv_time, decode_time, poll_time, emit_time):
        self.sentence_tag = tag
        self.sentence_length = int(length)
        self.sentence_time = float(sentence_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)
    def __str__(self):
        return "%s\t%2d\t%2.6f\t%2.6f\t%2.6f\t%2.6f\t%2.6f\t%2.6f\t%2.6f\t%2.6f\n" % (
            self.sentence_tag,
            self.sentence_length,
            self.sentence_time,
            self.d_xmit_time,
            self.d_recv_time,
            self.d_decode_time,
            self.poll_time,
            self.emit_time,
            self.c_recv_time,
            self.c_decode_time
        )

class version:
    def __init__(self, **kw):
        self.__dict__.update(kw)
    def __repr__(self):
        return "<version: release='%(release)s', proto=%(proto_major)s.%(proto_minor)s, rev='%(rev)s'>" % self.__dict__

class device:
    def __init__(self):
        self.path = None
        self.activated = 0
        self.subtype = None
        self.driver_mode = 0
        self.bps = 0
        self.serialmode = '8N1'
        self.cycle = 0
        self.mincycle = 0
    def __repr__(self):
        return "<device path='%(path)s, activated=%(activated)s', bps=%(bps)s, serialmode=%(serialmode)s>" % self.__dict__

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: %3d  Used: %s" % (
            self.PRN, self.elevation, self.azimuth, self.ss, "ny"[self.used]
        )

class skyview:
    def __init__(self):
        self.satellites = []
        self.satellites_used = 0        # Satellites used in last fix
        self.xdop = self.ydop = self.pdop = self.hdop = self.vdop = self.tdop = self.gdop = 0.0
    def __repr__(self):
        st = "Quality:  %d x=%2.2f y=%2.2f p=%2.2f h=%2.2f v=%2.2f t=%2.2f g=%2.2f\n" % \
              (self.satellites_used, self.xdop, self.ydop, self.pdop, self.hdop, self.vdop, self.tdop, self.gdop)
        st += "Y: %s satellites in view:\n" % len(self.satellites)
        for sat in self.satellites:
          st += "    %r\n" % sat
        return st

class gpsfix:
    def __init__(self):
        self.mode = MODE_NO_FIX
        self.time = NaN
        self.ept = NaN
        self.latitude = self.longitude = 0.0
        self.epx = NaN
        self.epy = NaN
        self.altitude = NaN         # Meters
        self.epv = NaN
        self.track = NaN            # Degrees from true north
        self.speed = NaN            # Knots
        self.climb = NaN            # Meters per second
        self.epd = NaN
        self.eps = NaN
        self.epc = NaN
    def __repr__(self):
        st = "Time:     %s (%s)\n" % (isotime(self.time), self.time)
        st += "Lat/Lon:  %f %f\n" % (self.latitude, self.longitude)
        if isnan(self.altitude):
            st += "Altitude: ?\n"
        else:
            st += "Altitude: %f\n" % (self.altitude)
        if isnan(self.speed):
            st += "Speed:    ?\n"
        else:
            st += "Speed:    %f\n" % (self.speed)
        if isnan(self.track):
            st += "Track:    ?\n"
        else:
            st += "Track:    %f\n" % (self.track)
        return st

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

    def __init__(self):
        # Initialize all data members 
        self.online = 0                 # NZ if GPS on, zero if not

        self.valid = 0
        self.fix = gpsfix()

        self.status = STATUS_NO_FIX
        self.utc = ""

        self.epe = 0.0

        self.satellites = skyview()            # satellite objects in view
        self.await = self.parts = 0

        self.profiling = False
        self.timings = gpstimings()
        self.device = device()

        self.devices = []

    def __repr__(self):
        st = repr(self.fix)
        st += "Status:   STATUS_%s\n" % ("NO_FIX", "FIX", "DGPS_FIX")[self.status]
        st += "Mode:     MODE_%s\n" % ("ZERO", "NO_FIX", "2D", "3D")[self.fix.mode]
        st += "Quality:  %d p=%2.2f h=%2.2f v=%2.2f t=%2.2f g=%2.2f\n" % \
              (self.satellites_used, self.pdop, self.hdop, self.vdop, self.tdop, self.gdop)
        st += "Y: %s satellites in view:\n" % len(self.satellites)
        for sat in self.satellites:
          st += "    %r\n" % sat
        return st

class gps(gpsdata):
    "Client interface to a running gpsd instance."
    def __init__(self, host="127.0.0.1", 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 __iter__(self):
        return self

    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 = GPSD_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)
                self.close()
                continue
            break
        if not self.sock:
            raise socket.error, msg

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

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

    def __del__(self):
        self.close()

    def __oldstyle_unpack(self, buf):
        # unpack a daemon response into the instance members
        self.fix.time = 0.0
        fields = buf.strip().split(",")
        if fields[0] == "GPSD":
            for field in fields[1:]:
                if not field or field[1] != '=':
                    continue
                cmd = field[0].upper()
                data = field[2:]
                if data[0] == "?":
                    continue
                if cmd == 'A':
                    self.fix.altitude = float(data)
                    self.valid |= ALTITUDE_SET
                elif cmd == 'B':
                    parts = data.split()
                    self.device.bps = int(parts[0])
                    self.device.serialmode = parts[1]+parts[2]+parts[3]
                elif cmd == 'C':
                    parts = data.split()
                    if len(parts) == 2:
                        (self.device.cycle, self.device.mincycle) = map(float, parts)
                    else:
                        self.device.mincycle = self.device.cycle = float(data)
                elif cmd == 'D':
                    self.utc = data
                    self.fix.time = isotime(self.utc)
                    self.valid |= TIME_SET
                elif cmd == 'E':
                    parts = data.split()
                    (self.epe, eph, self.fix.epv) = map(float, parts)
                    self.epx = self.epy = eph
                    self.valid |= HERR_SET | VERR_SET | PERR_SET
                elif cmd == 'F':
                    self.device = data
                elif cmd == 'I':
                    self.gps_id = data
                elif cmd == 'K':
                    self.devices = data[1:].split()
                elif cmd == 'M':
                    self.fix.mode = int(data)
                    self.valid |= MODE_SET
                elif cmd == 'N':
                    self.device.driver_mode = int(data)
                elif cmd == 'O':
                    fields = data.split()
                    if fields[0] == '?':
                        self.fix.mode = MODE_NO_FIX
                    else:
                        self.timings.sentence_tag = fields[0]
                        def default(i, vbit=0, cnv=float):
                            if fields[i] == '?':
                                return NaN
                            else:
                                try:
                                    value = cnv(fields[i])
                                except ValueError:
                                    return NaN
                                self.valid |= vbit
                                return value
                        # clear all valid bits that might be set again below
                        self.valid &= ~(
                            TIME_SET | TIMERR_SET | LATLON_SET | ALTITUDE_SET |
                            HERR_SET | VERR_SET | TRACK_SET | SPEED_SET |
                            CLIMB_SET | SPEEDERR_SET | CLIMBERR_SET | MODE_SET
                        )
                        self.utc = fields[1]
                        self.fix.time = default(1, TIME_SET)
                        if not isnan(self.fix.time):
                            self.utc = isotime(self.fix.time)
                        self.fix.ept = default(2, TIMERR_SET)
                        self.fix.latitude = default(3, LATLON_SET)
                        self.fix.longitude = default(4)
                        self.fix.altitude = default(5, ALTITUDE_SET)
                        self.fix.epx = self.epy = default(6, HERR_SET)
                        self.fix.epv = default(7, VERR_SET)
                        self.fix.track = default(8, TRACK_SET)
                        self.fix.speed = default(9, SPEED_SET)
                        self.fix.climb = default(10, CLIMB_SET)
                        self.fix.epd = default(11)
                        self.fix.eps = default(12, SPEEDERR_SET)
                        self.fix.epc = default(13, CLIMBERR_SET)
                        if len(fields) > 14:
                            self.fix.mode = default(14, MODE_SET, int)
                        else:
                            if self.valid & ALTITUDE_SET:
                                self.fix.mode = MODE_2D
                            else:
                                self.fix.mode = MODE_3D
                            self.valid |= MODE_SET
                elif cmd == 'P':
                    (self.fix.latitude, self.fix.longitude) = map(float, data.split())
                    self.valid |= LATLON_SET
                elif cmd == 'Q':
                    parts = data.split()
                    self.satellites.satellites_used = int(parts[0])
                    (self.skyview.pdop, self.skyview.hdop, \
                     self.skyview.vdop, self.skyview.tdop, \
                     self.skyview.gdop) = map(float, parts[1:])
                    self.valid |= DOP_SET | USED_SET
                elif cmd == 'S':
                    self.status = int(data)
                    self.valid |= STATUS_SET
                elif cmd == 'T':
                    self.fix.track = float(data)
                    self.valid |= TRACK_SET
                elif cmd == 'U':
                    self.fix.climb = float(data)
                    self.valid |= CLIMB_SET
                elif cmd == 'V':
                    self.fix.speed = float(data)
                    self.valid |= SPEED_SET
                elif cmd == 'X':
                    self.online = float(data)
                    self.valid |= ONLINE_SET
                elif cmd == 'Y':
                    satellites = data.split(":")
                    prefix = satellites.pop(0).split()
                    self.timings.sentence_tag = prefix.pop(0)
                    self.timings.sentence_time = prefix.pop(0)
                    if self.timings.sentence_time != "?":
                        self.timings.sentence_time = float(self.timings.sentence_time)
                    d1 = int(prefix.pop(0))
                    newsats = []
                    for i in range(d1):
                        newsats.append(gps.satellite(*map(int, satellites[i].split())))
                    self.satellites = newsats
                    self.valid |= SATELLITE_SET
                elif cmd == 'Z':
                    self.profiling = (data[0] == '1')
                elif cmd == '$':
                    self.timings.collect(*data.split())
        return self.valid

    def __json_unpack(self, buf):
        def asciify(d):
            "De-Unicodify everything so we can copy dicts into Python objects."
            t = {}
            for (k, v) in d.items():
                ka = k.encode("ascii")
                if type(v) == type(u"x"):
                    va = v.encode("ascii")
                elif type(v) == type({}):
                    va = asciify(v)
                elif type(v) == type([]):
                    va = map(asciify, v)
                else:
                    va = v
                t[ka] = va
            return t
        def default(k, dflt, vbit=0):
            if k not in self.data:
                return dflt
            else:
                self.valid |= vbit
                return self.data[k]
        self.data = asciify(json.loads(buf, encoding="ascii"))
        if self.data.get("class") == "VERSION":
            self.valid = ONLINE_SET | VERSION_SET
            self.version = version(**self.data)
            self.version.gpsdata = self
            return self.version
        elif self.data.get("class") == "DEVICE":
            self.valid = ONLINE_SET | DEVICE_SET
            self.device = device()
            self.device.gpsdata = self
            self.device.path        = self.data["path"]
            self.device.activated   = default("activated", None) 
            self.device.subtype     = default("subtype", None, DEVICEID_SET) 
            self.device.driver_mode = default("native", 0)
            self.device.serialmode  = default("serialmode", "8N1")
            self.device.cycle       = default("cycle",    NaN)
            self.device.mincycle    = default("mincycle", NaN)
            return self.device
        elif self.data.get("class") == "TPV":
            self.fix.gpsdata = self
            self.timings.sentence_tag = self.data["tag"]
            # clear all valid bits that might be set again below
            self.valid &= ~(
                TIME_SET | TIMERR_SET | LATLON_SET | ALTITUDE_SET |
                HERR_SET | VERR_SET | TRACK_SET | SPEED_SET |
                CLIMB_SET | SPEEDERR_SET | CLIMBERR_SET | MODE_SET
            )
            self.utc = None
            self.fix.time = default("time", NaN, TIME_SET)
            if not isnan(self.fix.time):
                self.utc = isotime(self.fix.time)
            self.fix.ept =       default("ept",   NaN, TIMERR_SET)
            self.fix.latitude =  default("lat",   NaN, LATLON_SET)
            self.fix.longitude = default("lon",   NaN)
            self.fix.altitude =  default("alt",   NaN, ALTITUDE_SET)
            self.fix.epx =       default("epx",   NaN, HERR_SET)
            self.fix.epy =       default("epy",   NaN, HERR_SET)
            self.fix.epv =       default("epv",   NaN, VERR_SET)
            self.fix.track =     default("track", NaN, TRACK_SET)
            self.fix.speed =     default("speed", NaN, SPEED_SET)
            self.fix.climb =     default("climb", NaN, CLIMB_SET)
            self.fix.epd =       default("epd",   NaN)
            self.fix.eps =       default("eps",   NaN, SPEEDERR_SET)
            self.fix.epc =       default("epc",   NaN, CLIMBERR_SET)
            self.fix.mode =      default("mode",  0,   MODE_SET)
            return self.fix
        elif self.data.get("class") == "SKY":
            self.skyview = skyview()
            self.skyview.gpsdata = self
            for attrp in "xyvhpg":
                setattr(self.skyview, attrp+"dop", default(attrp+"dop", NaN, DOP_SET))
            if "satellites" in self.data:
                for sat in self.data['satellites']:
                    self.skyview.satellites.append(satellite(PRN=sat['PRN'], elevation=sat['el'], azimuth=sat['az'], ss=sat['ss'], used=sat['used']))
            self.skyview.used = 0
            for sat in self.skyview.satellites:
                if sat.used:
                    self.skyview.used += 1
            return self.skyview
        else:
            # Other classes, including RTCM2, AIS, WATCH and DEVICELIST,
            # fall through to here.
            return self.data

    def waiting(self):
        "Return True if data is ready for the client."
        (winput, woutput, wexceptions) = select.select((self.sock,), (), (), 0)
        return winput != []

    def next(self):
        "Get the next response object from gpsd abd return it."
        self.response = self.sockfile.readline()
        if self.response.startswith("H") and "=" not in self.response:
            while True:
                frag = self.sockfile.readline()
                self.response += frag
                if frag.startswith("."):
                    break
        if not self.response:
            raise StopIteration
        if self.verbose:
            sys.stderr.write("GPS-DATA %s\n" % repr(self.response))
        self.timings.c_recv_time = time.time()
        if self.raw_hook:
            self.raw_hook(self.response);
        if self.response.startswith("{") and "class" in self.response:
            data = self.__json_unpack(self.response)
        else:
            data = self.__oldstyle_unpack(self.response)
        if self.profiling:
            if self.timings.sentence_time != '?':
                basetime = self.timings.sentence_time
            else:
                basetime = self.timings.d_xmit_time
            self.timings.c_decode_time = time.time() - basetime
            self.timings.c_recv_time -= basetime
        return data

    def poll(self):
        "Poll for data from the GPS."
        try:
            self.next()
            return 0
        except StopIteration:
            return -1

    def send(self, commands):
        "Ship commands to the daemon."
        if not commands.endswith("\n"):
            commands += "\n"
        self.sock.send(commands)

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

    def stream(self, flags=0):
        "Ask gpsd to stream reports at your client."
        if flags & WATCH_NEWSTYLE:
            if flags & WATCH_ENABLE:
                arg = '?WATCH={"enable":true'
                if self.raw_hook or (flags & WATCH_NMEA):
                    arg += ',"nmea":true'
            elif flags & WATCH_DISABLE:
                arg = '?WATCH={"enable":false'
                if self.raw_hook or (flags & WATCH_NMEA):
                    arg += ',"nmea":false'
            return self.send(arg + "}")
        else:
            if flags & WATCH_ENABLE:
                arg = 'w+'
                if self.raw_hook or (flags & WATCH_NMEA):
                    arg += 'r+'
                    return self.send(arg)
            elif flags & WATCH_DISABLE:
                arg = "w-"
                if self.raw_hook or (flags & WATCH_NMEA):
                    arg += 'r-'
                    return self.send(arg)

# 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 * (math.pi/180)

def Rad2Deg(x):
    "Radians to degress."
    return x * (180/math.pi)

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 = math.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) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
    x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2))
    y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
    y2 = CalcRad(lat2) * math.sin(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2))
    z1 = CalcRad(lat1) * math.cos(Deg2Rad(90-lat1))
    z2 = CalcRad(lat2) * math.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) * math.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 time."
    if type(s) == type(1):
        return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
    elif type(s) == type(1.0):
        date = int(s)
        msec = s - date
        date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
        return date + "." + ("%.2f" % msec)[2:]
    elif type(s) == type(""):
        if s[-1] == "Z":
            s = s[:-1]
        if "." in s:
            (date, msec) = s.split(".")
        else:
            date = s
            msec = "0"
        # Note: no leap-second correction! 
        return calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%S")) + float("0." + msec)
    else:
        raise TypeError

if __name__ == '__main__':
    import readline, getopt
    (options, arguments) = getopt.getopt(sys.argv[1:], "w")
    streaming = False
    for (switch, val) in options:
        if (switch == '-w'):
            streaming = True    
    if len(arguments) > 2:
        print 'Usage: gps.py [host [port]]'
        sys.exit(1)

    if streaming:
        session = gps(*arguments)
        #session.set_raw_hook(lambda s: sys.stdout.write(s.strip() + "\n"))
        session.stream(WATCH_ENABLE | WATCH_NEWSTYLE)
        for event in session:
            print event
    else:
        print "This is the exerciser for the Python gps interface."
        session = gps(*arguments)
        #session.set_raw_hook(lambda s: sys.stdout.write(s.strip() + "\n"))
        try:
            while True:
                session.query(raw_input("> "))
                print session
        except EOFError:
            print "Goodbye!"
        del session

# gps.py ends here