简体   繁体   中英

Python GPS data capture

So I'm making an application using a GPS module , Python and a MySQL database .

So I have written some code, to try to capture the data from the GPS and store it in the database. I'm using a plugin called " pynmea2 " to parse some of the data (longitude and latitude). However, I need more data then that, so, I already tried ALOT different things, but my program keeps crashing the whole time. Could someone help me out with this?

Most of the time I get all the data from the Serial connection, but I want to be able to strip data from it. So example of what I get: [b'$GPGGA,093512.000,,,,,0,3,,,M,,M,,*47\\r\\n', b'$GPGLL,,,,,093512.000,V,N*76\\r\\n', b'$GPGSA,A,1,,,,,,,,,,,,,,,*1E\\r\\n', b'$GPGSV,3,1,11,15,72,214,,24,52,276,,13,48,141,,17,31,093,29*70\\r\\n', b'$GPGSV,3,2,11,18,28,292,,28,27,049,25,19,24,120,24,12,23,211,13*7E\\r\\n', b'$GPGSV,3

Well, it's not that simple to extract data from it,but it works out just fine with the pynmea2 library ( only library I'm allowed to use.

So, I need the speed, the latitude and longitude for now, but the speed is bothering me now. It gives ValueError: could not convert string to float: "22*49\\\\r\\\\n'" alot of times because I don't do a proper way of finding the data and then "parsing" it.

Here is my code I'm currently using;

from model.GPSParser import GPSParser
from model.DB import DB
import serial
import time
import datetime
import pynmea2

#########################################
# This is the main code to setup the
# serial connection with the GPS module.
# it needs to be OR runt as root OR as
# pi with all the root rights.
#########################################
port = "/dev/ttyAMA0"
ser = serial.Serial(port, 9600, timeout=0)

#########################################
# These are all the global variables
# to be used. All defined and set to
# zero or their standard 'Null' value.
#########################################
lat = 0.0
lon = 0.0
cur_speed = 0.0


while True:

    try:
        # Get the data from the serial monitor.
        data = str(ser.readlines()).lstrip("b'")[:-3]
        # print(data)

        #########################################
        # Find the speed, to check if we're
        # standing still or not. Save it in a
        # @var speed
        #########################################
        if data.find('$GPVTG') != -1:
            cur_speed = data.split(",")[7]

        #########################################
        # Get the Latitude and Longitude
        #########################################
        if data.find('$GPGGA') != -1:
            print(data)
            # Check whether the data strings are empty or not.
            if GPSParser.parseLatitude(data) != "" and GPSParser.parseLongitude(data) != "":
                lat = GPSParser.parseLatitude(data)
                lon = GPSParser.parseLongitude(data)
                # Debug printing
                # print("Latitude: " + GPSParser.parseLatitude(data))
                # print("Longitude: " + GPSParser.parseLongitude(data))
                # print("Speed: " + cur_speed)

        #########################################
        # Insert the coordinates into the database
        # Be sure to check of we are really driving
        # So when the speed is higher then 5 km/u
        # Store everything into the database.
        #########################################
        if float(cur_speed) > 5.0:
            db = DB()
            db.insertCoordinates(lat, lon, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        # Wait a bit to not overload the Serial port
        time.sleep(0.5)

    ############################################################
    # The error handling
    ############################################################
    except serial.serialutil.SerialException:
        ser.close()
        port = "/dev/ttyAMA0"
        ser = serial.Serial(port, 9600, timeout=0)
        continue
    except pynmea2.ParseError:
        # print("Error on parsing object, continuing...")
        continue
    except BlockingIOError:
        # print("Blocking I/O error, continuing...")
        continue
    except TypeError:
        # print("Type error, continuing...")
        continue
    except IndexError:
        # print("To catch an error...")
        continue
    except KeyboardInterrupt:
        print("\nProgram stopped.")
        exit()

So the import from model doesn't do much, only the database connection and the "gps parser" is only the pynmea that parses a string of data and then returns it.


So what I want is something like:

It gets all the data it pulses once per second, it then splits it all into chucks where it starts with the $GP variable, then I can search for the second variable part, for example VTG or GGA . And then I can use that string to make conversions to the right value to extract the speed, latitude, longitude and other data if needed.

Hope you guys can understand me well and can help me out.

Not sure if that solves your problem, but pynmea2 has speed attributes, defined in talker.py .

import pynmea2
for i, line in enumerate(open('/tmp/nmea.txt').readlines()):
    # parsing via pynmea
    msg = pynmea2.parse(line.strip())
    if msg.sentence_type == 'VTG':
        print ('parsing line %s with pynmea:' % i, float(msg.spd_over_grnd_kmph))

    # parsing via manually
    if line.startswith('$GPVTG'):
        cur_speed = line.split(",")[7]
        print ('parsing line %s manually:' % i, float(cur_speed))

Returns:

parsing line 1 with pynmea: 91.626
parsing line 1 manually: 91.626
parsing line 10 with pynmea: 90.842
parsing line 10 manually: 90.842
parsing line 19 with pynmea: 89.676
parsing line 19 manually: 89.676

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM