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 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 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'
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,
import Adafruit_BBIO.ADC as ADC import Adafruit_BBIO.UART as UART import time import datetime import numpy as np import serial from pynmea import nmea from Adafruit_I2C import Adafruit_I2C # Addresses for reading x,y,z axes of the magnotomer. They are stored in registers and read as most significant bits (msb) and least $ # See page 11: #http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Co$ gprmc = nmea.GPRMC() mag_addr = 0x1E config_register = 0x01 X_msb = 0x03 X_lsb = 0x04 Z_msb = 0x05 Z_lsb = 0x06 Y_msb = 0x07 Y_lsb = 0x08 i2c = Adafruit_I2C(mag_addr) UART.setup("UART2") ser = serial.Serial(port="/dev/ttyO2", baudrate=9600) ser.close() ser.open()
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
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"
def loki(bound_lat, bound_lon, bound_radius, polling, flag): port = serial.Serial("/dev/ttyAMA0", 9600, timeout=1.0) gprmc = nmea.GPRMC() print "Bound Latitude: " + bound_lat print "Bound Longitude: " + bound_lon print "Bound Radius: " + bound_radius print "Patient Status Flag: " + flag try: bound_lat = float(bound_lat) except ValueError: print "Lat Value Error" + bound_lat try: bound_lon = float(bound_lon) except ValueError: print "Lon Value Error" + bound_lon try: bound_radius = float(bound_radius) except ValueError: print "Rad Value Error" + bound_radius while True: rcvd = port.readline() if rcvd[0:6] == '$GPRMC': gprmc.parse(rcvd) if gprmc.data_validity == 'V': print "No Location Found" location = { "latitude": "28.6647183333", "longitude": "77.2320366667", "flag": flag } data = json.dumps(location) return (json.dumps(location)) else: gprmc.parse(rcvd) latitude = gprmc.lat try: latitude = float(latitude) except ValueError: print "Lat Value Error " + latitude lat_direction = gprmc.lat_dir longitude = gprmc.lon try: longitude = float(longitude) 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) latitude = lat_dec_deg longitude = lon_dec_deg print "Current Latitude: " + str(latitude) + str(lat_direction) print "Current Longitude: " + str(longitude) + str( lon_direction) print "Time: " + str(gps_hour) + ":" + str( gps_min) + ":" + str(gps_sec) earth_radius = 6371 * 1000 dLat = (latitude - bound_lat) * math.pi / 180.0 dLon = (longitude - bound_lon) * math.pi / 180.0 latitude_rad = latitude * math.pi / 180.0 bound_lat_rad = bound_lat * math.pi / 180.0 val = math.sin(dLat / 2.0) * math.sin(dLat / 2.0) + math.sin( dLon / 2.0) * math.sin(dLon / 2.0) * math.cos( bound_lat_rad) * math.cos(latitude_rad) ang = 2 * math.atan2(math.sqrt(val), math.sqrt(1.0 - val)) distance = earth_radius * ang print "Distance from Bound Location: " + str(distance) #Send Latitude Longitude if distance > bound_radius and polling == "yes" and flag == "0": flag = "1" print "Patient outside Boundary" s = alert() elif distance <= bound_radius and polling == "yes" and flag == "1": flag = "0" print "Patient back in Boundary" location = { "latitude": str(lat_dec_deg), "longitude": str(lon_dec_deg), "flag": flag } data = json.dumps(location) return (json.dumps(location)) '''else: