#!/usr/bin/env python
#*******************************************
#            smsgps.py
# 
# To execute this script type:
# python3 smsgps.py &
# The & at the end runs it in the background
#*******************************************
import time
import serial
import io
import sys
import os
import threading

ser=serial.Serial('/dev/ttyUSB3',115200,timeout=1)
event_port=serial.Serial('/dev/ttyUSB2',115200,timeout=1)

#----------------------------------------
def send(command,port,sleeptime):
#----------------------------------------
   command=command+"\r"
   port.write(command.encode())
   time.sleep(sleeptime)  
   data=ser.read(10000)
   data=data.decode("utf-8").strip()
   return data

#----------------------------------------
def listen():
#----------------------------------------
   threading.Timer(3.0, listen).start()
   eventbuf=event_port.read(1000) 
   eventbuffer=eventbuf.decode("utf-8").strip()
   eventbuffer=eventbuffer.replace('OK','')
   if(len(eventbuffer)>0):
      #---check to see if there was an incoming text 
      if (eventbuffer.find("+CMT:") != -1):
         lines=eventbuffer.split("\r\n")
         metadata=lines[0].partition('+CMT: ')[2].split(",")
         msg=lines[1]
         phone_number=metadata[0].replace('"','')
      if(msg[0:6]=="locate"):
         #get_gps_location(phone_number)
         get_gps_location(phone_number)

#----------------------------------------
def sms_reply(phone_number,msg):
#----------------------------------------
   send('AT+CMGS="'+phone_number+'"',ser,.1)
   send(msg+"\x1a",ser,.1)

#----------------------------------------
def get_gps_location(phone_number):
#----------------------------------------
   response=send("AT+QGPSLOC=2",ser,.5)
   print("initiated gps locator routine for "+phone_number)
   if (response.find('+CME ERROR: 516') != -1):
      print("No fixed location yet")
      sms_reply(phone_number,"No fixed location yet")
      return
   gps=(response.partition('+QGPSLOC: ')[2]).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(str(latitude)+" "+latitude_hemisphere+" "+str(longitude)+" "+longitude_hemisphere)

   msg=str(latitude)+" "+latitude_hemisphere+" "+str(longitude)+" "+longitude_hemisphere+"\n"

   print ("Alt="+altitude+"M")
   msg=msg+"Alt="+altitude+"M\n"
   print ("Dir="+course+" deg")
   msg=msg+"Dir="+course+" deg\n"

   link="https://www.google.com/maps/place/"+gps[1] +","+gps[2]

   print(link)
   msg=msg+link
   sms_reply(phone_number,msg)

#---------------------------  start ----------------------
send('ATE0',ser,.1) # turn echo off
send("AT+CMGF=1",ser,.1) #turn on texting
send('AT+CSCS="GSM"',ser,.1)
#send constant gps sentence data to /dev/ttyUSB1
send('AT+QGPSCFG="outport","usbnmea"',ser,.1)
send("AT+QGPS=1",ser,.1) # turn on gps positioning
#Make it so that sms messages are routed directly to ttyUSB2 
#  and displayed in full but not saved
send("AT+CNMI=1,2,0,1,0",ser,.1)  
#2,1,0,0,0 will reset to normal
listen() # start listing for incoming texts
