| 1 |
"""Manage a stream of NMEA TAG block messages. |
| 2 |
|
| 3 |
The TAG (Transport, Annotate, and Group) Block messages are defined in NMEA 4.0 |
| 4 |
section 7. |
| 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 |
TODO(schwehr): Add a queue method to drop old groups caches. |
| 10 |
TODO(schwehr): Catch a wider variety of incomplete groups. |
| 11 |
TODO(schwehr): Compute running stats in the queue. |
| 12 |
""" |
| 13 |
|
| 14 |
import hashlib |
| 15 |
import logging |
| 16 |
import re |
| 17 |
|
| 18 |
import six |
| 19 |
import six.moves.queue as Queue |
| 20 |
|
| 21 |
import ais |
| 22 |
from ais import nmea |
| 23 |
from ais import nmea_messages |
| 24 |
from ais import util |
| 25 |
from ais import vdm |
| 26 |
|
| 27 |
logger = logging.getLogger('libais') |
| 28 |
|
| 29 |
# Added a decimal value to time beyond the normal TAG BLOCK spec. |
| 30 |
TAG_BLOCK_RE = re.compile(r""" |
| 31 |
(\\ |
| 32 |
(?P<metadata>( |
| 33 |
( |
| 34 |
c:(?P<time>\d{10,15}(\.\d*)?) | # Receiver Unix time in seconds or millisec |
| 35 |
d:(?P<dest>[^*,\\]{1,15}) | # Destination |
| 36 |
g:(?P<group>(?P<sentence_num>\d)-(?P<sentence_tot>\d)-(?P<group_id>\d+)) | |
| 37 |
n:(?P<line_num>\d+) | # Line count |
| 38 |
q:(?P<quality>\w) | # Orbcomm specific character code |
| 39 |
r:(?P<rel_time>\d+) | # Relative time |
| 40 |
s:(?P<rcvr>[^$*,!\\]{1,15}) | # Source / station |
| 41 |
t:(?P<text>[^$*,!\\]+) | # Text string |
| 42 |
T:(?P<text_date>[^$*,!\\]+) # Orbcomm human readable date |
| 43 |
)[,]? |
| 44 |
)+([*](?P<tag_checksum>[0-9A-Fa-f]{2}))?) |
| 45 |
\\)(?P<payload>.*) |
| 46 |
""", re.VERBOSE) |
| 47 |
|
| 48 |
NUMERIC_FIELDS = ( |
| 49 |
'dest', |
| 50 |
'group', |
| 51 |
'group_id', |
| 52 |
'line_num', |
| 53 |
'rel_time', |
| 54 |
'sentence_num', |
| 55 |
'sentence_tot', |
| 56 |
'time' |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
def Parse(data): |
| 61 |
"""Unpack a TAG Block line or return None. |
| 62 |
|
| 63 |
Makes sure that the line matches the regex and the checksum matches. |
| 64 |
|
| 65 |
Args: |
| 66 |
data: Line of text or a dict from at TAG_BLOCK_RE. |
| 67 |
|
| 68 |
Returns: |
| 69 |
A NMEA TAG Block dict or None if the line would not parse or has |
| 70 |
an invalid checksum. |
| 71 |
""" |
| 72 |
if isinstance(data, str): |
| 73 |
try: |
| 74 |
result = TAG_BLOCK_RE.search(data).groupdict() |
| 75 |
except AttributeError: |
| 76 |
return |
| 77 |
elif isinstance(data, dict): |
| 78 |
result = data |
| 79 |
else: |
| 80 |
return |
| 81 |
|
| 82 |
result.update({k: util.MaybeToNumber(v) |
| 83 |
for k, v in six.iteritems(result) if k in NUMERIC_FIELDS}) |
| 84 |
|
| 85 |
actual = nmea.Checksum(result['metadata']) |
| 86 |
expected = result['tag_checksum'].upper() |
| 87 |
if actual != expected: |
| 88 |
return |
| 89 |
|
| 90 |
return result |
| 91 |
|
| 92 |
|
| 93 |
class TagQueue(Queue.Queue): |
| 94 |
"""Aggregate TAG Block group messages into logical units. |
| 95 |
|
| 96 |
This queue tracks message lines with the "g" group TAG and finds matching |
| 97 |
lines. It will pass single line messages straight through. |
| 98 |
""" |
| 99 |
|
| 100 |
def __init__(self): |
| 101 |
self.groups = {} |
| 102 |
self.line_num = 0 |
| 103 |
Queue.Queue.__init__(self) |
| 104 |
|
| 105 |
def put(self, line, line_num=None): |
| 106 |
if line_num is not None: |
| 107 |
self.line_num = line_num |
| 108 |
else: |
| 109 |
self.line_num += 1 |
| 110 |
|
| 111 |
line = line.rstrip() |
| 112 |
match = Parse(line) |
| 113 |
|
| 114 |
if not match: |
| 115 |
Queue.Queue.put(self, { |
| 116 |
'line_nums': [self.line_num], |
| 117 |
'lines': [line], |
| 118 |
}) |
| 119 |
return |
| 120 |
|
| 121 |
time = util.MaybeToNumber(match['time']) |
| 122 |
|
| 123 |
if not match['group']: |
| 124 |
msg = { |
| 125 |
'line_nums': [self.line_num], |
| 126 |
'lines': [line], |
| 127 |
'matches': [match], |
| 128 |
'times': [time], |
| 129 |
} |
| 130 |
decoded = DecodeTagSingle(msg) |
| 131 |
if decoded: |
| 132 |
msg['decoded'] = decoded |
| 133 |
else: |
| 134 |
logger.info('Unable to decode. Passing without decoded block.') |
| 135 |
decoded = nmea_messages.DecodeLine(match['payload']) |
| 136 |
if decoded: |
| 137 |
msg['decoded'] = decoded |
| 138 |
else: |
| 139 |
logger.info('No NMEA match for line: %d, %s', line_num, line) |
| 140 |
Queue.Queue.put(self, msg) |
| 141 |
return |
| 142 |
|
| 143 |
sentence_num = int(match['sentence_num']) |
| 144 |
sentence_total = int(match['sentence_tot']) |
| 145 |
group_id = int(match['group_id']) |
| 146 |
|
| 147 |
if sentence_num == 1: |
| 148 |
self.groups[group_id] = { |
| 149 |
'line_nums': [self.line_num], |
| 150 |
'lines': [line], |
| 151 |
'matches': [match], |
| 152 |
'times': [time], |
| 153 |
} |
| 154 |
return |
| 155 |
|
| 156 |
if group_id not in self.groups: |
| 157 |
logger.error('group_id not in groups: %d', group_id) |
| 158 |
return |
| 159 |
|
| 160 |
entry = self.groups[group_id] |
| 161 |
entry['line_nums'].append(self.line_num) |
| 162 |
entry['lines'].append(line) |
| 163 |
entry['matches'].append(match) |
| 164 |
entry['times'].append(time) |
| 165 |
|
| 166 |
if sentence_num != sentence_total: |
| 167 |
# Found the middle part of a message. |
| 168 |
return |
| 169 |
|
| 170 |
# Found the final message in a group. |
| 171 |
decoded = DecodeTagMultiple(entry) |
| 172 |
if decoded: |
| 173 |
entry['decoded'] = decoded |
| 174 |
else: |
| 175 |
logger.info('Unable to process: %s', entry) |
| 176 |
Queue.Queue.put(self, entry) |
| 177 |
self.groups.pop(group_id) |
| 178 |
|
| 179 |
|
| 180 |
def DecodeTagSingle(tag_block_message): |
| 181 |
"""Decode the payload of one (but NOT more) NMEA TAG block. |
| 182 |
|
| 183 |
Args: |
| 184 |
tag_block_message: dict, A dictionary with a matches entry. |
| 185 |
|
| 186 |
Returns: |
| 187 |
A message dictionary compatible with vdm.BareQueue. |
| 188 |
""" |
| 189 |
line = tag_block_message['matches'][0]['payload'] |
| 190 |
match = vdm.Parse(line) |
| 191 |
if not match: |
| 192 |
logger.info('Single line NMEA TAG block decode failed for: %s', |
| 193 |
tag_block_message) |
| 194 |
return |
| 195 |
|
| 196 |
sentence_total = int(match['sen_tot']) |
| 197 |
if sentence_total != 1: |
| 198 |
logger.error('Multi-line message? %s', tag_block_message) |
| 199 |
return |
| 200 |
|
| 201 |
body = match['body'] |
| 202 |
fill_bits = int(match['fill_bits']) |
| 203 |
try: |
| 204 |
decoded = ais.decode(body, fill_bits) |
| 205 |
except ais.DecodeError as error: |
| 206 |
logger.error('Unable to decode: %s', error) |
| 207 |
return |
| 208 |
|
| 209 |
decoded['md5'] = hashlib.md5(body.encode('utf-8')).hexdigest() |
| 210 |
return decoded |
| 211 |
|
| 212 |
|
| 213 |
def DecodeTagMultiple(tag_block_message): |
| 214 |
"""Decode a TAG block message that spans multiple lines.""" |
| 215 |
payloads = [msg['payload'] for msg in tag_block_message['matches']] |
| 216 |
|
| 217 |
q = vdm.BareQueue() |
| 218 |
for line in vdm.VdmLines(payloads): |
| 219 |
q.put(line) |
| 220 |
if q.qsize() != 1: |
| 221 |
logger.info('Error: Should get just one message decoded from this: %s', |
| 222 |
tag_block_message) |
| 223 |
return |
| 224 |
msg = q.get() |
| 225 |
return msg['decoded'] |