from pynmea import nmea
import serial
import os
from WGS84ToGCJ02 import transform
from WGS84Distance import distance

#import threading

#class ThreadWorker(threading.Thread):
    #def __init__(self, callable, *args, **kwargs):
        #super(ThreadWorker, self).__init__()
        #self.callable = callable
        #self.args = args
        #self.kwargs = kwargs

    #def run(self):
        #self.callable(*self.args, **self.kwargs)

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

def decodeNMEAStream(serialport,GCJ02=False):
    while True:
        line = serialport.readline()
        if(line[4] == 'G'): # $GPGGA
            if(len(line) > 50):
                #print line
                gpgga = nmea.GPGGA()
                gpgga.parse(line)
                lats = gpgga.latitude
                longs = gpgga.longitude
                
                #convert degrees,decimal minutes to decimal degrees 
                _lat = (float(lats[2]+lats[3]+lats[4]+lats[5]+lats[6]+lats[7]+lats[8]))/60
                lat = (float(lats[0]+lats[1])+_lat)
                _long = (float(longs[3]+longs[4]+longs[5]+longs[6]+longs[7]+longs[8]+longs[9]))/60
                longs = (float(longs[0]+longs[1]+longs[2])+_long)

            if GCJ02:
                return transform(lat,longs)
            else:
                return (lat,longs)

if __name__ == "__main__":
    ser = serial.Serial("COM2",38400)

    origin_position = ()
    current_position = ()

    origin_position = decodeNMEAStream(ser,GCJ02=True)
    while True:
        current_position = decodeNMEAStream(ser,GCJ02=True)
        print current_position,
        print "distance:",distance(origin_position,current_position)*1000,'m'

@@ -1475,31 +1475,62 @@
 ()%0A%0A    
+_avg = 5%0A    print 'Average %25d 
 origin
-_
+ 
 position
  = decod
@@ -1525,43 +1525,252 @@
 tion
- = decodeNMEAStream(ser,GCJ02=True)
+'%25_avg,%0A    _x = 0%0A    _y = 0%0A    for i in range(_avg):%0A        _p = decodeNMEAStream(ser,GCJ02=False)%0A        _x += _p%5B0%5D%0A        _y += _p%5B1%5D%0A        print '.',%0A    x = _x / _avg%0A    y = _y / _avg %0A    origin_position = (x,y)%0A    print 'done'%0A
 %0A   
@@ -1836,19 +1836,20 @@
 r,GCJ02=
-Tru
+Fals
 e)%0A     

add average of origin position