当前位置: 首页>>代码示例>>Python>>正文


Python pynmea2.parse方法代码示例

本文整理汇总了Python中pynmea2.parse方法的典型用法代码示例。如果您正苦于以下问题:Python pynmea2.parse方法的具体用法?Python pynmea2.parse怎么用?Python pynmea2.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pynmea2的用法示例。


在下文中一共展示了pynmea2.parse方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: gnss_nmea_gga

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def gnss_nmea_gga():
    """
    Get NMEA GGA data parsed into dict.
    """

    res = query('AT+QGPSGNMEA="{:s}"'.format("gga"))
    if "data" in res:
        sentence = _parse_dict(res.pop("data"))["+QGPSGNMEA"]

        obj = pynmea2.parse(sentence, check=True)
#        if obj.is_valid:
        res.update({
            "utc": obj.timestamp.isoformat(),
            "latitude": obj.latitude,
            "longitude": obj.longitude,
            "altitude": float(obj.altitude),
        })

    return res 
开发者ID:autopi-io,项目名称:autopi-core,代码行数:21,代码来源:ec2x.py

示例2: convert_nmea_to_json

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def convert_nmea_to_json(nmea_str, filename, GMT_OFFSET=0):
    json_list = []
    filename = filename.strip('.LOG').strip('N')
    year = 2000 + int(filename[0:2])
    month = int(filename[2:4])
    day = int(filename[4:6])
    print(year, month, day)
    for line in nmea_str.split('\n'):
        line = line.strip()
        if '@' in line or 'GPRMC' in line or len(line) == 0:
            continue
        record = pynmea2.parse(line)
        dt = record.timestamp
        dt = datetime(year, month, day, dt.hour, dt.minute, dt.second)
        # Gather values
        posix = int(dt.strftime("%s"))
        posix += (60 * 60 * GMT_OFFSET)
        lat   = float(record.latitude)
        lon   = float(record.longitude)
        json_list.append({
            'time': posix,
            'lat':  lat,
            'lon':  lon,
        })
    return json.dumps({ "track": json_list }) 
开发者ID:Erotemic,项目名称:ibeis,代码行数:27,代码来源:appfuncs.py

示例3: _set_platform_dict

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def _set_platform_dict(self):
        out_dict = dict()
        # TODO: Need to reconcile the logic between using the unpacked "survey_name"
        #  and the user-supplied platform_name
        # self.platform_name = self.config_datagram['survey_name']
        out_dict['platform_name'] = self.platform_name
        out_dict['platform_type'] = self.platform_type
        out_dict['platform_code_ICES'] = self.platform_code_ICES

        # Read pitch/roll/heave from ping data
        out_dict['ping_time'] = self.ping_time  # [seconds since 1900-01-01] for xarray.to_netcdf conversion
        out_dict['pitch'] = np.array(self.mru_data['pitch'])
        out_dict['roll'] = np.array(self.mru_data['roll'])
        out_dict['heave'] = np.array(self.mru_data['heave'])
        out_dict['water_level'] = self.environment['water_level_draft']

        # Read lat/long from NMEA datagram
        idx_loc = np.argwhere(np.isin(self.nmea_data.messages, ['GGA', 'GLL', 'RMC'])).squeeze()
        nmea_msg = []
        [nmea_msg.append(pynmea2.parse(self.nmea_data.raw_datagrams[x])) for x in idx_loc]
        out_dict['lat'] = np.array([x.latitude for x in nmea_msg])
        out_dict['lon'] = np.array([x.longitude for x in nmea_msg])
        out_dict['location_time'] = self.nmea_data.nmea_times[idx_loc]
        return out_dict 
开发者ID:OSOceanAcoustics,项目名称:echopype,代码行数:26,代码来源:ek80.py

示例4: gnss_nmea_gsa

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def gnss_nmea_gsa():
    """
    Get NMEA GSA data parsed into dict.
    """

    res = query('AT+QGPSGNMEA="{:s}"'.format("gsa"))
    if "data" in res:
        sentence = _parse_dict(res.pop("data"))["+QGPSGNMEA"]

        obj = pynmea2.parse(sentence, check=True)
        fix_prns = [getattr(obj, "sv_id{:02d}".format(idx)) for idx in range(1, 13)]
        fix_sat_count = len(fix_prns)

        res.update({
            "mode": obj.mode,
            "fix": "{:}D".format(obj.mode_fix_type),
            "fix_prns": fix_prns,
            "fix_sat_count": fix_sat_count,
            "pdop": float(obj.pdop) if obj.pdop else None,
            "hdop": float(obj.hdop) if obj.hdop else None,
            "vdop": float(obj.vdop) if obj.vdop else None,
        })

    return res 
开发者ID:autopi-io,项目名称:autopi-core,代码行数:26,代码来源:ec2x.py

示例5: parse_gps_sentence

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def parse_gps_sentence(sentence):
    """Parse an NMEA 0183 formatted data sample.

    Parameters
    ----------
    sentence : str
        A NMEA 0183 formatted "sentence" with the prefix $GPRMC
        (Recommended minimum specific GPS/Transit data)

    Returns
    -------
    A pynmea2.types.talker.RMC object

    References
    ----------
    http://aprs.gids.nl/nmea (NMEA Sentence Information)
    """
    try:
        gps = pynmea2.parse(sentence)
        if not gps.is_valid:
            gps = None

    except pynmea2.nmea.SentenceTypeError:
        gps = None

    return gps 
开发者ID:openoakland,项目名称:woeip,代码行数:28,代码来源:dustrak.py

示例6: get_lat_lon_time_from_gpx

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def get_lat_lon_time_from_gpx(gpx_file, local_time=True):
    '''
    Read location and time stamps from a track in a GPX file.

    Returns a list of tuples (time, lat, lon).

    GPX stores time in UTC, by default we assume your camera used the local time
    and convert accordingly.
    '''
    with open(gpx_file, 'r') as f:
        gpx = gpxpy.parse(f)

    points = []
    if len(gpx.tracks) > 0:
        for track in gpx.tracks:
            for segment in track.segments:
                for point in segment.points:
                    t = utc_to_localtime(point.time) if local_time else point.time
                    points.append((t, point.latitude, point.longitude, point.elevation))
    if len(gpx.waypoints) > 0:
        for point in gpx.waypoints:
            t = utc_to_localtime(point.time) if local_time else point.time
            points.append((t, point.latitude, point.longitude, point.elevation))

    # sort by time just in case
    points.sort()

    return points 
开发者ID:mapillary,项目名称:mapillary_tools,代码行数:30,代码来源:gps_parser.py

示例7: get_lat_lon_time_from_nmea

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def get_lat_lon_time_from_nmea(nmea_file, local_time=True):
    '''
    Read location and time stamps from a track in a NMEA file.

    Returns a list of tuples (time, lat, lon).

    GPX stores time in UTC, by default we assume your camera used the local time
    and convert accordingly.
    '''
    with open(nmea_file, "r") as f:
        lines = f.readlines()
        lines = [l.rstrip("\n\r") for l in lines]

    # Get initial date
    for l in lines:
        if "GPRMC" in l:
            data = pynmea2.parse(l)
            date = data.datetime.date()
            break

    # Parse GPS trace
    points = []
    for l in lines:
        if "GPRMC" in l:
            data = pynmea2.parse(l)
            date = data.datetime.date()

        if "$GPGGA" in l:
            data = pynmea2.parse(l)
            timestamp = datetime.datetime.combine(date, data.timestamp)
            lat, lon, alt = data.latitude, data.longitude, data.altitude
            points.append((timestamp, lat, lon, alt))

    points.sort()
    return points 
开发者ID:mapillary,项目名称:mapillary_tools,代码行数:37,代码来源:gps_parser.py

示例8: _set_platform_dict

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def _set_platform_dict(self, out_file=None, piece_seq=0):
        out_dict = dict()
        # TODO: Need to reconcile the logic between using the unpacked "survey_name"
        #  and the user-supplied platform_name
        # self.platform_name = self.config_datagram['survey_name']
        out_dict['platform_name'] = self.platform_name
        out_dict['platform_type'] = self.platform_type
        out_dict['platform_code_ICES'] = self.platform_code_ICES

        # Read pitch/roll/heave from ping data
        # [seconds since 1900-01-01] for xarray.to_netcdf conversion
        out_dict['ping_time'] = self.ping_time
        out_dict['pitch'] = np.array(self.ping_data_dict[1]['pitch'], dtype='float32')
        out_dict['roll'] = np.array(self.ping_data_dict[1]['roll'], dtype='float32')
        out_dict['heave'] = np.array(self.ping_data_dict[1]['heave'], dtype='float32')
        # water_level is set to 0 for EK60 since this is not separately recorded
        # and is part of transducer_depth
        out_dict['water_level'] = np.int32(0)

        # Read lat/long from NMEA datagram
        idx_loc = np.argwhere(np.isin(self.nmea_data.messages, ['GGA', 'GLL', 'RMC'])).squeeze()
        # TODO: use NaN when nmea_msg is empty
        nmea_msg = []
        [nmea_msg.append(pynmea2.parse(self.nmea_data.raw_datagrams[x])) for x in idx_loc]
        out_dict['lat'] = np.array([x.latitude for x in nmea_msg])
        out_dict['lon'] = np.array([x.longitude for x in nmea_msg])
        out_dict['location_time'] = self.nmea_data.nmea_times[idx_loc]

        if len(self.range_lengths) > 1:
            out_dict['path'] = self.all_files[piece_seq]
            out_dict['ping_slice'] = self.ping_time_split[piece_seq]
            out_dict['overwrite_plat'] = True if piece_seq == 1 else False
        else:
            out_dict['path'] = out_file
            out_dict['overwrite_plat'] = False
        return out_dict 
开发者ID:OSOceanAcoustics,项目名称:echopype,代码行数:38,代码来源:ek60.py

示例9: parse_as_dict

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def parse_as_dict(sentence, check=True, verbose=False):
    ret = {}

    if verbose:
        ret["sentence"] = sentence

    obj = pynmea2.parse(sentence, check=True)
    ret["data_type"] = obj.__class__.__name__

    for f in obj.fields:
        desc = f[0]
        attr = f[1]
        val = getattr(obj, attr)

        if not val and not verbose:
            continue

        # Workaround because msgpack will not serialize datetime.date, datetime.time and decimal.Decimal
        if isinstance(val, datetime.date):
            val = str(val)
        elif isinstance(val, datetime.time):
            val = str(val)
        elif isinstance(val, decimal.Decimal):
            val = float(val)
        # TODO: Temp fix to get correct types because pynmea2 does not handle it
        elif attr.startswith("num_") or attr.endswith("_num") or "_num_" in attr:
            val = int(val)
        elif attr.startswith("snr_") or attr.startswith("azimuth_"):
            val = float(val)

        ret[attr] = val if not verbose else {
            "description": desc,
            "value": val
        }

    return ret 
开发者ID:autopi-io,项目名称:autopi-core,代码行数:38,代码来源:nmea_util.py

示例10: gnss_nmea_gsv

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def gnss_nmea_gsv():
    """
    Get list where entries are grouped by all available satellites in NMEA GSV data.
    """

    res = query('AT+QGPSGNMEA="{:s}"'.format("gsv"))
    if "data" in res:
        values = []

        sentences = _parse_dict(res.pop("data"), multiline=True)["+QGPSGNMEA"]
        for sentence in sentences:
            obj = pynmea2.parse(sentence, check=True)

            msg_idx = int(obj.msg_num)
            msg_count = int(obj.num_messages)
            sat_count = int(obj.num_sv_in_view)

            for idx in range(1, 5): # Max 4 satellites in each sentence
                prn = getattr(obj, "sv_prn_num_{:d}".format(idx))
                if not prn:
                    continue

                azimuth = getattr(obj, "azimuth_{:d}".format(idx))
                elevation = getattr(obj, "elevation_deg_{:d}".format(idx))
                snr = getattr(obj, "snr_{:d}".format(idx))

                values.append({
                    "msg_idx": msg_idx,
                    "msg_count": msg_count,
                    "sat_count": sat_count,
                    "prn": prn,
                    "azimuth": float(azimuth) if azimuth else None,
                    "elevation": float(elevation) if elevation else None,
                    "snr": float(snr) if snr else None,
                })

        res["values"] = values

    return res 
开发者ID:autopi-io,项目名称:autopi-core,代码行数:41,代码来源:ec2x.py

示例11: nmea0183_readout_handler

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def nmea0183_readout_handler():
    """
    Reads all available NMEA0183 sentences through serial connection.
    """

    ret = {}

    # Read lines from serial connection
    lines = conn.read_lines()
    if not lines:
        log.warn("No NMEA0183 sentences available")

        return ret

    # Parse NMEA sentences
    for line in lines:
        try:
            obj = pynmea2.parse(line, check=True)

            # Put into dict indexed by type
            name = obj.__class__.__name__.lower()
            if name in ret:
                if isinstance(ret[name], list):
                    ret[name].append(obj)
                else:
                    ret[name] = [ret[name], obj]
            else:
                ret[name] = obj

        except Exception:
            log.exception("Failed to parse NMEA0183 sentence: {:}".format(line))

    return ret 
开发者ID:autopi-io,项目名称:autopi-core,代码行数:35,代码来源:tracking_manager.py

示例12: load_ek80_raw

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def load_ek80_raw(self, raw):
        """Method to parse the EK80 ``.raw`` data file.

        This method parses the ``.raw`` file and saves the parsed data
        to the ConvertEK80 instance.

        Parameters
        ----------
        raw : str
            raw filename
        """
        print('%s  converting file: %s' % (dt.now().strftime('%H:%M:%S'), os.path.basename(raw)))

        with RawSimradFile(raw, 'r') as fid:
            self.config_datagram = fid.read(1)
            self.config_datagram['timestamp'] = np.datetime64(self.config_datagram['timestamp'], '[ms]')

            # IDs of the channels found in the dataset
            self.ch_ids = list(self.config_datagram[self.config_datagram['subtype']])

            for ch_id in self.ch_ids:
                self.ping_data_dict[ch_id] = defaultdict(list)
                self.ping_data_dict[ch_id]['frequency'] = \
                    self.config_datagram['configuration'][ch_id]['transducer_frequency']
                self.power_dict[ch_id] = []
                self.angle_dict[ch_id] = []
                self.complex_dict[ch_id] = []

                # Parameters recorded for each frequency for each ping
                self.parameters[ch_id]['frequency_start'] = []
                self.parameters[ch_id]['frequency_end'] = []
                self.parameters[ch_id]['frequency'] = []
                self.parameters[ch_id]['pulse_duration'] = []
                self.parameters[ch_id]['pulse_form'] = []
                self.parameters[ch_id]['sample_interval'] = []
                self.parameters[ch_id]['slope'] = []
                self.parameters[ch_id]['transmit_power'] = []
                self.parameters[ch_id]['timestamp'] = []

            # Read the rest of datagrams
            self._read_datagrams(fid)
            # Remove empty lists
            for ch_id in self.ch_ids:
                if all(x is None for x in self.power_dict[ch_id]):
                    self.power_dict[ch_id] = None
                if all(x is None for x in self.complex_dict[ch_id]):
                    self.complex_dict[ch_id] = None

        if len(self.ch_ids) != len(self.recorded_ch_ids):
            self.ch_ids = self.recorded_ch_ids 
开发者ID:OSOceanAcoustics,项目名称:echopype,代码行数:52,代码来源:ek80.py

示例13: load_ek60_raw

# 需要导入模块: import pynmea2 [as 别名]
# 或者: from pynmea2 import parse [as 别名]
def load_ek60_raw(self, raw):
        """Method to parse the EK60 ``.raw`` data file.

        This method parses the ``.raw`` file and saves the parsed data
        to the ConvertEK60 instance.

        Parameters
        ----------
        raw : string
            raw filename
        """
        print('%s  converting file: %s' % (dt.now().strftime('%H:%M:%S'), os.path.basename(raw)))

        with RawSimradFile(raw, 'r') as fid:
            # Read the CON0 configuration datagram. Only keep 1 if multiple files
            if self.config_datagram is None:
                self.config_datagram = fid.read(1)
                self.config_datagram['timestamp'] = np.datetime64(
                    self.config_datagram['timestamp'].replace(tzinfo=None), '[ms]')

                for ch_num in self.config_datagram['transceivers'].keys():
                    self.ping_data_dict[ch_num] = defaultdict(list)
                    self.ping_data_dict[ch_num]['frequency'] = \
                        self.config_datagram['transceivers'][ch_num]['frequency']
                    self.power_dict[ch_num] = []
                    self.angle_dict[ch_num] = []
            else:
                tmp_config = fid.read(1)

            # Check if reading an ME70 file with a CON1 datagram.
            next_datagram = fid.peek()
            if next_datagram == 'CON1':
                self.CON1_datagram = fid.read(1)
            else:
                self.CON1_datagram = None

            # Read the rest of datagrams
            self._read_datagrams(fid)

        # Split data based on range_group (when there is a switch of range_bin in the middle of a file)
        self.split_by_range_group()

        # Trim excess data from NMEA object
        self.nmea_data.trim()

    # Functions to set various dictionaries 
开发者ID:OSOceanAcoustics,项目名称:echopype,代码行数:48,代码来源:ek60.py


注:本文中的pynmea2.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。