Skip to content

Instantly share code, notes, and snippets.

@parthpower
Last active December 17, 2015 16:10
Show Gist options
  • Save parthpower/a56dd670c24513e498c7 to your computer and use it in GitHub Desktop.
Save parthpower/a56dd670c24513e498c7 to your computer and use it in GitHub Desktop.
#Author: Parth Parikh
#Distributed under MIT license
import serial
import pynmea2
import datetime
from dateutil import tz
LOG_FILE = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M_%S')+"_gps_log.csv"
LOG_FILE_RAWPACKET = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M_%S')+"_gps_raw_log.txt"
BAUD = 9600
def get_checksum(data):
j = ord(data[0])
for i in data[1:]:
j ^= ord(i)
return j
def available_ports():
ports =['COM%s'%(i+1) for i in range(256)]
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == "__main__":
portList = available_ports()
i = 1
for port in portList:
print(str(i) +')'+port)
i+=1
print("0)Exit")
selectedPortId = raw_input("SelectPort:")
if(selectedPortId == "0"):
exit()
try:
i = int(selectedPortId)
selectedPort = portList[i-1]
except Exception,e:
print("Wrong Input!!!!!!!!!!!!!!!")
raise e
try:
interface = serial.Serial(selectedPort,BAUD)
except Exception, e:
raise e
fp_log = open(LOG_FILE,"w")
fp_log.write("writing_datetime,reading_datetime,latitude,longitude,speed\n")
fp_log.close()
csv_dict = {}
while True:
rawPacket = interface.readline()
print(rawPacket)
fp_rawpacket = open(LOG_FILE_RAWPACKET,"a")
fp_rawpacket.write("["+datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')+"]:"+rawPacket)
fp_rawpacket.close()
try:
parsedPacket = pynmea2.parse(rawPacket)
if(parsedPacket.sentence_type == 'RMC' and parsedPacket.status =='A'):
csv_dict['latitude'] = parsedPacket.latitude #float
csv_dict['longitude'] = parsedPacket.longitude #float
csv_dict['reading_datetime'] = parsedPacket.datetime.replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal()).strftime("%d-%m-%Y %H:%M:%S") #string
csv_dict['writing_datetime'] = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
csv_dict['speed'] = parsedPacket.spd_over_grnd #float
fp_log = open(LOG_FILE,"a")
csv_string = "%s,%s,%s,%s,%s\n" % (csv_dict['writing_datetime'],csv_dict['reading_datetime'],csv_dict['latitude'],csv_dict['longitude'],csv_dict['speed'])
print(csv_string)
fp_log.write(csv_string)
fp_log.close()
pass
except Exception, e:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment