### Install pynmea2 with pip Source: https://github.com/knio/pynmea2/blob/master/README.md Install the pynmea2 library using pip. This is the recommended installation method. ```bash pip install pynmea2 ``` -------------------------------- ### Install pynmea2 from source Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Install pynmea2 in editable mode from its GitHub repository. This is useful for making direct changes to the library's source code. ```bash pip install -e git+https://github.com/Knio/pynmea2.git ``` -------------------------------- ### Parse Common NMEA Sentence Types Source: https://context7.com/knio/pynmea2/llms.txt Examples of parsing common NMEA sentence types like GGA, RMC, and GSV, demonstrating access to their key properties. ```python import pynmea2 ``` -------------------------------- ### Define a custom TalkerSentence Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Create a custom NMEA sentence class by extending pynmea2.TalkerSentence. Define the 'fields' tuple to map sentence data to attributes. This example defines a THS sentence. ```python import pynmea2 from pynmea2 import TalkerSentence from decimal import Decimal from pynmea2.nmea_utils import * class THS(TalkerSentence): fields = ( ("Heading", "heading", Decimal), ("A", "A"), ) pynmea2.parse('$HETHS,141.10,A*18') ``` -------------------------------- ### Proprietary Sentence: UBX00 type Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Example of a custom proprietary sentence class (UBX00) that extends pynmea2.ProprietarySentence. It handles cases where the sentence type is formed by combining the manufacturer code and a specific data field. ```python # pynmea2\types\proprietary\ubx.py class UBX(nmea.ProprietarySentence): sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[1] cls = _cls.sentence_types.get(name, _cls) return super(UBX, cls).__new__(cls) def __init__(self, manufacturer, data): self.sentence_type = manufacturer + data[1] super(UBX, self).__init__(manufacturer, data[2:]) class UBX00(UBX, LatLonFix): ... ``` -------------------------------- ### Proprietary Sentence: GRM type Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Example of a custom proprietary sentence class (GRM) where the sentence type is determined by the manufacturer code and the first data field. This class extends pynmea2.ProprietarySentence. ```python # pynmea2\types\proprietary\grm.py class GRM(nmea.ProprietarySentence): sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[0] cls = _cls.sentence_types.get(name, _cls) return super(GRM, cls).__new__(cls) def __init__(self, manufacturer, data): self.sentence_type = manufacturer + data[0] super(GRM, self).__init__(manufacturer, dat) class GRME(GRM): fields = ( ("Subtype", "subtype"), ... ``` -------------------------------- ### Import necessary utilities Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Import functions from pynmea2.nmea_utils and the Decimal type for use in custom sentence field conversions. ```python from pynmea2.nmea_utils import * from decimal import Decimal ``` -------------------------------- ### Create a GGA NMEA sentence object Source: https://github.com/knio/pynmea2/blob/master/README.md Instantiate a NMEA sentence object, specifically a GGA message, by providing the talker, message type, and a tuple of data fields. ```python import pynmea2 msg = pynmea2.GGA('GP', 'GGA', ('184353.07', '1929.045', 'S', '02410.506', 'E', '1', '04', '2.6', '100.00', 'M', '-33.9', 'M', '', '0000')) ``` -------------------------------- ### Read NMEA Log Files with NMEAFile Source: https://context7.com/knio/pynmea2/llms.txt Use the NMEAFile class to read and parse NMEA log files. Supports context managers, iteration, and reading all sentences at once. ```python import pynmea2 with pynmea2.NMEAFile('gps_log.nmea') as nmea_file: for msg in nmea_file: if hasattr(msg, 'latitude'): print(f"Position: {msg.latitude}, {msg.longitude}") ``` ```python import pynmea2 nmea_file = pynmea2.NMEAFile('gps_log.nmea') all_sentences = nmea_file.read() nmea_file.close() ``` ```python import pynmea2 nmea_file = pynmea2.NMEAFile('gps_log.nmea') while True: msg = nmea_file.readline() if not msg: break print(repr(msg)) nmea_file.close() ``` ```python import pynmea2 with open('examples/data.log', encoding='utf-8') as file: for line in file.readlines(): try: msg = pynmea2.parse(line) print(repr(msg)) except pynmea2.ParseError as e: print(f'Parse error: {e}') continue ``` -------------------------------- ### Generate NMEA GGA Sentence Source: https://context7.com/knio/pynmea2/llms.txt Create NMEA sentence objects programmatically using classes like pynmea2.GGA. This allows generating valid NMEA strings with automatic checksum calculation for simulation or device communication. ```python import pynmea2 # Create a GGA sentence with talker ID, sentence type, and data fields msg = pynmea2.GGA('GP', 'GGA', ( '184353.07', # timestamp '1929.045', # latitude 'S', # latitude direction '02410.506', # longitude 'E', # longitude direction '1', # GPS quality indicator '04', # number of satellites '2.6', # horizontal dilution '100.00', # altitude 'M', # altitude units '-33.9', # geoidal separation 'M', # geo sep units '', # age of GPS data '0000' # reference station ID )) # To get the NMEA string, you would typically convert the object to a string: # print(str(msg)) ``` -------------------------------- ### Convert NMEA to GPX Source: https://context7.com/knio/pynmea2/llms.txt Converts NMEA log files to GPX format for use with mapping applications. Requires date for timestamping. ```python import pynmea2 import xml.dom.minidom import datetime def nmea_to_gpx(nmea_file_path, output_path, date=None): """Convert NMEA log file to GPX format""" doc = xml.dom.minidom.Document() root = doc.createElement('gpx') root.setAttribute('version', '1.1') root.setAttribute('xmlns', 'http://www.topografix.com/GPX/1/1') doc.appendChild(root) trk = doc.createElement('trk') trkseg = doc.createElement('trkseg') trk.appendChild(trkseg) root.appendChild(trk) with open(nmea_file_path) as f: for line in f: try: msg = pynmea2.parse(line) except pynmea2.ParseError: continue # Only process sentences with position data if not (hasattr(msg, 'latitude') and hasattr(msg, 'longitude')): continue trkpt = doc.createElement('trkpt') trkpt.setAttribute('lat', f'{msg.latitude:.6f}') trkpt.setAttribute('lon', f'{msg.longitude:.6f}') if hasattr(msg, 'altitude') and msg.altitude: ele = doc.createElement('ele') ele.appendChild(doc.createTextNode(f'{msg.altitude:.3f}')) trkpt.appendChild(ele) if date and hasattr(msg, 'timestamp'): time_elem = doc.createElement('time') dt = datetime.datetime.combine(date, msg.timestamp) time_elem.appendChild(doc.createTextNode(dt.isoformat() + 'Z')) trkpt.appendChild(time_elem) trkseg.appendChild(trkpt) with open(output_path, 'w') as f: f.write(doc.toprettyxml(indent=' ')) # Usage mea_to_gpx('gps_log.nmea', 'track.gpx', date=datetime.date.today()) ``` -------------------------------- ### Define and Parse Custom Talker Sentence Source: https://context7.com/knio/pynmea2/llms.txt Extends pynmea2 to support a custom Talker Sentence (e.g., $GPXYZ) by defining its fields. ```python import pynmea2 from pynmea2 import TalkerSentence from pynmea2.nmea_utils import timestamp # Custom Talker Sentence class XYZ(TalkerSentence): """Custom sensor data sentence""" fields = ( ("Timestamp", "timestamp", timestamp), ("Sensor Value", "sensor_value", float), ("Unit", "unit"), ("Status", "status"), ) # Now pynmea2 can parse $GPXYZ sentences msg = pynmea2.parse("$GPXYZ,120000.00,23.5,C,A*XX") print(f"Custom: value={msg.sensor_value}{msg.unit}, status={msg.status}") ``` -------------------------------- ### Read NMEA Data from Serial Port with pySerial Source: https://context7.com/knio/pynmea2/llms.txt Integrate pynmea2 with pySerial to read NMEA data from serial devices in real-time. Includes configuration for typical GPS devices and continuous reading loop. ```python import io import pynmea2 import serial ser = serial.Serial( port='/dev/ttyUSB0', # or 'COM3' on Windows baudrate=9600, # standard GPS baud rate timeout=5.0 ) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) while True: try: line = sio.readline() msg = pynmea2.parse(line) if isinstance(msg, pynmea2.GGA): print(f"Fix: {msg.latitude}, {msg.longitude}, Alt: {msg.altitude}m") print(f"Quality: {msg.gps_qual}, Satellites: {msg.num_sats}") elif isinstance(msg, pynmea2.RMC): print(f"Speed: {msg.spd_over_grnd} knots, Course: {msg.true_course}°") if msg.is_valid: print(f"Valid fix at {msg.datetime}") elif isinstance(msg, pynmea2.GSV): print(f"Satellites in view: {msg.num_sv_in_view}") except serial.SerialException as e: print(f'Device error: {e}') break except pynmea2.ParseError as e: print(f'Parse error: {e}') continue ``` -------------------------------- ### Define and Parse Custom Proprietary Sentence Source: https://context7.com/knio/pynmea2/llms.txt Extends pynmea2 to support custom proprietary sentences with sub-types, defining fields for specific sentence types. ```python import pynmea2 from pynmea2 import ProprietarySentence from decimal import Decimal # Custom Proprietary Sentence with sub-types class ABC(ProprietarySentence): """Custom proprietary manufacturer""" sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[0] cls = _cls.sentence_types.get(name, _cls) return super(ABC, cls).__new__(cls) def __init__(self, manufacturer, data): self.sentence_type = manufacturer + data[0] super(ABC, self).__init__(manufacturer, data[1:]) class ABC01(ABC): """Sub-type 01 of ABC manufacturer""" fields = ( ("Temperature", "temp", Decimal), ("Pressure", "pressure", Decimal), ) # Parse custom proprietary sentence msg = pynmea2.parse("$PABC,01,25.5,1013.2*XX") print(f"Custom proprietary: temp={msg.temp}, pressure={msg.pressure}") ``` -------------------------------- ### Stream NMEA Data with NMEAStreamReader Source: https://context7.com/knio/pynmea2/llms.txt Process NMEA data from continuous sources like network connections or serial ports using NMEAStreamReader. Supports buffering and error handling. ```python import pynmea2 reader = pynmea2.NMEAStreamReader(errors='yield') data_chunk = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,47.0,M,,*47\r\n$GPRMC,123519,A" for msg in reader.next(data_chunk): if isinstance(msg, pynmea2.ParseError): print(f"Error: {msg}") else: print(f"Parsed: {msg.sentence_type}") more_data = ",4807.038,N,01131.000,W,022.4,084.4,230394,003.1,W*6A\r\n" for msg in reader.next(more_data): print(f"Parsed: {type(msg).__name__}") ``` ```python import pynmea2 with open('gps_log.nmea') as f: reader = pynmea2.NMEAStreamReader(stream=f, errors='ignore') for batch in reader: for msg in batch: if hasattr(msg, 'latitude'): print(f"{msg.latitude}, {msg.longitude}") ``` -------------------------------- ### Generate NMEA String with Checksum Source: https://context7.com/knio/pynmea2/llms.txt Generate an NMEA string from a message object, with options to control checksum, dollar prefix, and newline characters. ```python nmea_string = str(msg) print(nmea_string) ``` ```python print(msg.render(checksum=True, dollar=True, newline=False)) ``` ```python print(msg.render(checksum=False, dollar=False)) ``` ```python print(msg.render(newline=True)) ``` ```python print(msg.render(newline='\n')) ``` ```python msg.altitude = 150.0 msg.num_sats = '08' print(str(msg)) ``` -------------------------------- ### Read and parse NMEA sentences from a file Source: https://github.com/knio/pynmea2/blob/master/README.md Read lines from a file, attempting to parse each line as an NMEA sentence. Handles `ParseError` exceptions for invalid lines. ```python import pynmea2 file = open('examples/data.log', encoding='utf-8') for line in file.readlines(): try: msg = pynmea2.parse(line) print(repr(msg)) except pynmea2.ParseError as e: print('Parse error: {}'.format(e)) continue ``` -------------------------------- ### Parse Custom Proprietary Sentence Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Use `pynmea2.parse` to parse an instance of a custom proprietary sentence. Ensure the custom sentence class is defined and registered before parsing. ```python pynmea2.parse('$PIXSE,STATUS,00001000,00000604*6C') ``` -------------------------------- ### Control Checksum Validation with pynmea2.parse() Source: https://context7.com/knio/pynmea2/llms.txt Control checksum validation behavior using the 'checksums' parameter in pynmea2.parse(). Options include 'check' (default), 'required', and 'my_data_is_corrupt'. Handle potential ParseError, ChecksumError, and SentenceTypeError exceptions. ```python import pynmea2 # Default behavior: 'check' - validates checksum if present, accepts sentences without checksum msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D") # Require checksum - raises ChecksumError if missing try: msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000", checksums='required') except pynmea2.ChecksumError as e: print(f"Checksum required but missing: {e}") # Accept invalid checksums (use with caution - data may be corrupt) msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*FF", checksums='my_data_is_corrupt') # Handle parse errors gracefully try: msg = pynmea2.parse("invalid data") except pynmea2.ParseError as e: print(f"Parse error: {e}") try: msg = pynmea2.parse("$GPXXX,invalid*00") except pynmea2.SentenceTypeError as e: print(f"Unknown sentence type: {e}") ``` -------------------------------- ### Generate NMEA string from sentence object Source: https://github.com/knio/pynmea2/blob/master/README.md Convert a `NMEASentence` object back into its NMEA 0183 string representation, including the checksum. ```python str(msg) ``` -------------------------------- ### Parse MWV Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses an MWV sentence to extract wind angle, reference, speed, and units. ```python import pynmea2 mwv = pynmea2.parse("$WIMWV,214.8,R,15.8,K,A*28") print(f"MWV: angle={mwv.wind_angle}°, ref={mwv.reference}, speed={mwv.wind_speed}{mwv.wind_speed_units}") ``` -------------------------------- ### Parse NMEA GGA Sentence and Access Fields Source: https://context7.com/knio/pynmea2/llms.txt Use pynmea2.parse() to convert an NMEA GGA string into a sentence object. Access fields as typed properties and use computed properties for decimal degree coordinates. Coordinate formatting utilities are also available. ```python import pynmea2 # Parse a GGA (GPS Fix Data) sentence msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D") # Access parsed fields as typed properties print(msg.timestamp) # datetime.time(18, 43, 53, 70000) print(msg.lat) # '1929.045' print(msg.lat_dir) # 'S' print(msg.lon) # '02410.506' print(msg.lon_dir) # 'E' print(msg.gps_qual) # 1 (GPS quality indicator) print(msg.num_sats) # '04' print(msg.horizontal_dil) # '2.6' print(msg.altitude) # 100.0 (as float) print(msg.altitude_units) # 'M' # Access computed decimal degree coordinates print(msg.latitude) # -19.4840833333 (negative for South) print(msg.longitude) # 24.1751 (positive for East) # Format coordinates in degrees/minutes/seconds print('%02d°%07.4f′' % (msg.latitude, msg.latitude_minutes)) # Output: '-19°29.0450′' print('%02d°%02d′%07.4f″' % (msg.latitude, msg.latitude_minutes, msg.latitude_seconds)) # Output: "-19°29′02.7000″" ``` -------------------------------- ### Define Custom Proprietary Sentence Parser Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Extend the `ProprietarySentence` class to define a new sentence type. The `__new__` method determines the sentence class based on manufacturer and data, while `__init__` handles initialization. ```python class IXS(ProprietarySentence): sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[0] + data[1] cls = _cls.sentence_types.get(name, _cls) return super(IXS, cls).__new__(cls) def __init__(self, manufacturer, data): self.sentence_type = manufacturer + data[0] +data[1] super(IXS, self).__init__(manufacturer, data[2:]) class IXSESTATUS(IXS): fields = ( ("INS status 1", "status1", lambda data1: int(data1, 16)), ("INS status 2", "status2", lambda data1: int(data1, 16)) ) ``` -------------------------------- ### Parse Generic Proprietary Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a generic proprietary sentence to extract manufacturer and raw data. ```python import pynmea2 # Generic proprietary sentence handling msg = pynmea2.parse("$PMTK001,314,3*36") print(f"Proprietary: manufacturer={msg.manufacturer}, data={msg.data}") ``` -------------------------------- ### Parse VTG Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a VTG sentence to extract track made good and ground speed in knots and km/h. ```python import pynmea2 vtg = pynmea2.parse("$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48") print(f"VTG: true_track={vtg.true_track}°, speed={vtg.spd_over_grnd_kts}kts, {vtg.spd_over_grnd_kmph}km/h") ``` -------------------------------- ### Parse DBT Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a DBT sentence to extract depth measurements in meters, feet, and fathoms. ```python import pynmea2 dbt = pynmea2.parse("$SDDBT,12.3,f,3.7,M,2.0,F*2C") print(f"DBT: depth={dbt.depth_meters}m ({dbt.depth_feet}ft, {dbt.depth_fathoms} fathoms)") ``` -------------------------------- ### Parse Garmin Proprietary Sentence Source: https://context7.com/knio/pynmea2/llms.txt Attempts to parse a Garmin proprietary sentence (PGRM). Includes error handling for unimplemented sentence types. ```python import pynmea2 # Garmin proprietary sentence (PGRM) try: grm = pynmea2.parse("$PGRME,15.0,M,22.5,M,28.0,M*1C") print(f"GRM: {grm}") except pynmea2.ParseError: print("Sentence type not implemented") ``` -------------------------------- ### Convert NMEA coordinates to decimal degrees Source: https://github.com/knio/pynmea2/blob/master/README.md Utilize helper properties like `latitude` and `longitude` to convert NMEA DDDMM.MMMM format to Python floats representing decimal degrees. Also shows formatting for minutes and seconds. ```python msg.latitude msg.longitude '%02d°%07.4f′' % (msg.latitude, msg.latitude_minutes) '%02d°%02d′%07.4f″' % (msg.latitude, msg.latitude_minutes, msg.latitude_seconds) ``` -------------------------------- ### Parse u-blox Proprietary Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a u-blox proprietary sentence (PUBX) to extract manufacturer and other data. ```python import pynmea2 # u-blox proprietary sentence (PUBX) ubx = pynmea2.parse("$PUBX,00,081350.00,4717.113210,N,00833.915187,E,546.589,G3,2.1,2.0,0.007,77.52,0.007,,0.92,1.19,0.77,9,0,0*5F") print(f"UBX: manufacturer={ubx.manufacturer}") ``` -------------------------------- ### Parse RMC Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses an RMC sentence to extract recommended minimum GPS data like latitude, longitude, speed, course, and validity. ```python import pynmea2 rmc = pynmea2.parse("$GPRMC,123519,A,4807.038,N,01131.000,W,022.4,084.4,230394,003.1,W*6A") print(f"RMC: lat={rmc.latitude}, lon={rmc.longitude}") print(f" speed={rmc.spd_over_grnd}kts, course={rmc.true_course}°, valid={rmc.is_valid}") ``` -------------------------------- ### Parse GSV Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a GSV sentence to retrieve information about satellites in view, including PRN, elevation, azimuth, and SNR. ```python import pynmea2 gsv = pynmea2.parse("$GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75") print(f"GSV: total_msgs={gsv.num_messages}, msg_num={gsv.msg_num}, sats_in_view={gsv.num_sv_in_view}") print(f" sat1: PRN={gsv.sv_prn_num_1}, elev={gsv.elevation_deg_1}°, az={gsv.azimuth_1}°, snr={gsv.snr_1}dB") ``` -------------------------------- ### Parse HDT Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses an HDT sentence to extract the true heading information. ```python import pynmea2 hdt = pynmea2.parse("$HCHDT,123.456,T*32") print(f"HDT: heading={hdt.heading}° true") ``` -------------------------------- ### Parse ZDA Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a ZDA sentence to extract time, date, and timezone offset information. ```python import pynmea2 zda = pynmea2.parse("$GPZDA,160012.71,11,03,2004,-1,00*7D") print(f"ZDA: time={zda.timestamp}, date={zda.datestamp}, datetime={zda.datetime}") print(f" tz_offset={zda.local_zone}h {zda.local_zone_minutes}m") ``` -------------------------------- ### Read NMEA from pySerial Device Source: https://github.com/knio/pynmea2/blob/master/README.md Use this snippet to read NMEA data from a serial port. Ensure the correct serial port and baud rate are specified. Handles serial and parsing errors. ```python import io import pynmea2 import serial ser = serial.Serial('/dev/ttyS1', 9600, timeout=5.0) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) while 1: try: line = sio.readline() msg = pynmea2.parse(line) print(repr(msg)) except serial.SerialException as e: print('Device error: {}'.format(e)) break except pynmea2.ParseError as e: print('Parse error: {}'.format(e)) continue ``` -------------------------------- ### Robust NMEA Error Handling Source: https://context7.com/knio/pynmea2/llms.txt Provides comprehensive error handling for NMEA data processing, including checksum validation, parse errors, and unknown sentence types. Use this for reliable data ingestion. ```python import pynmea2 def process_nmea_safely(data): """Process NMEA data with comprehensive error handling""" results = { 'parsed': [], 'checksum_errors': [], 'parse_errors': [], 'unknown_types': [] } for line in data.split('\n'): line = line.strip() if not line: continue try: msg = pynmea2.parse(line, checksums='check') results['parsed'].append(msg) except pynmea2.ChecksumError as e: results['checksum_errors'].append({ 'line': line, 'error': str(e) }) except pynmea2.SentenceTypeError as e: results['unknown_types'].append({ 'line': line, 'error': str(e) }) except pynmea2.ParseError as e: results['parse_errors'].append({ 'line': line, 'error': str(e) }) return results # Example usage mea_data = """$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,47.0,M,,*47 $GPGGA,invalid,data*FF $GPXXX,unknown,type*00 $GPRMC,123519,A,4807.038,N,01131.000,W,022.4,084.4,230394,003.1,W*6A""" results = process_nmea_safely(nmea_data) print(f"Successfully parsed: {len(results['parsed'])} sentences") print(f"Checksum errors: {len(results['checksum_errors'])}") print(f"Unknown types: {len(results['unknown_types'])}") print(f"Parse errors: {len(results['parse_errors'])}") # Access sentence properties safely for msg in results['parsed']: if hasattr(msg, 'is_valid') and msg.is_valid: print(f"Valid {type(msg).__name__}: {getattr(msg, 'latitude', 'N/A')}, {getattr(msg, 'longitude', 'N/A')}") ``` -------------------------------- ### Parse GGA Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a GGA sentence to extract GPS fix data including latitude, longitude, altitude, quality, and number of satellites. ```python import pynmea2 gga = pynmea2.parse("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,47.0,M,,*47") print(f"GGA: lat={gga.latitude}, lon={gga.longitude}, alt={gga.altitude}m") print(f" quality={gga.gps_qual}, sats={gga.num_sats}, hdop={gga.horizontal_dil}") ``` -------------------------------- ### Modify NMEA Sentence Regex for Comments Source: https://github.com/knio/pynmea2/wiki/How-to-extend-pynmea2 Temporarily override `pynmea2.NMEASentence.sentence_re` to allow optional comments at the end of NMEA sentences. Backup and restore the original regex to maintain compatibility. ```python import pynmea2 import re pynmea2.NMEASentence.sentence_re_backup = pynmea2.NMEASentence.sentence_re pynmea2.NMEASentence.sentence_re = re.compile(r''' # start of string, optional whitespace, optional '$' ^\s*\$? # message (from '$' or start to checksum or end, non-inclusve) (?P # sentence type identifier (?P # proprietary sentence (P\w{3})| # query sentence, ie: 'CCGPQ,GGA' # NOTE: this should have no data (\w{2}\w{2}Q,\w{3})| # taker sentence, ie: 'GPGGA' (\w{2}\w{3},) ) # rest of message (?P[^*]*) ) # checksum: *HH (?:[*](?P[A-F0-9]{2}))? # optional trailing whitespace and comments \s*.*[\r\n]*$ ''', re.X | re.IGNORECASE) ``` ```python pynmea2.parse('$GPGGA,134658.00,5106.9792,N,11402.3003,W,2,09,1.0,1048.47,M,-16.27,M,08,AAAA*60 #some white space and commnets') ``` ```python pynmea2.NMEASentence.sentence_re = pynmea2.NMEASentence.sentence_re_backup ``` -------------------------------- ### Parse NMEA RMC Sentence and Access Date/Time Source: https://context7.com/knio/pynmea2/llms.txt Parse an NMEA RMC sentence to extract timestamp, date, and datetime objects. Access speed over ground and true course, and check the validity status. ```python # Parse RMC (Recommended Minimum) sentence with date/time rmc = pynmea2.parse("$GPRMC,225446,A,4916.45,N,12311.12,W,000.5,054.7,191194,020.3,E*68") print(rmc.timestamp) # datetime.time(22, 54, 46) print(rmc.datestamp) # datetime.date(1994, 11, 19) print(rmc.datetime) # datetime.datetime(1994, 11, 19, 22, 54, 46) print(rmc.spd_over_grnd) # 0.5 (knots) print(rmc.true_course) # 54.7 (degrees) print(rmc.is_valid) # True (status == 'A') ``` -------------------------------- ### Parse an NMEA sentence Source: https://github.com/knio/pynmea2/blob/master/README.md Parse an individual NMEA 0183 sentence string using the `parse` function. The leading '$' is optional and trailing whitespace is ignored. ```python import pynmea2 msg = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D") print(repr(msg)) ``` -------------------------------- ### Parse GLL Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a GLL sentence to extract geographic position (latitude and longitude), time, and validity status. ```python import pynmea2 gll = pynmea2.parse("$GPGLL,4916.45,N,12311.12,W,225444,A,*1D") print(f"GLL: lat={gll.latitude}, lon={gll.longitude}, time={gll.timestamp}, valid={gll.is_valid}") ``` -------------------------------- ### Parse GSA Sentence Source: https://context7.com/knio/pynmea2/llms.txt Parses a GSA sentence to extract GPS DOP (Dilution of Precision) values and fix type. ```python import pynmea2 gsa = pynmea2.parse("$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39") print(f"GSA: mode={gsa.mode}, fix_type={gsa.mode_fix_type}, pdop={gsa.pdop}, hdop={gsa.hdop}, vdop={gsa.vdop}") print(f" valid_fix={gsa.is_valid}") ``` -------------------------------- ### Access GGA message properties Source: https://github.com/knio/pynmea2/blob/master/README.md Access specific properties of a parsed GGA NMEA sentence object. These properties correspond to the fields within the GGA message. ```python msg.timestamp msg.lat msg.lat_dir msg.lon msg.lon_dir msg.gps_qual msg.num_sats msg.horizontal_dil msg.altitude msg.altitude_units msg.geo_sep msg.geo_sep_units msg.age_gps_data msg.ref_station_id ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.