def read_rtc_datetime(): """Read date and time from the RTC from a serial connection, and return as a datetime object. """ # Open a serial connection ser = serial.Serial() ser.port = "/dev/ttyUSB0" #USB ser.baudrate = 9600 ser.timeout = 1 ser.open() # Define the required NMEA sentences gpgga = nmea.GPGGA() # time information gprmc = nmea.GPRMC() # date information time_stamp = None date_stamp = None while time_stamp is None or date_stamp is None: data = ser.readline() if data[0:6] == '$GPGGA': gpgga.parse(data) time_stamp = str(int(nm.round(float(gpgga.timestamp)))) if data[0:6] == '$GPRMC': gprmc.parse(data) date_stamp = str(gprmc.datestamp) ser.close() dtstamp = datetime.datetime.strptime(time_stamp+' '+date_stamp, '%H%M%S %d%m%y') return dtstamp
def updateLatLong(self): data = self.ser.readline() try: data = data.decode( "utf-8") #converts data from bytes to string for parsing if (data[0:6] == '$GPGGA'): gpgga = nmea.GPGGA() gpgga.parse(data) lats = gpgga.latitude longs = gpgga.longitude #convert degrees, decimal minutes to decimal degrees lat1 = (float(lats[2] + lats[3] + lats[4] + lats[5] + lats[6] + lats[7] + lats[8])) / 60 lat = (float(lats[0] + lats[1]) + lat1) long1 = (float(longs[3] + longs[4] + longs[5] + longs[6] + longs[7] + longs[8] + longs[9])) / 60 long = (float(longs[0] + longs[1] + longs[2]) + long1) #calc position self.lat = lat self.long = -long self.coord = (str(self.lat) + ',' + str(self.long)) except: pass
def altitude(): global alt, i #we want to create temporary file to parse, so that we don't mess with the nmea.txt file #f1 = open('test.txt', 'w') #creates and opens a writable txt file #f1.truncate() #erase contents of file #shutil.copyfile('test.txt', 'temp.txt') #copy nmea.txt to temp.txt #f1.close() #close writable file f1 = open('temp.txt', 'r') #open and read only #print(f1) try: #best to use try/finally so that the file opens and closes correctly #print("qwe") # print(f2) for line in f1: #read each line in temp.txt # print(line[4]) if(line[4] == 'G'): # fifth character in $GPGGA if(len(line) > 50): # when there is a lock, the sentence gets filled with data #print line gpgga = nmea.GPGGA() gpgga.parse(line) alt = gpgga.antenna_altitude i +=1 #increment the counter # plt.scatter(x=[i], y=[float(alt)], s = 1, c='r') #plot each point finally: print("error") f1.close() i=0
def altitude(): global alt, i #we want to create temporary file to parse, so that we don't mess with the nmea.txt file f1 = open('temp.txt', 'w') #creates and opens a writable txt file f1.truncate() #erase contents of file shutil.copyfile('nmea.txt', 'temp.txt') #copy nmea.txt to temp.txt f1.close() #close writable file f1 = open('temp.txt', 'r') #open and read only try: #best to use try/finally so that the file opens and closes correctly for line in f1: #read each line in temp.txt if(line[4] == 'G'): # fifth character in $GPGGA if(len(line) > 50): # when there is a lock, the sentence gets filled with data #print line gpgga = nmea.GPGGA() gpgga.parse(line) alt = gpgga.antenna_altitude i +=1 #increment the counter print i print alt plt.scatter(x=[i], y=[float(alt)], s = 1, c='r') #plot each point finally: f1.close() i=0 #axis is autoscaled plt.ylabel('meters') plt.xlabel('counts') plt.title('ALTITUDE') plt.show()
def decodeNMEAStream(serialport,GCJ02=False): while True: try: line = serialport.readline() line = line.decode('ascii') #print(line) if(line[4] == 'G'): # $GPGGA if(len(line) > 50): #print line gpgga = nmea.GPGGA() gpgga.parse(line) lats = gpgga.latitude longs = gpgga.longitude #convert degrees,decimal minutes to decimal degrees _lat = (float(lats[2]+lats[3]+lats[4]+lats[5]+lats[6]+lats[7]+lats[8]))/60 lat = (float(lats[0]+lats[1])+_lat)+0.00629 _long = (float(longs[3]+longs[4]+longs[5]+longs[6]+longs[7]+longs[8]+longs[9]))/60 longs = (float(longs[0]+longs[1]+longs[2])+_long)+0.00643 if GCJ02: return transform(lat,longs) else: return (lat,longs) except: continue
def position(): #opens a the saved txt file, parses for lat and long, displays on map global lat, long, lat_input, long_input, pos_x, pos_y, altitude global BLX, BLY, TRX, TRY #same process here as in altitude f1 = open('temp.txt', 'w') f1.truncate() shutil.copyfile('nmea.txt', 'temp.txt') f1.close() f1 = open('temp.txt', 'r') #open and read only try: for line in f1: if (line[4] == 'G'): # $GPGGA if (len(line) > 50): #print line gpgga = nmea.GPGGA() gpgga.parse(line) lats = gpgga.latitude longs = gpgga.longitude #convert degrees,decimal minutes to decimal degrees lat1 = (float(lats[2] + lats[3] + lats[4] + lats[5] + lats[6] + lats[7] + lats[8])) / 60 lat = (float(lats[0] + lats[1]) + lat1) long1 = (float(longs[3] + longs[4] + longs[5] + longs[6] + longs[7] + longs[8] + longs[9])) / 60 long = (float(longs[0] + longs[1] + longs[2]) + long1) #calc position pos_y = lat pos_x = -long #longitude is negaitve #plot the x and y positions plt.scatter(x=[pos_x], y=[pos_y], s=5, c='r') #shows that we are reading through this loop print pos_x print pos_y finally: f1.close() #now plot the data on a graph #plt.scatter(x=[long_input], y=[lat_input], s = 45, c='b') #sets your home position plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title('POSITION (in Decimal Degrees)') #lay the image under the graph #read a png file to map on im = plt.imread('map.png') implot = plt.imshow(im, extent=[BLX, TRX, BLY, TRY]) plt.show()
def ParseGpsNmeaFile(self, filename): """ Read in a GPS NMEA formated input file <filename> Parse it assuming the file contains pairs of GPGGA and GPRMC lines of data. Some fault tolerance if one or the other line is dropped or the line is poorly formed/corrupt. Return the array of data for subsequent parsing """ print("Parsing input NMEA file %s" % filename) self.gpsData = [] gprmc = nmea.GPRMC() gpgga = nmea.GPGGA() outputLine = "" lastLat = 0.0 lastLon = 0.0 for line in open(filename, 'r'): # strip any whitespace from edges line = line.strip() if not line: continue # Try to catch corrupt lines early if not line.startswith('$GP'): print('Bad line: ', line) continue # Skip any sentence other than GPGGA if line.startswith('$GPGGA'): outputLine = "" gpgga.parse(line) if self.DoNotHaveFix(gpgga.latitude): continue [lat, lon] = self.ConvertLatLonToDecimalDegrees( gpgga.latitude, gpgga.lat_direction, gpgga.longitude, gpgga.lon_direction) distance = self.HaversineDistance(lat, lastLat, lon, lastLon) lastLat = lat lastLon = lon outputLine = "%s,%f,%f,%s,%f,%s,%s," % \ (gpgga.timestamp, lat, lon, gpgga.antenna_altitude, distance, \ gpgga.num_sats, gpgga.gps_qual) elif line.startswith('$GPRMC'): if (len(outputLine) == 0): continue gprmc.parse(line) outputLine += "%s,%s,%s" % \ (gprmc.spd_over_grnd, gprmc.true_course, gprmc.datestamp) self.gpsData.append(outputLine) outputLine = ""
def init_classes(self): self.config_menus = configparser.ConfigParser() self.config_tools = configparser.ConfigParser() self.config_tabs = configparser.ConfigParser() self.config_map = configparser.ConfigParser() self._serial = serial.Serial() self._parser = parsenmea.ParseNmea() self._storage = StorageDB('gps.sqlite') self._settings = Settings() self._gpgga = nmea.GPGGA() self._gprmc = nmea.GPRMC() pass
def convert(inputName, outputName): data = open(inputName, "r") file = open(outputName, "w") file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <gpx version=\"1.0\">\n") file.write("<tk>\n<trkseg>\n") while(True): data.seek(data.tell()) time.sleep(1) for line in data: if line[4] == 'G': gpgga = nmea.GPGGA() gpgga.parse(line) lats = gpgga.latitude longs = gpgga.longitude print(lats, longs)
def get_serial_nmea(port_num=0): gpgga = nmea.GPGGA() port_num = 1 if port_num == 0 else port_num trying = True while trying: com_port = 'COM{0}'.format(port_num) try: # print('attempting com_port {0}'.format(com_port)) ser = serial.Serial( port=str( com_port ), # Ports 1 thru 10 will be checked and nmea data returned if GPS Puck found baudrate=4800, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) test_data = ser.readline() if test_data: trying = False except serial.serialutil.SerialException as e: # sys.stderr.write('Could not open serial port {}: {}\n'.format(port_num, e)) if port_num >= 10: sys.exit(1) port_num += 1 # print('com_port is now: {0}'.format(com_port)) working = True while working: data = ser.readline() str_data = str(data) if 'GPGGA' in str_data: # method for parsing the sentence gpgga.parse(str_data) lats = str(gpgga.parts[2]) longs = str(gpgga.parts[4]) time_stamp = str( gpgga.parts[1]) # not currently used by this script alt = str(gpgga.parts[9]) # not currently used by this script ser.close() latitude_str = str(lats) + 'N' if str( gpgga.parts[3]).lower() == 'n' else str(lats) + 'S' longitude_str = str(longs) + 'E' if str( gpgga.parts[4]).lower() == 'e' else str(longs) + 'W' # gps_data_str = latitude_str + ',' + longitude_str # return gps_data_str, com_port return latitude_str + ',' + longitude_str, com_port
def run(self): """ Start reading GPS data from the UART. Updates will be sent to the callback function. """ if not self.serial_port.isOpen(): self.serial_port.open() if not self.serial_port.isOpen(): log.fatal('Couldn\'t open serial port') sys.exit(-1) log.info('Serial port opened') log.info('GPS running') self.serial_port.flushOutput() self.serial_port.flushInput() while True: time.sleep(1) # Read from the UART line = self.serial_port.read(self.serial_port.inWaiting()) self.serial_port.flushOutput() self.serial_port.flushInput() if line.startswith('$GPGGA'): gpgga = nmea.GPGGA() # Ask the object to parse the data gpgga.parse(line) # Set dummy timestamp self.current_timestamp = time.strftime("%H%M%S") # self.current_timestamp = float(gpgga.timestamp) self.current_lat = float( float(gpgga.latitude[2:]) / 60) + float(gpgga.latitude[:2]) self.current_lon = float( float(gpgga.longitude[3:]) / 60) + float( gpgga.longitude[:3]) # Invoke the callback listener self.listener.on_gpgga(gpgga)
def convert(inputName, outputName): data = open(inputName, "r") file = open(outputName, "w") file.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <gpx version=\"1.0\">\n") file.write("<tk>\n<trkseg>\n") for line in data: #gpgga = line.split(',') if line[4] == 'G': gpgga = nmea.GPGGA() gpgga.parse(line) lats = gpgga.latitude longs = gpgga.longitude print(lats, longs)
def position(): #opens a the saved txt file, parses for lat and long, displays on map global lat, long, lat_input, long_input, pos_x, pos_y, altitude global BLX, BLY, TRX, TRY, count f1 = open('nmea.txt', 'r') #open and read only f2 = open('map.png', 'w') #write info for line in f1: if (line[0] == '\0'): f1.close() break elif (line[4] == 'G'): # $GPGGA print line gpgga = nmea.GPGGA() gpgga.parse(line) lats = gpgga.latitude longs = gpgga.longitude f2.write(lats) f2.write(longs)
def getAltitude(self, altResp=None, _=None): ser = serial.Serial() ser.port = "/dev/ttyAMA0" ser.baudrate = 9600 ser.timeout = 10.0 ser.open() gpgga = nmea.GPGGA() CURRENT_ALT = None while True: data = ser.readline() if data[0:6] == '$GPGGA': gpgga.parse(data) global CURRENT_ALT CURRENT_ALT = gpgga.antenna_altitude if CURRENT_ALT: break return 'altResp({"Altitude" : "' + str(CURRENT_ALT).replace( u'\xb0', "") + '"};)'
def recording(): target_dir = dt.now().strftime('%Y_%m_%d_%h_%m_%s') os.makedirs(target_dir) f = open(target_dir + '/data.csv', 'ab') csvWriter = csv.writer(f) beforeFlag = True dataIndex = 1 # GPS ser = serial.Serial('/dev/ttyAMA0', 9600) gpgga = nmea.GPGGA() # Camera camera = picamera.PiCamera() while True: # Camera camera.capture(target_dir + '/' + str(dataIndex) + '.jpg') # GPS gpsLat = -1 gpsLong = -1 data = ser.readline() if (data.startswith('$GPGGA')): gpgga.parse(data) gpggaLat = gpgga.latitude gpggaLong = gpgga.longitude if gpggaLat is not '': gpsLat = float(gpggaLat[0:1]) + float(gpggaLat[1:]) / 60 gpsLong = float(gpggaLong[0:2]) + float(gpggaLong[2:]) / 60 listData = [dataIndex, gpsLat, gpsLong] csvWriter.writerow(listData) dataIndex = dataIndex + 1 if GPIO.input(GPIO_START_BUTTON) and not beforeFlag: break else: beforeFlag = False time.sleep(1) camera.close() f.close()
def convert_gpgga(line): gpgga = nmea.GPGGA() gpgga.parse(line) alt = gpgga.antenna_altitude lats = gpgga.latitude longs = gpgga.longitude #convert degrees,decimal minutes to decimal degrees lat1 = (float(lats[2] + lats[3] + lats[4] + lats[5] + lats[6] + lats[7] + lats[8])) / 60 lat = (float(lats[0] + lats[1]) + lat1) long1 = (float(longs[3] + longs[4] + longs[5] + longs[6] + longs[7] + longs[8] + longs[9])) / 60 long = (float(longs[0] + longs[1] + longs[2]) + long1) #calc position pos_y = lat pos_x = -long #longitude is negaitve return [pos_y, pos_x, alt]
def getGpsData(): '''Writes latest gps string to the file''' appId = "A" #A = GPS tracker messageId = "A" # A = GPS data, B = storing GPS data Imei = "355435047096119" #IMEI 15 chars GpsFix = "0" #A=DataValid,B=invalid,X=GPSnotworkin,M = Masked GpsTime = "000000" #hhmmss, use GPRMC GpsDate = "000000" #ddmmyy, use GPRMC Lati = "0000.0000" #ddmm.mmmm, use GGA NorthSouth = "0" #N or S, use GGA Longi = "0000.0000" #ddmm.mmmm, use GGA EastWest = "0" #E or W, use GGA Sog = "000000" #speed over ground, use GPVTG Cog = "000000" #course over ground, use GPVTG Sats = "00" #no of satellites, use GPGGA Hdop = "0000" #Horizontal dilution of precision, use GPGGA StrengthQual = "0000" #signal strength and qual. of gprs PowerMode = "0" # BatLevel = "000" AiVal = "0000" AiVal2 = "0000" #DailyDist = "" #OdoDist = "" DiStat = "0000" CrLf = '\n' + '\t' gpgga = nmea.GPGGA() gpgll = nmea.GPGLL() gpvtg = nmea.GPVTG() gprmc = nmea.GPRMC() ser = serial.Serial(serial_port, baudrate, timeout=5) #camera = picamera.PiCamera() for i in range(10): try: data = ser.readline() except serial.serialutil.SerialException: pass if data.startswith('$GPGGA'): gpgga.parse(data) #ref nmea Lati = gpgga.latitude Longi = gpgga.longitude Sats = gpgga.num_sats GpsFix = gpgga.timestamp NorthSouth = gpgga.lat_direction EastWest = gpgga.lon_direction Sats = gpgga.num_sats Hdop = gpgga.horizontal_dil print "gpgga", Lati, Longi, Sats, GpsFix, Hdop elif data.startswith('$GPGLL'): gpgll.parse(data) klist = data.split(",") GpsFix = klist[6] print "gpgll", GpsFix elif data.startswith('$GPVTG'): gpvtg.parse(data) Cog = gpvtg.true_track Sog = gpvtg.spd_over_grnd_kts print "gpvtg", Cog, Sog elif data.startswith('$GPRMC'): gprmc.parse(data) GpsDate = gprmc.datestamp GpsTime = gprmc.timestamp print "gprmc", GpsTime, GpsDate msgString = appId + messageId + Imei + GpsFix + GpsTime + \ GpsDate + Lati + NorthSouth + Longi + EastWest + \ Sog + Cog + Sats + Hdop + StrengthQual + PowerMode + \ BatLevel + AiVal + AiVal2 + DiStat + CrLf print >> sys.stderr, msgString ser.close() #sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #sock.connect(server_addr) print >> sys.stderr, 'sending ...' try: sock.sendall(msgString) finally: print >> sys.stderr, 'closing socket'
from abc import abstractmethod import serial from pynmea import nmea import threading import time import sys from util.logger import Logger log = Logger(__name__).setup() test = nmea.GPGGA() test.parse("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47") class GPS(threading.Thread): """ Helper class to read GPS data in a separate thread. """ def __init__(self, listener): log.info('Initialising GPS') super(GPS, self).__init__() self.daemon = True self.serial_port = serial.Serial("/dev/ttyAMA0", 9600, timeout=2) self.listener = listener self.current_timestamp = float(test.timestamp) self.current_lat = float(test.latitude) self.current_lon = float(test.longitude)
def create_gps_csv(self): print "Start" print "Creating Object" ser = serial.Serial() ser.port = "COM4" ser.baudrate = 4800 ser.bytesize = serial.EIGHTBITS ser.timeout = 1 ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE print "Opening Port" ser.open() gpgga = nmea.GPGGA() year = arrow.now().format('YYYY') month = arrow.now().format('MM') day = arrow.now().format('DD') print "Receiving information" try: os.chdir(self.root_path + self.date_path) except WindowsError: os.mkdir(self.root_path + self.date_path) try: os.chdir(self.root_path + self.date_path + "\\GPS") except WindowsError: os.mkdir(self.root_path + self.date_path + "\\GPS") gps_path = self.root_path + self.date_path + "\\GPS" while True: data = ser.readline() if data[0:6] == '$GPGGA': print # method for parsing the sentence gpgga.parse(data) lat = gpgga.latitude templat = lat.split(' ') d = lat[:2] m = lat[2:4] s = float(lat[4:]) * 60 if str(gpgga.lat_direction) == "S": d = "-" + d lat = str(d) + " " + str(m) + " " + str(s) lon = gpgga.longitude d = lon[:3] m = lon[3:5] s = float(lon[5:]) * 60 if str(gpgga.lon_direction) == "W": d = "-" + d lon = str(d) + " " + str(m) + " " + str(s) time_stamp = gpgga.timestamp local_time = arrow.get( arrow.now('GMT').format('YYYY-MM-DD') + " " + arrow.get(time_stamp, 'HHmmss').format('HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss').to('Australia/Melbourne') print "GPS time stamp : " + str( arrow.get(local_time).format('YYYY-MM-DD HH:mm:ss')) print lat, lon with open(gps_path + "\GPS.csv", 'a') as f: line_string = str(local_time) + "," + str( arrow.get(local_time).timestamp) + "," + str( lat) + "," + str(lon) + "\n" f.writelines(line_string)
rad_feed = 0 c_rad = 0 f_lat_feed = 0 f_lon_feed = 0 status = 0 c_lat = 3 c_lon = 2 f_lat = 18.672652777777778 f_lon = 73.84744444444443 ser = serial.Serial() ser.port = "/dev/ttyS0" ser.baudrate = 9600 ser.timeout = 1 ser.open() gpgga = nmea.GPGGA() def Read_serial(): while (1): data = ser.readline() if data[0:6] == '$GPGGA': ##method for parsing the sentence gpgga.parse(data) lats = gpgga.latitude #print "Latitude values : " + str(lats) lat_dir = gpgga.lat_direction #print "Latitude direction : " + str(lat_dir) longitude = gpgga.longitude
def parse(self, packet): print packet try: if (ord(packet['DevID']) == 20): if (ord(packet['MsgID']) == 13): #self.accelburst = self.accelburst + 1 #print "IMU: " + str(self.accelburst) accelnr = 0 try: for i in range(len(packet['Data'])): #print packet['Data'][i] +"\t (" + str(ord(packet['Data'][i])) + ")\t [" + hex(ord(packet['Data'][i])) + "]" #print str(packet['Data'][i-1:i+1]) if ((i & 1) == 1): tempval = packet['Data'][i - 1:i + 1] tempval.reverse() #print str("".join(tempval)) val = 0 try: val = struct.unpack('h', "".join(tempval)) except: pass #val = struct.unpack('h', "".join(packet['Data'][i-1:i+1])) self.accelburst[accelnr] = val[0] accelnr = accelnr + 1 #print str(val[0]) self.accelburst[accelnr] = packet['Time'] if (abs(self.accelburst[accelnr - 2]) > 1000): print packet print self.accelburst #print self.accelburst else: self.writer.writerow(self.accelburst) except Exception as e: print e #print "IMU BURST!" pass elif (ord(packet['DevID']) == 30): if (ord(packet['MsgID']) == 6): self.gpspacket += 1 #print "GPS: " + str(self.gpspacket) #print "".join(packet['Data']), self.gpslog.write("".join(packet['Data'])) #self.gpswriter.writerow("".join(packet['Data'])) #print "Logged" if ("".join(packet['Data'][1:6]) == "GPGGA"): gpgga = nmea.GPGGA() tempstr = "".join(packet['Data']) gpgga.parse(tempstr) #print "Timestamp:" + gpgga.timestamp '''try: deltat = int(float(gpgga.timestamp))-self.prevtime print deltat self.prevtime = int(float(gpgga.timestamp)) except Exception as e: print e''' gpsd = [ gpgga.timestamp, gpgga.latitude, gpgga.longitude, packet['Time'] ] #self.gpswriter.writerow(gpsd) elif ("".join(packet['Data'][1:6]) == "GPRMC"): gprmc = nmea.GPRMC() tempstr = "".join(packet['Data']) gprmc.parse(tempstr) self.gpsdata[0] = gprmc.timestamp self.gpsdata[1] = gprmc.lat self.gpsdata[2] = gprmc.lon self.gpsdata[3] = gprmc.spd_over_grnd #self.gpsdata[4] = gprmc.true_course #self.gpsdata[5] = gprmc.datestamp #self.gpsdata[6] = gprmc.mag_variation self.gpsdata[7] = packet['Time'] # print self.gpsdata #print self.gpsdata #self.gpswriter.writerow(self.gpsdata) else: print "unknown packet" except Exception as e: self.excount += 1 print " " + str(self.excount) print e,
def gpsdata(self): logger.debug('Starting gpsdata') self.__future = datetime.now() cameraControl = CameraControl() logger.debug("Getting GPS data") ser = serial.Serial() ser.port = "/dev/ttyUSB0" ser.baudrate = 9600 ser.timeout = 1 ser.open() gpgga = nmea.GPGGA() gprmc = nmea.GPRMC() foundGPRMC = False foundGPGGA = False logger.debug('Starting While() to GPS Data') while True: # foundGPGGA ==False or foundGPRMC==False: data = ser.readline() logger.debug(data) if data[0:6] == '$GPRMC': gprmc.parse(data) #print(gprmc.sen_type) #print(gprmc.nmea_sentence) ##for d in data.split(','): # print('d:' + d) ufDate = data.split(',')[9] logger.debug('date:' + ufDate) logger.debug( str(ufDate)[4:].zfill(2) + '-' + str(ufDate)[2:4].zfill(2) + '-' + str(ufDate)[0:2].zfill(2)) self.__currentDate = datetime(2000 + int(str(ufDate)[4:]), int(str(ufDate)[2:4]), int(str(ufDate)[0:2])) logger.debug('current date:' + self.__currentDate.strftime("%d %B %Y")) foundGPRMC = True elif data[0:6] == '$GPGGA': ##method for parsing the sentence gpgga.parse(data) lats = gpgga.latitude logger.debug("Latitude values : " + str(lats)) lat_dir = gpgga.lat_direction logger.debug("Latitude direction : " + str(lat_dir)) longitude = gpgga.longitude logger.debug("Longitude values : " + str(longitude)) long_dir = gpgga.lon_direction logger.debug("Longitude direction : " + str(long_dir)) time_stamp = gpgga.timestamp #utctime = str(time_stamp)[0:2].zfill(2) + ':' + str(time_stamp)[2:4].zfill(2) + ':' + str(time_stamp)[4:].zfill(2) logger.debug("GPS time stamp : " + str(time_stamp)[0:2].zfill(2) + ':' + str(time_stamp)[2:4].zfill(2) + ':' + str(time_stamp)[4:].zfill(2)) utctime = self.__currentDate.replace( hour=int(str(time_stamp)[0:2]), minute=int(str(time_stamp)[2:4]), second=int(str(time_stamp)[4:6])) alt = gpgga.antenna_altitude logger.debug("Antenna altitude : " + str(alt)) #lat_secs = round(float(lats[5:]) * 60 / 10000, 2) if datetime.now() > self.__future: self.__future = datetime.now() + timedelta(minutes=1) self.__currentDateTime = utctime self.__currentLat = lats + lat_dir self.__currentLong = longitude + long_dir self.__currentAlt = alt distance = 0 #self.haversine(self.__previousLat,self.__previousLong, lats, longitude) self.__totalDistance = self.totalDistance + distance speed = self.calcSpeed(self.__previousDateTime, self.__currentDateTime, self.__totalDistance) self.saveDataToFile(self.__currentDateTime, lats, lat_dir, longitude, long_dir, alt, distance, speed) cameraControl.takeSingle(self.__currentDateTime) foundGPGGA = True
from std_msgs.msg import String import serial from pynmea import nmea import sys import urllib import urllib2 # Give ourselves the ability to run a dynamic reconfigure server. from dynamic_reconfigure.server import Server as DynamicReconfigureServer ser = serial.Serial() ser.port = "/dev/ttyACM0" ser.baudrate = 9600 ser.timeout = 1 ser.open() gps = nmea.GPGGA() def talker(): pub = rospy.Publisher('gps', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(5) # 10hz while not rospy.is_shutdown(): data = ser.readline() if data[0:6] == '$GPGGA': ##method for parsing the sentence gps.parse(data) latitude = gps.latitude latitude_direction = gps.lat_direction longitude = gps.longitude longitude_direction = gps.lon_direction
def getGpsData(): '''Writes latest gps string to the file ''' appId = "A" #A = GPS tracker messageId = "A" # A = GPS data, B = storing GPS data Imei = "000000000000000" #IMEI 15 chars GpsFix ="0" #A=DataValid,B=invalid,X=GPSnotworkin,M = Masked GpsTime = "000000" #hhmmss, use GPRMC GpsDate = "000000" #ddmmyy, use GPRMC Lati = "0000.0000" #ddmm.mmmm, use GGA NorthSouth = "0" #N or S, use GGA Longi = "0000.0000" #ddmm.mmmm, use GGA EastWest = "0" #E or W, use GGA Sog = "000000" #speed over ground, use GPVTG Cog = "000000" #course over ground, use GPVTG Sats = "00" #no of satellites, use GPGGA Hdop = "0000" #Horizontal dilution of precision, use GPGGA StrengthQual = "0000" #signal strength and qual. of gprs CrLf = '\n'+'\t' gpgga = nmea.GPGGA() gpgll = nmea.GPGLL() gpvtg = nmea.GPVTG() gprmc = nmea.GPRMC() ser = serial.Serial('/dev/ttyAMA0',9600) #gpio serial line, baud #camera = picamera.PiCamera() for i in range(10): data = ser.readline() if data.startswith('$GPGGA'): gpgga.parse(data) #ref nmea Lati = gpgga.latitude Longi = gpgga.longitude Sats = gpgga.num_sats GpsFix = gpgga.timestamp NorthSouth = gpgga.lat_direction EastWest = gpgga.lon_direction Sats = gpgga.num_sats Hdop = gpgga.horizontal_dil print "gpgga", Lati, Longi, Sats, GpsFix, Hdop if data.startswith('$GPGLL'): gpgll.parse(data) klist = data.split(",") GpsFix = klist[6] print "gpgll", GpsFix if data.startswith('$GPVTG'): gpvtg.parse(data) Cog = gpvtg.true_track Sog = gpvtg.spd_over_grnd_kts print "gpvtg", Cog, Sog if data.startswith('$GPRMC'): gprmc.parse(data) GpsDate = gprmc.datestamp GpsTime = gprmc.timestamp print "gprmc", GpsTime, GpsDate msgString = appId + messageId + Imei + GpsFix + GpsTime + \ GpsDate + Lati + NorthSouth + Longi + EastWest + \ Sog + Cog + Sats + Hdop + StrengthQual + PowerMode + \ BatLevel + AiVal + AiVal2 + DiStat #msgString += str(datetime.datetime.now()) #testing msgString += CrLf gStringName = "/home/pi/txt/"+GpsDate+GpsTime+".txt" msgF = open(gStringName, 'w') print msgString msgF.write(msgString) #To do; check write error; and then write a msg to log file msgF.close() camera = picamera.PiCamera() try: camera.resolution=(1024, 768) time.sleep(2) picName = "/home/pi/pic/"+GpsDate+GpsTime+".jpg" camera.capture(picName)
def loki(bound_lat, bound_lon, bound_radius): #Calculate Current Coordinates port = serial.Serial("/dev/ttyAMA0", 9600, timeout=3.0) gpgga = nmea.GPGGA() gprmc = nmea.GPRMC() while True: rcvd = port.readline() if rcvd[0:6] == '$GPRMC': gprmc.parse(rcvd) if gprmc.data_validity == 'V': print "No Location Found" else: gprmc.parse(rcvd) latitude = gprmc.lat try: latitude = float(latitude) except ValueError: print "Lat Value Error" + latitude lat_direction = gprmc.lat_dir try: longitude = float(gprmc.lon) except ValueError: print "Longitude Value Error" + longitude lon_direction = gprmc.lon_dir gps_time = float(gprmc.timestamp) gps_hour = int(gps_time / 10000.0) gps_min = gps_time % 10000.0 gps_sec = gps_min % 100.0 gps_min = int(gps_min / 100.0) gps_sec = int(gps_sec) lat_deg = int(latitude / 100.0) lat_min = latitude - (lat_deg * 100) lat_dec_deg = lat_deg + (lat_min / 60) lon_deg = int(longitude / 100.0) lon_min = longitude - (lon_deg * 100) lon_dec_deg = lon_deg + (lon_min / 60) lon_sec = lon_min % 100.0 lon_min = int(lon_min / 100.0) print "Time: " + str(gps_hour) + ":" + str( gps_min) + ":" + str(gps_sec) print "Latitude: " + str(lat_dec_deg) + str(lat_direction) print "Longitude: " + str(lon_dec_deg) + str(lon_direction) #Calculate dist between bound_coord and current location latitude = 28.664227 longitude = 77.232989 earth_radius = 6371 * 1000 dLat = (latitude - bound_lat) * math.pi / 180 dLon = (longitude - bound_lon) * math.pi / 180 latitude = latitude * math.pi / 180 bound_lat = bound_lat * math.pi / 180 val = math.sin(dLat / 2) * math.sin(dLat / 2) + math.sin( dLon / 2) * math.sin( dLon / 2) * math.cos(bound_lat) * math.cos(latitude) ang = 2 * math.atan2(math.sqrt(val), math.sqrt(1 - val)) distance = earth_radius * ang if distance > bound_radius: print "Patient Lost" #Send Push Noti and Location else: print "Patient Found"