#!/usr/bin/env python
#*******************************************
#            gps.py
# 
# To execute this script type:
# python3 gps.py
#*******************************************
import time
import serial
import io
import sys
import os
ser=serial.Serial('/dev/ttyUSB2',115200,timeout=1)
def send(command):
   #This function sends the command to the modem
   command=command+"\r"
   ser.write(command.encode())
   time.sleep(.1)  
os.system('clear')
data=""
send('ATE0')
send('AT+QGPSCFG="outport","usbnmea"')
send("AT+QGPS=1")
send("AT+QGPSLOC=2")
time.sleep(.5)
data=ser.read(1000)
time.sleep(.1)
data=data.decode("utf-8").strip()
data=data.replace('OK','')
data=data.replace('\r\n','')
if (data.find('+CME ERROR: 516') != -1):
   print("Not Fixed Yet")
   time.sleep(2)
   os._exit(0)
p=(data.partition('+QGPSLOC: ')[2])
gps=p.split(",")
latitude=float(gps[1])
if (latitude < 0):
   latitude_hemisphere="South"
if (latitude > 0):
   latitude_hemisphere="North"
longitude=float(gps[2])
if(longitude < 0):
   longitude_hemisphere="West"
if(longitude > 0):
   longitude_hemisphere="East"
latitude=abs(latitude)
longitude=abs(longitude)
altitude=gps[4]
course=gps[6]
speed=gps[7]
print("")
print(str(latitude)+" "+latitude_hemisphere+" Latitude")
print(str(longitude)+" "+longitude_hemisphere+" Longitude")
print ("Altitude="+altitude+" Meters")
print ("Direction traveling="+course+" degrees")
print("")
print("Link for Google Maps:")
print("")
link="https://www.google.com/maps/place/"+gps[1]+","+gps[2]
print(link)
print("")
ser.close()