在python3中的同一字典中从两个实例获取信息

时间:2018-08-30 08:25:46

标签: python-3.x gps

我编写了一个脚本,该脚本从GPS模块获取信息并将其推送到InfluxDB。我正在使用GPGGAGPRMC NMEA语句来获取以下值:

  1. 纬度
  2. 经度
  3. 海拔
  4. 地面速度

我正在使用pynmea2来解析NMEA句子。由于我是从串行端口读取的,因此我正在使用NMEAStreamReader()

代码

while True:
        if com is None:
            try:
               # set the serial port 
        try:
              # read the information (NMEA sentence)
        except Exception as e:
            logger.error(e)
            pass

        try:
            # for sentence obtained from reader    
            for msg in reader.next(data):
                measurements = {} # create a measurement dict

                dat = pynmea2.parse(str(msg).strip('\r\n')) # parse the sentence
                if not (dat.latitude == 0.0 and dat.longitude == 0.0):
                    # If Latitude and Longitude are not 0.0
                    if isinstance(dat, pynmea2.GGA): # if GPGGA
                        # Store Latitude Longitude Altitude in `measurements`
                        measurements['lat'] = dat.latitude
                        # measurements['lat_dir'] = dat.lat_dir
                        measurements['lon'] = dat.longitude
                        # measurements['lon_dir'] = dat.lon_dir
                        measurements['alt'] = dat.altitude

                    if isinstance(dat, pynmea2.RMC):
                       # if sentence is RMC store latitude, longitude, speed over ground
                        measurements['lat'] = dat.latitude
                        # measurements['lat_dir'] = dat.lat_dir
                        measurements['lon'] = dat.longitude
                        # measurements['lon_dir'] = dat.lon_dir
                        measurements['spd_over_grnd'] = dat.spd_over_grnd
                    # print(measurements)
                    client.write_points([{
                            'measurement': 'gps',
                            'tags': {
                                'type': 'gps-adafruit',
                            },
                            'time': datetime.datetime.utcnow().isoformat('T') + 'Z',
                            'fields': measurements
                        }])
                else:
                    print('Location Values not available yet. Not writing to DB')
        except Exception as e:
            logger.error(e)
pass

问题

如果GGA句子可用,则进入DB的条目为lat, long, alt。如果RMC句子可用,则进入DB的条目为lat, long, spd_over_ground(该句子中没有海拔高度)

我想拥有measurements字典,如下所示:

{
  'lat': 23.034, <- from GGA
  'lon': 4.3455, <- from GGA
  'alt': '2.45', <- from GGA
  'spd_over_grnd': 2.2 <- from RMC
}

问题是因为NMEA句子被\r\n终止,所以我必须等到下一次被解析,然后我的measurements已经存储在数据库中。

存储库

gpsinflux

0 个答案:

没有答案