#!/usr/bin/env python
#-*- coding: utf-8 -*-   
#-*- coding: cp950 -*- 

import array,time,threading,serial,urllib2,urllib,os,os.path,requests   #How to install?? ----> pip install requests
import traceback



path_gps='http://www.aisky.com.tw/field/gps.php'
ser=serial.Serial('/dev/ttyUSB0',9600,timeout=0.1)


rx_dev_nr = "2"
case_command = "0"


def catch_RTK_GPS():
	global rx_dev_nr
	global case_command
	if ser.inWaiting() :
	#if True :
		try :
			x = ser.readline()
			#x = "$GPGGA,140025.00,2503.2423699,N,12136.4594332,E,1,04,1.0,17.259,M,19.013,M,0.0,*7B"
			#print x

			if x[0:6] == "$GPGGA" and len(x) < 90 :
				log = x
				x = x.split(",")
				if x[7] == '0':
					print "no satellite data available"
				if x[2] != "0" and x[4] != "0":
					time_data = x[1][0:2] + ":" + x[1][2:4] + ":" + x[1][4:6]
					lat = x[2]
					lng = x[4]
					print "Time : " + time_data + "/ Lat : " + lat + "/ Lng : " + lng
					mydata=[("dev_nr",rx_dev_nr),("lat",lat),("lng",lng),("log",log)]
					#mydata=[("dev_nr",rx_dev_nr),("lat","2503.5376838"),("lng","12136.8545442")]
					print mydata
					print 'GateWay Catch Nr '+str(rx_dev_nr)+' ok'
					mydata=urllib.urlencode(mydata)
					req=urllib2.Request(path_gps, mydata)
					req.add_header('User-Agent','Magic Browser')
					page=urllib2.urlopen(req).read()

					print time.strftime(' nr '+str(rx_dev_nr)+' command:'+str(case_command)+' %m/%d/%Y'+' %H:%M:%S'+' add ok ')

					x = ""
					y = ""
					print '######################################################################################## \n'
		except Exception, e:
			try :
				print 'traceback.print_exc():'; traceback.print_exc()
				mydata=[("dev_nr",rx_dev_nr),("data_error",traceback.format_exc())]
				mydata=urllib.urlencode(mydata)
				req=urllib2.Request(path_gps, mydata)
				req.add_header('User-Agent','Magic Browser')
				page=urllib2.urlopen(req).read()
			except :
				print ("無法上傳")
			print ("有問題,請確認")


time.sleep(15)
print ("開始偵測GPS訊號GO")
while True :
	catch_RTK_GPS()
	time.sleep(1)