nmea_parser.py
Go to the documentation of this file.
1 import logging
2 
3 NMEA_DEFAULT_MAX_LENGTH = 82
4 NMEA_DEFAULT_MIN_LENGTH = 3
5 _NMEA_CHECKSUM_SEPERATOR = "*"
6 
7 class NMEAParser:
8 
9  def __init__(self, logerr=logging.error, logwarn=logging.warning, loginfo=logging.info, logdebug=logging.debug):
10  # Bit of a strange pattern here, but save the log functions so we can be agnostic of ROS
11  self._logerr = logerr
12  self._logwarn = logwarn
13  self._loginfo = loginfo
14  self._logdebug = logdebug
15 
16  # Save some other config
17  self.nmea_max_length = NMEA_DEFAULT_MAX_LENGTH
18  self.nmea_min_length = NMEA_DEFAULT_MIN_LENGTH
19 
20  def is_valid_sentence(self, sentence):
21  # Simple sanity checks
22  if len(sentence) > self.nmea_max_length:
23  self._logwarn('Received invalid NMEA sentence. Max length is {}, but sentence was {} bytes'.format(self.nmea_max_length, len(sentence)))
24  self._logwarn('Sentence: {}'.format(sentence))
25  return False
26  if len(sentence) < self.nmea_min_length:
27  self._logwarn('Received invalid NMEA sentence. We need at least {} bytes to parse but got {} bytes'.format(self.nmea_min_length, len(sentence)))
28  self._logwarn('Sentence: {}'.format(sentence))
29  return False
30  if sentence[0] != '$' and sentence[0] != '!':
31  self._logwarn('Received invalid NMEA sentence. Sentence should begin with "$" or "!", but instead begins with {}'.format(sentence[0]))
32  self._logwarn('Sentence: {}'.format(sentence))
33  return False
34  if sentence[-2:] != '\r\n':
35  self._logwarn('Received invalid NMEA sentence. Sentence should end with \\r\\n, but instead ends with {}'.format(sentence[-2:]))
36  self._logwarn('Sentence: {}'.format(sentence))
37  return False
38  if _NMEA_CHECKSUM_SEPERATOR not in sentence:
39  self._logwarn('Received invalid NMEA sentence. Sentence should have a "{}" character to seperate the checksum, but we could not find it.'.format(_NMEA_CHECKSUM_SEPERATOR))
40  self._logwarn('Sentence: {}'.format(sentence))
41  return False
42 
43  # Checksum check
44  data, expected_checksum_str = sentence.rsplit(_NMEA_CHECKSUM_SEPERATOR, 1)
45  expected_checksum = int(expected_checksum_str, 16)
46  calculated_checksum = 0
47  for char in data[1:]:
48  calculated_checksum ^= ord(char)
49  if expected_checksum != calculated_checksum:
50  self._logwarn('Received invalid NMEA sentence. Checksum mismatch');
51  self._logwarn('Expected Checksum: 0x{:X}'.format(expected_checksum))
52  self._logwarn('Calculated Checksum: 0x{:X}'.format(calculated_checksum))
53  return False
54 
55  # Passed all checks
56  return True
def is_valid_sentence(self, sentence)
Definition: nmea_parser.py:20
def __init__(self, logerr=logging.error, logwarn=logging.warning, loginfo=logging.info, logdebug=logging.debug)
Definition: nmea_parser.py:9


ntrip_client
Author(s): Parker Hannifin Corp
autogenerated on Thu Aug 18 2022 02:39:24