Source

gpstrackerpi / v0.1 / serialGetGPS.py

Full commit
#!/usr/bin/python -tt
#serialGetGPS.py

import serial, time, csv, sys
import parseNMEA
from gpsPostData import postGPSData
from datetime import datetime
from dateutil import tz
from gpsTrackLog import gpstrack
from gpsLogger import gpslog
from unitCallHome import callhome

def startSerialCapture(trackUnit):
	##different commands to set the update rate from once a second (1 Hz) to 10 times a second (10Hz)
	PMTK_SET_NMEA_UPDATE_1HZ = '$PMTK220,1000*1F\r\n'
	PMTK_SET_NMEA_UPDATE_5HZ = '$PMTK220,200*2C\r\n'
	PMTK_SET_NMEA_UPDATE_10H = '$PMTK220,100*2F\r\n'
	unitNum = trackUnit
	##print unitNum
	##turn on only the second sentence (GPRMC)
	PMTK_SET_NMEA_OUTPUT_RMCONLY = '$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n'
	##turn on GPRMC and GGA
	PMTK_SET_NMEA_OUTPUT_RMCGGA = '$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n'
	##turn on ALL THE DATA
	PMTK_SET_NMEA_OUTPUT_ALLDATA = '$PMTK314,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n'
	## turn off output
	PMTK_SET_NMEA_OUTPUT_OFF = '$PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n'
	knot=float(1.15077945)
	
	DEVICE = '/dev/ttyAMA0'
	BAUD = 115200
	ser = serial.Serial(DEVICE, BAUD)
	ser.open()
	ser.flush()
	##ser.writelines(PMTK_SET_NMEA_UPDATE_1HZ, PMTK_SET_NMEA_OUTPUT_RMCONLY)
	ser.write(PMTK_SET_NMEA_UPDATE_1HZ)
	ser.write(PMTK_SET_NMEA_OUTPUT_RMCONLY)
	##ser.write(PMTK_SET_NMEA_OUTPUT_RMCGGA)
	
	ser.close()
	time.sleep(1)
	BAUD = 9600
	ser = serial.Serial(DEVICE, BAUD)
	ser.open()
	count = 0
	out = ''
	##callhome(trackUnit)
	while True:
		while ser.inWaiting() > 0:
			out = ser.readline()
			##	print "sats:" + str(numSats)
			if out.startswith("$GPRMC"):
				# Create the object
				count = count + 1
				##print count
				##print repr(out)
				##gpstrack('INFO', repr(out))
				try:
					parseNMEA.parseLine(out)
					fail = 0
				except (AssertionError, ValueError, TypeError) as e:
					fail = 1
					##print 'CHECKSUM ERROR 2'
					gpslog('ERROR', 'CHECKSUM ERROR: '+ e)
				
				if fail == 0:
					timeUTC = time.strftime("%H:%M:%S", time.strptime(parseNMEA.getField('UtcTime').split(".")[0],"%H%M%S"))
					try:
						speedGPS = parseNMEA.getField('SpeedOverGround')
					except ValueError:
						speedGPS = float(0)
						##print "Error 2"
						gpslog('ERROR', e)
					mph = round(speedGPS*knot,2)
					gpsLat = parseNMEA.getField('Latitude')
					gpsLong = parseNMEA.getField('Longitude')
					gpsCourse = round(parseNMEA.getField('CourseOverGround'))
					logme = "time:", timeUTC, "lat:", gpsLat, "long:", gpsLong, "speed:", mph, "course:", gpsCourse
					##gpstrack('INFO', logme)
					if (count % 10) == 0:
						postGPSData(unitNum, timeUTC, gpsLat, gpsLong, mph, gpsCourse)
					
					if (count % 600) == 0:
						callhome(unitNum)
			

	
##time.sleep(10)