2 """ Functions for creating and validating NMEA style checksums. """
4 # Copyright (C) 2008 Laurens Van Houtven <lvh at laurensvh.be>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 def is_valid_nmea_sentence(sentence
):
19 """Validates the checksum of an NMEA sentence.
21 Returns True if the sentence has either a valid checksum or no checkum.
22 Returns False if the checksum was bad.
24 if sentence
[-3] == '*': # sentence has a checksum
25 reference
, source
= sentence
[-2:], sentence
[1:-3]
26 return is_valid_hex_csum(source
, reference
)
27 else: # sentence does not have a checksum
30 def is_valid_hex_csum(string
, reference
):
31 """Calculates a hex checksum and compares it to the reference."""
32 return generate_hex_checksum(string
) == reference
34 def generate_checksum(string
):
35 """Generates an NMEA style checksum (in decimal) of a given string."""
38 checksum
= checksum ^
ord(char
)
41 def generate_hex_checksum(string
):
42 """Generates the hexadecimal form of the checksum of a given string."""
43 hex_csum
= "%02x" % generate_checksum(string
)
44 return hex_csum
.upper()
46 def generate_byte_checksum(string
):
47 """Generates the byte form of the checksum of a given string."""
48 return chr(generate_checksum(string
))