| 1 |
"""Handling of NMEA encoded formatting. |
| 2 |
|
| 3 |
The National Marine Electronics Association (NMEA) added a TAG BLOCK |
| 4 |
metadata data specification to NMEA 0183 4.0. |
| 5 |
|
| 6 |
Some providers violate the NMEA standard by using lower case letters in NMEA |
| 7 |
checksums. This module forces checksums to always be upper case. |
| 8 |
|
| 9 |
See Also: |
| 10 |
http://catb.org/gpsd/NMEA.html |
| 11 |
http://catb.org/gpsd/AIVDM.html#_nmea_tag_blocks |
| 12 |
""" |
| 13 |
|
| 14 |
import re |
| 15 |
|
| 16 |
|
| 17 |
CHECKSUM_RE = re.compile(r'\*(?P<checksum>[0-9A-Fa-f]{2})$') |
| 18 |
SENTENCE_START_RE = re.compile(r'^[\\$!]') |
| 19 |
|
| 20 |
|
| 21 |
TEXT = 'TEXT' |
| 22 |
BARE = 'BARE' |
| 23 |
TAGB = 'TAGB' |
| 24 |
USCG = 'USCG' |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
ID_BARE_RE = re.compile(r'[!$][A-Z]{4}[^*!$]*\*[0-9A-Fa-f]{2}$') |
| 29 |
ID_USCG_RE = re.compile(r'[!$][A-Z]{4}[^*!$]*\*[0-9A-Fa-f]{2},[^*!$]+$') |
| 30 |
ID_TAGB_RE = re.compile(r'\\([a-zA-Z]:[^*,\\]*[,]?)+\*[0-9A-Fa-f]{2}(\\.*)?$') |
| 31 |
|
| 32 |
|
| 33 |
ID_BARE_VDM_RE = re.compile(r'[!$][A-Z]{2}VD[MO][^*!$]*\*[0-9A-Fa-f]{2}') |
| 34 |
|
| 35 |
|
| 36 |
def _Checksum(sentence): |
| 37 |
"""Compute the NMEA checksum for a payload.""" |
| 38 |
checksum = 0 |
| 39 |
for char in sentence: |
| 40 |
checksum ^= ord(char) |
| 41 |
checksum_str = '%02x' % checksum |
| 42 |
return checksum_str.upper() |
| 43 |
|
| 44 |
|
| 45 |
def Checksum(sentence): |
| 46 |
"""Compute the checksum for a NMEA sentence or TAG BLOCK prefix. |
| 47 |
|
| 48 |
Args: |
| 49 |
sentence: str, NMEA tag block sentence starting with a backslash, bang, or |
| 50 |
dollar sign. The string must end with a star and the 2 character |
| 51 |
checksum. |
| 52 |
|
| 53 |
Returns: |
| 54 |
The computed checksum. |
| 55 |
""" |
| 56 |
sentence = SENTENCE_START_RE.sub('', sentence) |
| 57 |
sentence = CHECKSUM_RE.sub('', sentence) |
| 58 |
return _Checksum(sentence) |
| 59 |
|
| 60 |
|
| 61 |
def LineType(line): |
| 62 |
"""Give the type of NMEA line this is. |
| 63 |
|
| 64 |
Args: |
| 65 |
line: str, Text to try to interpret. |
| 66 |
|
| 67 |
Returns: |
| 68 |
String that is one of 'TEXT', 'BARE', 'USCG', or 'TAGB'. |
| 69 |
""" |
| 70 |
if not line: |
| 71 |
return TEXT |
| 72 |
|
| 73 |
if line[0] in '!$': |
| 74 |
if ID_BARE_RE.match(line): |
| 75 |
return BARE |
| 76 |
elif ID_USCG_RE.match(line): |
| 77 |
return USCG |
| 78 |
return TEXT |
| 79 |
|
| 80 |
if line[0] == '\\' and ID_TAGB_RE.match(line): |
| 81 |
return TAGB |
| 82 |
|
| 83 |
return TEXT |