Skip to content

Instantly share code, notes, and snippets.

@forkbombe
Last active April 1, 2021 16:14
Show Gist options
  • Save forkbombe/1b241d8a51709e4c5a00fc47f710ade9 to your computer and use it in GitHub Desktop.
Save forkbombe/1b241d8a51709e4c5a00fc47f710ade9 to your computer and use it in GitHub Desktop.
Get NMEA and parse to LatLong using Waveshare GNSS, GPRS hat - https://www.waveshare.com/wiki/GSM/GPRS/GNSS_HAT
##!/usr/bin/python
import serial
import time
import pynmea2
import json
# Change to location of device
serialPort = "/dev/ttyS0"
class Commands(object):
GNSS_POWER_ON = "AT+CGNSPWR=1\r\n"
GNSS_GET_NMEA = "AT+CGNSINF\r\n"
GNSS_REC_UART = "AT+CGNSTST=1\r\n"
commands = Commands()
def get_latlong():
output = ""
ser = serial.Serial(serialPort,115200)
ser.flushInput()
ser.flushOutput()
ser.write(commands.GNSS_POWER_ON.encode())
ser.write(commands.GNSS_REC_UART.encode())
ser.write(commands.GNSS_GET_NMEA.encode())
print("Waiting for signal...")
try:
while True:
# Keep sending text stream to output
while ser.inWaiting() > 0:
try:
output = ser.read(ser.inWaiting()).decode()
except:
## If error, re-run
self.get_latlong()
return;
# Split the output lines from the device into an array
if output != "":
lines = output.split('\n')
# Iterate over output lines
for i in lines:
# Get the bit we need
if i.startswith('$GNRMC'):
try:
# Parse $GNRMC format
msg = pynmea2.parse(i)
if(msg.latitude!=0.0):
## Log to console
print(f'LAT: {msg.latitude}')
print(f'LON: {msg.longitude}')
print(f'TIME: {time.time()}')
## JSON data
data = {
"latitude" : msg.latitude,
"longitude" : msg.longitude,
"time" : time.time()
}
## Close connection to device
ser.close()
## Return
return json.dumps(data)
else:
print("Couldn't parse $GNRMC line from device. Retrying...");
except pynmea2.ParseError:
## If error, re-run
self.get_latlong()
return;
# Wait for half a second before looping again
time.sleep(0.5)
except KeyboardInterrupt:
if ser != None:
ser.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment