def test_stream(): data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n" sr = pynmea2.NMEAStreamReader() assert len(sr.next('')) == 0 assert len(sr.next(data)) == 1 assert len(sr.next(data)) == 1 sr = pynmea2.NMEAStreamReader() assert len(sr.next(data)) == 1 assert len(sr.next(data[:10])) == 0 assert len(sr.next(data[10:])) == 1
def run(base_url, conn): lat = 0 lon = 0 orientation = 0 gotUpdate = False reader = pynmea2.NMEAStreamReader() for data in conn.iter(): try: for msg in reader.next(data): if type(msg) == pynmea2.types.talker.GGA: lat = msg.latitude lon = msg.longitude gotUpdate = True elif type(msg) == pynmea2.types.talker.HDT: orientation = msg.heading gotUpdate = True except pynmea2.ParseError as e: log.warning("Error while parsing NMEA string: {}".format(e)) if gotUpdate: log.info('Sending position and orientation') set_position_master('{}/api/v1/external/master'.format(base_url), lat, lon, orientation) gotUpdate = False
def __init__(self, fileStr): """ reads NMEA string and converts them to a List of cartesian Positions and a list of the related time in seconds using pynmea2 package """ projectPath = dirname(abspath(getcwd())) filePath = join(projectPath, fileStr) self.path = filePath self.P = [] self.t = [] with open(filePath, 'r') as fread: fileLen = getNumberOfLines(filePath) streamreader = pynmea2.NMEAStreamReader(fread, 'ignore') for _ in range(fileLen): for msg in streamreader.next(): if msg.sentence_type == 'GGA': he = float(msg.altitude) + float(msg.geo_sep) #m lat = deg2rad(msg.latitude) lon = deg2rad(msg.longitude) p_geo = EllipsoidPosition(toVector(lat, lon, he)) p_cart = ell2xyz(p_geo) t = msg.timestamp t_sec = (t.hour * 3600 + t.minute * 60 + t.second) self.P.append(p_cart) self.t.append(t_sec) self.length = len(self.t) self.sampleRate = (self.t[-1] - self.t[0]) / self.length
def start(self): print "Startings GPS Thread." com = None reader = pynmea2.NMEAStreamReader() if com is None: try: com = serial.Serial(GPS_SERIAL_DEVICE, timeout=5.0) except serial.SerialException: print('could not connect to %s' % filename) time.sleep(5.0) while not self.stop_soon: # TODO: handle exception thrown when out-of-sync data = com.read() for msg in reader.next(data): #print str(msg) parsed = pynmea2.parse(str(msg)) try: if isinstance(parsed, pynmea2.types.talker.GGA): # print lat+lon that can be parsed by http://maps.google.com print "", str(parsed.latitude) + str( parsed.lat_dir), str(parsed.longitude).replace( "-", "") + str(parsed.lon_dir) except: print "horse" time.sleep(4)
def run(self, port="/dev/ttyAMA0", baud=9600): com = None reader = pynmea2.NMEAStreamReader(errors='ignore') while self.run_event.is_set(): if com is None: try: com = serial.Serial(port, baudrate=baud, timeout=5.0) except serial.SerialException: print('could not connect to %s, trying again in 5 sec' % port) time.sleep(5.0) continue try: data = com.read(16) except serial.SerialException: print('Can not read from %s, trying again in 1 sec' % port) time.sleep(1.0) continue try: for msg in reader.next(data.decode('ascii', errors='ignore')): if msg.sentence_type == 'GGA': if msg.is_valid: self.data_lock.acquire(blocking=True, timeout=-1) self.gps_store.altitude = "%.2f" % msg.altitude + msg.altitude_units self.gps_store.lat = "%.8f" % msg.latitude self.gps_store.long = "%.8f" % msg.longitude self.gps_store.utc_time = msg.__getattr__('timestamp') self.gps_store.nr_sat = msg.__getattr__('num_sats') self.data_lock.release() self.timer.reset() else: self.clear_gps_store() except pynmea2.ChecksumError: continue
def getGPS(self, force=False, timeBound=3): #3s by default self.running = True if time.time( ) - self.timeCheck > timeBound or force: #every 3 seconds since last reading print("Reading new gps") self.timeCheck = time.time() else: self.running = False return self.coords ser = serial.Serial("/dev/ttyACM1") dataout = pynmea2.NMEAStreamReader() while 1: newdata = ser.readline() # Read a line from serial device if newdata[0:6] == "$GPGGA".encode( ): # If line contains GPS coordinate info newmsg = pynmea2.parse(newdata.decode()) # Parse it self.coords = (newmsg.latitude, newmsg.longitude) if self.log: self.logGPS() print(self.coords) self.running = False return self.coords #time.sleep(0.5) #when we find, take a little break
def main_loop(self): com = None reader = pynmea2.NMEAStreamReader() while True: if com is None: try: com = serial.Serial(self.port, timeout=5.0) except serial.SerialException: print('could not connect to %s' % self.port) time.sleep(5.0) continue data = com.read(16) for msg in reader.next(data): if msg: try: gmsg = pynmea2.parse(str(msg)) if int(gmsg.num_sats) >= NUM_SATS_NEEDED: # We have valid data print(time.time(), "lat", gmsg.latitude, "long", gmsg.longitude) self.ts = time.time() self.latitude = gmsg.latitude self.longitude = gmsg.longitude except: continue
class Read_Nmea(DatagramProtocol): # Read a UDP packet as an NMEA sentance streamReader = pynmea2.NMEAStreamReader() def datagramReceived(self, data, (host, port)): # A list of the incomming messages before writing to the db try: for line in data.split('\n'): nmea_msg = pynmea2.parse(line + '\n') if nmea_msg.sentence_type == 'GGA': # If message is a GPGGA, write it to the database print "msg to insert: " + str(nmea_msg) log(nmea_msg) try: data_to_insert = transform_coords( read_nmea(host, port, nmea_msg)) except: print 'error reading nmea' raise pass try: write_to_db(engine, tablename, data_to_insert) except: print 'error inserting into db!' raise pass except: print "error parsing message!" raise pass
def get_location(gps): gps_data = '' print('reading in location') gps.setblocking(True) while True: try: d = gps.recv(8096) gps.setblocking(False) except IOError: break gps_data += d print d if not d: break gps_data = '\n'.join(gps_data.split('\n')[1:-1]) # :( nmea_stream_reader = pynmea2.NMEAStreamReader() gps_loc_msg = None for msg in gps_data.split('\n'): if len(str(msg)) > 50 and 'GPGGA' in msg: gps_loc_msg = pynmea2.parse(msg[:-1]) if gps_loc_msg == None: return (0, 0, 0) return (gps_loc_msg.latitude, gps_loc_msg.longitude, gps_loc_msg.horizontal_dil)
def test_yield_errors(): sr = pynmea2.NMEAStreamReader(errors='yield') assert list(sr.next('foobar')) == [] data = list(sr.next('foo\n' + DATA)) assert len(data) == 2 assert isinstance(data[0], pynmea2.ParseError) assert isinstance(data[1], pynmea2.GGA)
def build_payload(variable_3): # Creates two random values for sending data # value_1 = random.randint(-10, 50) #value_2 = random.randint(0, 85) # Creates a random gps coordinates dataout = pynmea2.NMEAStreamReader() newdata = ser.readline() #print ("Get Latitude and Longitude") #print(newdata) #time.sleep(5) if newdata[0:6] == '$GPGGA': newmsg = pynmea2.parse(newdata) lat = newmsg.latitude print(lat) lng = newmsg.longitude print(lng) payload = { variable_3: { "value": 1, "context": { "lat": lat, "lng": lng } } } return payload time.sleep(10)
def getCoord(): try: if 'lat' not in getCoord.__dict__: getCoord.lat = 0 if 'lon' not in getCoord.__dict__: getCoord.lon = 0 # Some half-assed static variables ser = serial.Serial('/dev/ttyAMA0', baudrate=9600, timeout=10) # Open serial comm on ttyS0 dataout = pynmea2.NMEAStreamReader() # This is our GPS code parser timing = 0 while True: newdata = ser.readline() # Read a line from serial device if newdata[ 0:6] == '$GPGGA': # If line contains GPS coordinate info newmsg = pynmea2.parse(newdata) # Parse it getCoord.lat = newmsg.latitude # Store the values accordingly getCoord.lon = newmsg.longitude break ser.close() # Close serial comm except KeyboardInterrupt: ser.close() quit() print(getCoord.lat, getCoord.lon) return getCoord.lat, getCoord.lon
def _main(): from mqtt_utils import EUREC4AMqttPublisher streamreader = pynmea2.NMEAStreamReader() assets = ["33RO"] sources = { asset: http_iter( "https://seb.noaa.gov/pub/flight/aamps_ingest/ship/{}.txt".format( asset)) for asset in assets } asset_states = {asset: NMEAAssetState() for asset in assets} asset_platform_ids = {"33RO": "RHB"} with EUREC4AMqttPublisher() as publisher: while True: for asset in assets: for msg in streamreader.next( next(sources[asset]).decode("ascii")): asset_states[asset].update(msg) publisher.publish("platform/{}/location".format( asset_platform_ids[asset]), asset_states[asset].to_dict(), retain=True)
def read(filename): f = open(filename) reader = pynmea2.NMEAStreamReader(f) while 1: for msg in reader.next(): print(msg)
def GPS_Info(): global gps global map_link port="/dev/ttyUSB0" ser=serial.Serial(port,baudrate=9600,timeout=0.5) dataout =pynmea2.NMEAStreamReader() newdata=ser.readline() print(newdata) if newdata[0:6]==b'$GPRMC': newmsg=pynmea2.parse(newdata.decode('ASCII')) lat=newmsg.latitude lng=newmsg.longitude lat_in_degrees = convert_to_degrees(lat) #get latitude in degree decimal format long_in_degrees = convert_to_degrees(lng) gps="Latitude=" +str(lat) + "and Longitude=" +str(lng) map_link='http://maps.google.com/?q=' + str(lat)+ ',' + str(lng) print(map_link) print(gps)
def test_iter(): sr = pynmea2.NMEAStreamReader(StringIO(DATA)) for batch in sr: for msg in batch: assert isinstance(msg, pynmea2.GGA) break break
def main(portNum): reader = pynmea2.NMEAStreamReader() ser = serial.Serial( port= gpsPorts[portNum],\ baudrate=baudRate,\ parity =serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ bytesize=serial.EIGHTBITS,\ timeout=0) lastGPRMC = time.time() lastGPGGA = time.time() delta = 2 print("connected to: " + ser.portstr) #this will store the line line = [] while True: try: for c in ser.read(): line.append(chr(c)) if chr(c) == '\n': dataString = (''.join(line)) dateTime = datetime.datetime.now() mSR.GPSRawWrite(dataString, dateTime) line = [] break except: print("Incomplete String Read") line = [] ser.close()
def __init__(self, rx_queue, serial_port): threading.Thread.__init__(self) self.runSignal = True try: self.ser = serial.Serial(port=serial_port, baudrate=4800) except serial.serialutil.SerialException: print("Serial Permission Error") self.streamreader = pynmea2.NMEAStreamReader()
def read(filename): f = open(filename) reader = pynmea2.NMEAStreamReader(f) while 1: for msg in reader.next(): print(msg) test_proprietary_type_SCM(msg)
def __init__(self): rospy.loginfo("Initialising GPS publishing") self.lastMsg = None self.gps_pub = rospy.Publisher('/gps', NavSatFix, queue_size=10) rospy.sleep(1) self.port = "/dev/ttyS0" self.ser = serial.Serial(self.port, baudrate=9600, timeout=2) self.dataout = pynmea2.NMEAStreamReader() rospy.loginfo("initialised")
def readnmea_file(filename): f = open(filename, mode='r', encoding='ascii') reader = nmea.NMEAStreamReader(f) while 1: for msg in reader.next(): print(msg) print(msg.sentence_type) print(msg.talker)
def read(filename): f = open(filename) reader = pynmea2.NMEAStreamReader(f) while 1: for msg in reader.next(): #obj.getParams(msg) antenna.calcDir(obj) antenna.printDir()
def callback(data): msg = pynmea2.parse(data.data) print (msg) streamreader = pynmea2.NMEAStreamReader (msg) #print (msg.lat) rospy.loginfo(rospy.get_caller_id() + " Latitude %s %s %s", msg.latitude, msg.latitude_minutes, msg.latitude_seconds) rospy.loginfo(rospy.get_caller_id() + " Longitude %s %s %s", msg.longitude, msg.longitude_minutes, msg.longitude_seconds)
def __init__(self, nmea_stream, gtfs_file=None): if 'http' in nmea_stream: input_stream = urllib.urlopen(nmea_stream) stream = pynmea2.NMEAStreamReader(input_stream) self.stream = stream if gtfs_file is not None: with open(gtfs_file) as gtfs: self.gtfs = gtfs
def gps(latitude,longitude): dataout = pynmea2.NMEAStreamReader() newdata=ser.readline() if newdata[0:6] == b'$GPRMC': newmsg=pynmea2.parse(newdata.decode('ASCII')) lat=round(newmsg.latitude,6) lng=round(newmsg.longitude,6) gps = "Latitude=" + str(lat) + "and Longitude=" + str(lng) print(gps)
def test_stream(): sr = pynmea2.NMEAStreamReader() assert len(list(sr.next(''))) == 0 assert len(list(sr.next(DATA))) == 1 assert len(list(sr.next(DATA))) == 1 sr = pynmea2.NMEAStreamReader() assert len(list(sr.next(DATA))) == 1 assert len(list(sr.next(DATA[:10]))) == 0 assert len(list(sr.next(DATA[10:]))) == 1 sr = pynmea2.NMEAStreamReader() assert list(sr.next()) == [] f = StringIO(DATA * 2) sr = pynmea2.NMEAStreamReader(f) assert len(list(sr.next())) == 1 assert len(list(sr.next())) == 1 assert len(list(sr.next())) == 0
def __update__(): global newmsg, lat, lon dataout = pynmea2.NMEAStreamReader() newdata = ser.readline().decode("ascii", errors='replace') #print(newdata); if newdata[0:6] == "$GPRMC": newmsg = pynmea2.parse(newdata) lat = newmsg.latitude lon = newmsg.longitude
def run(self): com = None reader = pynmea2.NMEAStreamReader() while not self.event.is_set(): if self.gps_enable: if com is None: try: com = serial.Serial(GPS_SERIAL_DEVICE, timeout=5.0) except serial.SerialException: self.log.warning("GPS device missing") self.gps_avail = False time.sleep(15.0) else: self.log.warning("GPS device detected") try: data = com.read() for msg in reader.next(data): parsed = pynmea2.parse(str(msg)) try: if isinstance(parsed, pynmea2.types.talker.GGA): self.gps_quality = parsed.gps_qual self.num_sats = parsed.num_sats if self.gps_quality > 0 and self.gps_quality < 7: self.gps_avail = True self.log.debug("quality:" + str(self.gps_quality) + " #sats:" + str(self.num_sats)) self.gps_timestamp = parsed.timestamp self.lat = str(parsed.latitude) + str( parsed.lat_dir) self.long = str(parsed.longitude).replace( "-", "") + str(parsed.lon_dir) self.alt = str(parsed.altitude) self.alt_unit = str(parsed.altitude_units) self.log.debug("timestamp:" + str(self.gps_timestamp)) # log lat+lon that can be parsed by http://maps.google.com self.log.debug("lat long:" + self.lat + " " + self.long + " alt:" + self.alt + "(" + self.alt_unit + ")") except Exception as e: self.gps_avail = False self.log.error(str(e)) time.sleep(1) except Exception as e: # Force Reconnect com = None self.gps_avail = False self.log.error("GPS device lost.") else: time.sleep(10)
def dump_serial(filename): with serial.Serial(filename) as port: reader = pynmea2.NMEAStreamReader(port) while True: try: for msg in reader.next(): print("%r\n" % msg) except KeyboardInterrupt: break except: print("Could not parse record\n")
def __init__(self, port="/dev/ttyAMA0", quit_event=None): self.gps = serial.Serial(port) self.stream = pynmea2.NMEAStreamReader(self.gps) self.date = None self.time = None self.position = None if quit_event is not None: self.quit_event = quit_event else: self.quit_event = threading.Event() threading.Thread.__init__(self, name="GPS")