| 1 |
|
| 2 |
"""Manage the old USCG metadata format. |
| 3 |
|
| 4 |
The US Coast Guard's older format consists of comma separated values |
| 5 |
after the end of the traditional NMEA sentence. The format was never |
| 6 |
formalized in a standard. The TAG Block format is in NMEA 0183 standard |
| 7 |
and is now recognized as preferred. |
| 8 |
|
| 9 |
Each field (except the timestamp) starts with a letter code followed |
| 10 |
by the value. The timestamp is a UNIX UTC seconds from the epoch |
| 11 |
value and must come last. Station name and the timestamp are the only |
| 12 |
required fields. However, some stations mangle the name field or |
| 13 |
leave it out, so this module will substitute 'rUnknown' if none is |
| 14 |
found. It will also accept messages that are missing the timestamp. |
| 15 |
The timestamp is typically the datalogger's time, not the receiver. |
| 16 |
This can sometimes be large spans of time before or after the message |
| 17 |
was received. USCG loggers have been shown to be up to 24 hours off |
| 18 |
in time. Additionally some dataloggers only get periodic updates from the |
| 19 |
receivers. Often the time is not derived from the GPS receiver in the |
| 20 |
AIS transceiver or receiver. |
| 21 |
|
| 22 |
Many of the letter codes directly relate to Shine Micro receiver |
| 23 |
features. See Shine Micro AISRadar documentation for addition details. |
| 24 |
|
| 25 |
Example single line AIS NMEA VDM message with USCG metadata: |
| 26 |
|
| 27 |
!AIVDM,1,1,,A,35Mqd3POj3rmIpjGSpmeCJaH00Qh,0*34,d-095,S1651,t161344.00,T44.03018211,r3669963,1429287142 |
| 28 |
|
| 29 |
Example single line with the minimum metadata: |
| 30 |
|
| 31 |
!ANVDM,1,1,,B,15N6CB0000r86SRFAS:<E@SH08Il,0*43,r08ACERDC,1429287223 |
| 32 |
|
| 33 |
Example two line message: |
| 34 |
|
| 35 |
!AIVDM,2,1,5,A,ENk`sPI17ab7W@6;Q@1@@@@@@@@=MwK3<7v:@00003v,0*4F,d-084,S1652,t161344.00,T44.05687473,r003669945,1429287224 |
| 36 |
!AIVDM,2,2,5,A,P000,2*71,d-084,S1652,t161344.00,T44.05687473,r003669945,1429287224 |
| 37 |
|
| 38 |
""" |
| 39 |
|
| 40 |
import hashlib |
| 41 |
import logging |
| 42 |
import re |
| 43 |
|
| 44 |
import six |
| 45 |
import six.moves.queue as Queue |
| 46 |
|
| 47 |
import ais |
| 48 |
from ais import util |
| 49 |
from ais import vdm |
| 50 |
|
| 51 |
logger = logging.getLogger('libais') |
| 52 |
|
| 53 |
|
| 54 |
USCG_RE = re.compile(r""" |
| 55 |
(?P<payload>[^*]*\*[A-F0-9][A-F0-9]) |
| 56 |
(?P<uscg_metadata> |
| 57 |
( |
| 58 |
(,S(?P<slot>\d*)) |
| 59 |
| (,s(?P<rssi>\d*)) # Receiver signal strength indicator. |
| 60 |
| (,d(?P<signal_strength>[-0-9]*)) # dB. |
| 61 |
| (,t(?P<receiver_time>(?P<hour>\d\d)(?P<minute>\d\d) # UTC time. |
| 62 |
(?P<second>\d\d.\d*))) |
| 63 |
| (,T(?P<time_of_arrival>[^,]*)) # Seconds within the minute. |
| 64 |
| (,x(?P<counter>[0-9]*)) |
| 65 |
| (,(?P<station>(?P<station_type>[rRbBbD])[a-zA-Z0-9_-]*)) |
| 66 |
)* |
| 67 |
,(?P<time>\d+([.]\d*)?)? # Logger timestamp. Can be hours from receive time. |
| 68 |
) |
| 69 |
""", re.VERBOSE) |
| 70 |
|
| 71 |
NUMERIC_FIELDS = ( |
| 72 |
'counter', |
| 73 |
'hour', |
| 74 |
'minute', |
| 75 |
'receiver_time', |
| 76 |
'second', |
| 77 |
'signal_strength', |
| 78 |
'slot', |
| 79 |
'time', |
| 80 |
'time_of_arrival' |
| 81 |
) |
| 82 |
|
| 83 |
|
| 84 |
def Parse(data): |
| 85 |
"""Unpack a USCG old metadata format line or return None. |
| 86 |
|
| 87 |
Makes sure that the line matches the regex and the checksum matches. |
| 88 |
|
| 89 |
Args: |
| 90 |
data: Line of text. |
| 91 |
|
| 92 |
Returns: |
| 93 |
A vdm dict or None and a metadata dict or None. |
| 94 |
""" |
| 95 |
try: |
| 96 |
result = USCG_RE.search(data).groupdict() |
| 97 |
except AttributeError: |
| 98 |
return None |
| 99 |
|
| 100 |
result.update({k: util.MaybeToNumber(v) |
| 101 |
for k, v in six.iteritems(result) if k in NUMERIC_FIELDS}) |
| 102 |
|
| 103 |
return result |
| 104 |
|
| 105 |
|
| 106 |
class UscgQueue(Queue.Queue): |
| 107 |
"""Treats NMEA without USCG station in metadata as from rUnknown.""" |
| 108 |
|
| 109 |
def __init__(self): |
| 110 |
self.groups = {} |
| 111 |
self.line_num = 0 |
| 112 |
Queue.Queue.__init__(self) |
| 113 |
self.unknown_queue = vdm.BareQueue() |
| 114 |
|
| 115 |
def put(self, line, line_num=None): |
| 116 |
if line_num is not None: |
| 117 |
self.line_num = line_num |
| 118 |
else: |
| 119 |
self.line_num += 1 |
| 120 |
|
| 121 |
line = line.rstrip() |
| 122 |
metadata_match = Parse(line) |
| 123 |
match = vdm.Parse(line) |
| 124 |
|
| 125 |
if not match: |
| 126 |
logger.info('not match') |
| 127 |
msg = { |
| 128 |
'line_nums': [self.line_num], |
| 129 |
'lines': [line], |
| 130 |
} |
| 131 |
if metadata_match: |
| 132 |
msg['match'] = metadata_match |
| 133 |
Queue.Queue.put(self, msg) |
| 134 |
return |
| 135 |
|
| 136 |
if not metadata_match: |
| 137 |
logger.info('not metadata match') |
| 138 |
self.unknown_queue.put(line) |
| 139 |
if not self.unknown_queue.empty(): |
| 140 |
msg = Queue.Queue.get() |
| 141 |
self.put(msg) |
| 142 |
return |
| 143 |
|
| 144 |
match.update(metadata_match) |
| 145 |
|
| 146 |
if 'station' not in match: |
| 147 |
match['station'] = 'rUnknown' |
| 148 |
|
| 149 |
sentence_tot = int(match['sen_tot']) |
| 150 |
|
| 151 |
if sentence_tot == 1: |
| 152 |
body = match['body'] |
| 153 |
fill_bits = int(match['fill_bits']) |
| 154 |
try: |
| 155 |
decoded = ais.decode(body, fill_bits) |
| 156 |
except ais.DecodeError as error: |
| 157 |
logger.error( |
| 158 |
'Unable to decode message: %s\n %d %s', error, self.line_num, line) |
| 159 |
return |
| 160 |
decoded['md5'] = hashlib.md5(body.encode('utf-8')).hexdigest() |
| 161 |
Queue.Queue.put(self, { |
| 162 |
'line_nums': [line_num], |
| 163 |
'lines': [line], |
| 164 |
'decoded': decoded, |
| 165 |
'matches': [match] |
| 166 |
}) |
| 167 |
return |
| 168 |
|
| 169 |
station = match['station'] or 'rUnknown' |
| 170 |
sentence_num = int(match['sen_num']) |
| 171 |
sequence_id = match['seq_id'] or '' |
| 172 |
group_id = station + str(sequence_id) |
| 173 |
time = util.MaybeToNumber(match['time']) |
| 174 |
|
| 175 |
if group_id not in self.groups: |
| 176 |
self.groups[group_id] = [] |
| 177 |
|
| 178 |
if not self.groups[group_id]: |
| 179 |
if sentence_num != 1: |
| 180 |
|
| 181 |
return |
| 182 |
|
| 183 |
if sentence_num == 1: |
| 184 |
self.groups[group_id] = { |
| 185 |
'line_nums': [self.line_num], |
| 186 |
'lines': [line], |
| 187 |
'matches': [match], |
| 188 |
'times': [time], |
| 189 |
} |
| 190 |
return |
| 191 |
|
| 192 |
entry = self.groups[group_id] |
| 193 |
entry['line_nums'].append(self.line_num) |
| 194 |
entry['lines'].append(line) |
| 195 |
entry['matches'].append(match) |
| 196 |
entry['times'].append(time) |
| 197 |
|
| 198 |
if sentence_num != sentence_tot: |
| 199 |
|
| 200 |
return |
| 201 |
|
| 202 |
decoded = DecodeMultiple(entry) |
| 203 |
|
| 204 |
if decoded: |
| 205 |
entry['decoded'] = decoded |
| 206 |
else: |
| 207 |
logger.info('Unable to process: %s', entry) |
| 208 |
Queue.Queue.put(self, entry) |
| 209 |
self.groups.pop(group_id) |
| 210 |
|
| 211 |
|
| 212 |
def DecodeMultiple(message): |
| 213 |
"""Decode a message that spans multiple lines.""" |
| 214 |
payloads = [msg['payload'] for msg in message['matches']] |
| 215 |
|
| 216 |
q = vdm.BareQueue() |
| 217 |
for line in vdm.VdmLines(payloads): |
| 218 |
q.put(line) |
| 219 |
if q.qsize() != 1: |
| 220 |
logger.info('Error: Should get just one message decoded from this: %s', |
| 221 |
message) |
| 222 |
return |
| 223 |
msg = q.get() |
| 224 |
return msg['decoded'] |