| 1 |
"""Utilities for working with NMEA strings.""" |
| 2 |
|
| 3 |
import re |
| 4 |
import sys |
| 5 |
import time |
| 6 |
|
| 7 |
nmeaChecksumRegExStr = r"""\,[0-9]\*[0-9A-F][0-9A-F]""" |
| 8 |
nmeaChecksumRE = re.compile(nmeaChecksumRegExStr) |
| 9 |
|
| 10 |
|
| 11 |
def checksumStr(data): |
| 12 |
"""Take a NMEA 0183 string and compute the checksum. |
| 13 |
@param data: NMEA message. Leading ?/! and training checksum are optional |
| 14 |
@type data: str |
| 15 |
@return: hexidecimal value |
| 16 |
@rtype: str |
| 17 |
|
| 18 |
Checksum is calculated by xor'ing everything between ? or ! and the * |
| 19 |
|
| 20 |
>>> checksumStr("!AIVDM,1,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0*09") |
| 21 |
'09' |
| 22 |
>>> checksumStr("AIVDM,1,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0") |
| 23 |
'09' |
| 24 |
""" |
| 25 |
|
| 26 |
|
| 27 |
if data[0]=='!' or data[0]=='?': data = data[1:] |
| 28 |
if data[-1]=='*': data = data[:-1] |
| 29 |
if data[-3]=='*': data = data[:-3] |
| 30 |
|
| 31 |
checksum = 0 |
| 32 |
for c in data: |
| 33 |
checksum = checksum ^ ord(c) |
| 34 |
sum_hex = "%x" % checksum |
| 35 |
if len(sum_hex) == 1: |
| 36 |
sum_hex = '0' + sum_hex |
| 37 |
return sum_hex.upper() |
| 38 |
|
| 39 |
|
| 40 |
def isChecksumValid(nmeaStr, allowTailData=True): |
| 41 |
"""Return True if the string checks out with the checksum. |
| 42 |
|
| 43 |
@param allowTailData: Permit handing of Coast Guard format with data after the checksum |
| 44 |
@param data: NMEA message. Leading ?/! are optional |
| 45 |
@type data: str |
| 46 |
@return: True if the checksum matches |
| 47 |
@rtype: bool |
| 48 |
|
| 49 |
>>> isChecksumValid("!AIVDM,1,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0*09") |
| 50 |
True |
| 51 |
|
| 52 |
Corrupted: |
| 53 |
|
| 54 |
>>> isChecksumValid("!AIVDM,11,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0*09") |
| 55 |
False |
| 56 |
""" |
| 57 |
|
| 58 |
if allowTailData: |
| 59 |
match = nmeaChecksumRE.search(nmeaStr) |
| 60 |
if not match: |
| 61 |
return False |
| 62 |
nmeaStr = nmeaStr[:match.end()] |
| 63 |
|
| 64 |
if nmeaStr[-3]!='*': |
| 65 |
return False |
| 66 |
checksum=nmeaStr[-2:] |
| 67 |
if checksum.upper() == checksumStr(nmeaStr).upper(): |
| 68 |
return True |
| 69 |
return False |