| 1 |
|
| 2 |
"""Handle AIS VD[MO] messages without extra metadata. |
| 3 |
|
| 4 |
An example single line message: |
| 5 |
|
| 6 |
!AIVDM,1,1,,A,14VIk0002sMM04vE>V9jGimn08RP,0*0D |
| 7 |
|
| 8 |
An example two line message: |
| 9 |
|
| 10 |
!AIVDM,2,1,2,B,5KNp?6@00000=Phb220u1@Tlv0TV22222222220N0h:22400000000000000,0*2A |
| 11 |
!AIVDM,2,2,2,B,00000000000,2*25' |
| 12 |
|
| 13 |
The Parse class calculates the checksum and compares that to expected |
| 14 |
checksum at the end of the message. It then uses the VDM_RE regular |
| 15 |
expression to create a dictionary for a single line. These |
| 16 |
dictionaries are used by the BareQueue class to construct a queue of |
| 17 |
complete AIS messages. It also passes non AIS VDM messages through. |
| 18 |
Invalid AIS messages are dropped. |
| 19 |
|
| 20 |
The non AIS VDM messages have a simpler data structure like this: |
| 21 |
|
| 22 |
{ |
| 23 |
'line_nums': [42], |
| 24 |
'lines': ['A line of text'] |
| 25 |
} |
| 26 |
|
| 27 |
A single line AIS VDM message adds a 'decoded' dictionary with the |
| 28 |
unpacked message and a list of matches for each of the lines that came |
| 29 |
in. Additionally, the queue adds the md5 hash of the body of the |
| 30 |
message to assist with the process of looking for duplicate messages. |
| 31 |
|
| 32 |
{ |
| 33 |
'line_nums': [1], |
| 34 |
'lines': ['!SAVDM,1,1,,B,K8VSqb9LdU28WP8P,0*7B'], |
| 35 |
'decoded': { |
| 36 |
'md5': '6e1a4872825054e91ee7cfcfb9cc87e0', |
| 37 |
'id': 27, |
| 38 |
'mmsi': 577305000, |
| 39 |
# SNIP |
| 40 |
}, |
| 41 |
'matches': [{ |
| 42 |
'body': 'K8VSqb9LdU28WP8P', |
| 43 |
'fill_bits': '0', |
| 44 |
'sen_num': '1', |
| 45 |
'sen_tot': '1', |
| 46 |
'vdm_type': 'VDM', |
| 47 |
'talker': 'SA', |
| 48 |
'chan': 'B', |
| 49 |
'seq_id': None, |
| 50 |
'checksum': '7B'}] |
| 51 |
} |
| 52 |
|
| 53 |
TODO(schwehr): Make sure that multi-line messages are coming in on the |
| 54 |
same channel. |
| 55 |
|
| 56 |
See Also: |
| 57 |
http://catb.org/gpsd/AIVDM.html |
| 58 |
http://www.itu.int/rec/R-REC-M.1371/en |
| 59 |
""" |
| 60 |
|
| 61 |
import hashlib |
| 62 |
import logging |
| 63 |
import re |
| 64 |
|
| 65 |
import six |
| 66 |
import six.moves.queue as Queue |
| 67 |
|
| 68 |
import ais |
| 69 |
from ais import nmea |
| 70 |
from ais import nmea_messages |
| 71 |
from ais import util |
| 72 |
|
| 73 |
logger = logging.getLogger('libais') |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
VDM_RE_STR = r"""(?P<vdm> |
| 79 |
!(?P<talker>[A-Z][A-Z])(?P<vdm_type>VD[MO]) |
| 80 |
,(?P<sen_tot>\d) # Total number of sentences. |
| 81 |
,(?P<sen_num>\d) # Current sentence number. Starts from 1. |
| 82 |
,(?P<seq_id>[0-9])? # Receiver sequence number. |
| 83 |
,(?P<chan>[AB])? # VHF channel. |
| 84 |
,(?P<body>[;:=@a-zA-Z0-9<>\?\'\`]*) |
| 85 |
,(?P<fill_bits>\d)\*(?P<checksum>[0-9A-F][0-9A-F]) |
| 86 |
) # end vdm |
| 87 |
""" |
| 88 |
|
| 89 |
VDM_RE = re.compile(VDM_RE_STR, re.VERBOSE) |
| 90 |
NUMERIC_FIELDS = ('fill_bits', 'sen_num', 'sen_tot', 'seq_id') |
| 91 |
|
| 92 |
|
| 93 |
def VdmLines(lines): |
| 94 |
"""Yield only the lines that contain AIS messages. |
| 95 |
|
| 96 |
Args: |
| 97 |
lines: An iterable series of strings. |
| 98 |
|
| 99 |
Yields: |
| 100 |
Lines that look like they probably contain valid VDM/VDO messages. |
| 101 |
""" |
| 102 |
for line in lines: |
| 103 |
line = line.rstrip() |
| 104 |
if nmea.ID_BARE_VDM_RE.match(line): |
| 105 |
yield line |
| 106 |
|
| 107 |
|
| 108 |
def Parse(data): |
| 109 |
"""Unpack a NMEA VDM AIS message line(s).""" |
| 110 |
|
| 111 |
if not isinstance(data, six.string_types): |
| 112 |
raise NotImplementedError |
| 113 |
|
| 114 |
try: |
| 115 |
result = VDM_RE.search(data).groupdict() |
| 116 |
except AttributeError: |
| 117 |
return |
| 118 |
|
| 119 |
result.update({k: util.MaybeToNumber(v) |
| 120 |
for k, v in six.iteritems(result) if k in NUMERIC_FIELDS}) |
| 121 |
|
| 122 |
actual = nmea.Checksum(result['vdm']) |
| 123 |
expected = result['checksum'] |
| 124 |
if actual != expected: |
| 125 |
return |
| 126 |
|
| 127 |
return result |
| 128 |
|
| 129 |
|
| 130 |
class BareQueue(Queue.Queue): |
| 131 |
"""Build complete AIS messages and create a queue of decoded content. |
| 132 |
|
| 133 |
Manages parsing a stream of NMEA AIS VDM messages. Single line |
| 134 |
messages are decoded and added to the queue. Parts of multi-line VDM |
| 135 |
messages are stored until a complete message is available. The |
| 136 |
bodies of each part are joined with the fill_bit count from the final |
| 137 |
sentence are decoded and added to the queue. |
| 138 |
""" |
| 139 |
|
| 140 |
def __init__(self): |
| 141 |
self.groups = {} |
| 142 |
self.line_num = 0 |
| 143 |
Queue.Queue.__init__(self) |
| 144 |
|
| 145 |
def put(self, line, line_num=None): |
| 146 |
"""Add a line of NMEA or raw text to the queue.""" |
| 147 |
|
| 148 |
if line_num is not None: |
| 149 |
self.line_num = line_num |
| 150 |
else: |
| 151 |
self.line_num += 1 |
| 152 |
line_num = self.line_num |
| 153 |
|
| 154 |
line = line.rstrip() |
| 155 |
match = Parse(line) |
| 156 |
|
| 157 |
if not match: |
| 158 |
logger.info('No VDM match for line: %d, %s', line_num, line) |
| 159 |
msg = { |
| 160 |
'line_nums': [line_num], |
| 161 |
'lines': [line]} |
| 162 |
decoded = nmea_messages.DecodeLine(line) |
| 163 |
if decoded: |
| 164 |
msg['decoded'] = decoded |
| 165 |
else: |
| 166 |
logger.info('No NMEA match for line: %d, %s', line_num, line) |
| 167 |
Queue.Queue.put(self, msg) |
| 168 |
return |
| 169 |
|
| 170 |
sentence_total = int(match['sen_tot']) |
| 171 |
if sentence_total == 1: |
| 172 |
body = match['body'] |
| 173 |
fill_bits = int(match['fill_bits']) |
| 174 |
try: |
| 175 |
decoded = ais.decode(body, fill_bits) |
| 176 |
except ais.DecodeError as error: |
| 177 |
logger.error( |
| 178 |
'Unable to decode message: %s\n %d %s', error, line_num, line) |
| 179 |
return |
| 180 |
decoded['md5'] = hashlib.md5(body.encode('utf-8')).hexdigest() |
| 181 |
Queue.Queue.put(self, { |
| 182 |
'line_nums': [line_num], |
| 183 |
'lines': [line], |
| 184 |
'decoded': decoded, |
| 185 |
'matches': [match] |
| 186 |
}) |
| 187 |
return |
| 188 |
|
| 189 |
sentence_num = int(match['sen_num']) |
| 190 |
group_id = int(match['seq_id']) |
| 191 |
|
| 192 |
if sentence_num == 1: |
| 193 |
if group_id in self.groups: |
| 194 |
logger.error('Incomplete message overwritten by new start. ' |
| 195 |
'Dropped:\n %s', self.groups[group_id]) |
| 196 |
self.groups[group_id] = { |
| 197 |
'line_nums': [line_num], |
| 198 |
'lines': [line], |
| 199 |
'matches': [match] |
| 200 |
} |
| 201 |
return |
| 202 |
|
| 203 |
if group_id not in self.groups: |
| 204 |
logger.error('Do not have the prior lines in group_id %d. ' |
| 205 |
'Dropping: \n %s', group_id, line) |
| 206 |
return |
| 207 |
|
| 208 |
entry = self.groups[group_id] |
| 209 |
if len(entry['lines']) != sentence_num - 1: |
| 210 |
logger.error('Out of sequence message. Dropping: %d != %d \n %s', |
| 211 |
len(entry['lines']), sentence_num - 1, line) |
| 212 |
return |
| 213 |
|
| 214 |
entry['lines'].append(line) |
| 215 |
entry['matches'].append(match) |
| 216 |
entry['line_nums'].append(line_num) |
| 217 |
|
| 218 |
if sentence_num != sentence_total: |
| 219 |
|
| 220 |
return |
| 221 |
|
| 222 |
body = ''.join([match['body'] for match in entry['matches']]) |
| 223 |
fill_bits = int(entry['matches'][-1]['fill_bits']) |
| 224 |
try: |
| 225 |
decoded = ais.decode(body, fill_bits) |
| 226 |
except ais.DecodeError as error: |
| 227 |
logger.error( |
| 228 |
'Unable to decode message: %s\n%s', error, entry) |
| 229 |
return |
| 230 |
decoded['md5'] = hashlib.md5(body.encode('utf-8')).hexdigest() |
| 231 |
entry['decoded'] = decoded |
| 232 |
|
| 233 |
|
| 234 |
Queue.Queue.put(self, entry) |
| 235 |
self.groups.pop(group_id) |