Debian Codegraph @

ais/nmea_messages.py

raw symbols SCIP
1 """Parse non-AIS NMEA messages.
2
3 National Marine Electronics Association (NMEA) messages are comma separated
4 value lines of text that start with sender or "talker" code and the sentence
5 type. They finish up with a checksum. For example, this is a time message
6 (ZDA) from an "Integrated Navigation" (IN) system.
7
8 This module is only concerned with the actual messages and not the wire level
9 transfer of the data as defined in NMEA 0183 or NMEA 2000.
10
11 Most users of libais will eventually want to parse the surround NMEA messages
12 for time, AIS receiver status, station location, weather, etc. The core theme
13 of libais is handling the AIVDM messages. However, leaving out the other NMEA
14 messages means that a use of libais will have to write their own wrapper for
15 other NMEA messages or bring in another library like GPSD. Very few decoders
16 have support for messages like ABK, ABM, BBM, etc. that are often encountered
17 with AIS logs. Additionally, the official NMEA specification is paywalled and
18 public documentation covers only some of the messages.
19
20 TODO(schwehr): Make sure this works with proprietary messages.
21 TODO(schwehr): Factor our a generic handler for messages that do not need
22 customization of the result. Should there be a handler parent class?
23 TODO(schwehr): Consider using namedtuple rather than dict.
24
25 See also:
26
27 http://www.catb.org/gpsd/NMEA.html
28 https://en.wikipedia.org/wiki/NMEA_0183
29
30 """
31
32 import datetime
33 import logging
34 import math
35 import re
36
37 from ais import util
38
39 logger = logging.getLogger('libais')
40
41 NMEA_HEADER_RE_STR = r'[$!](?P<talker>[A-Z][A-Z])'
42 NMEA_SENTENCE_RE_STR = NMEA_HEADER_RE_STR + r'(?P<sentence>[A-Z]{3,4}),'
43 NMEA_CHECKSUM_RE_STR = r'\*(?P<checksum>[0-9A-F][0-9A-F])'
44
45 NMEA_HEADER_RE = re.compile(NMEA_HEADER_RE_STR)
46 NMEA_SENTENCE_RE = re.compile(NMEA_SENTENCE_RE_STR)
47 NMEA_CHECKSUM_RE = re.compile(NMEA_CHECKSUM_RE_STR)
48
49
50 # TODO(schwehr): Rename TimeUtc.
51 def TimeUtc(fields):
52 seconds, fractional_seconds = FloatSplit(float(fields['seconds']))
53 microseconds = int(math.floor(fractional_seconds * 1e6))
54
55 fields['seconds'] = seconds
56 fields['microseconds'] = microseconds
57 fields['hours'] = util.MaybeToNumber(fields['hours'])
58 fields['minutes'] = util.MaybeToNumber(fields['minutes'])
59
60 when = datetime.time(
61 fields['hours'],
62 fields['minutes'],
63 seconds,
64 microseconds
65 )
66 fields['when'] = when
67
68
69 ABK_RE_STR = (
70 NMEA_HEADER_RE_STR +
71 r'(?P<sentence>ABK),'
72 r'(?P<mmsi>\d+)?,'
73 r'(?P<chan>[AB])?,'
74 r'(?P<message_id>\d+)?,'
75 r'(?P<seq_num>\d+)?,'
76 r'(?P<ack_type>\d+)' +
77 NMEA_CHECKSUM_RE_STR
78 )
79
80 ABK_RE = re.compile(ABK_RE_STR)
81
82
83 # TODO(schwehr): Document that handlers return None if they fail to match
84 # the line to their message.
85 def HandleAbk(line):
86 """Decode AIS Addressed and Binary Broadcast Acknowledgement (ABK)."""
87 try:
88 fields = ABK_RE.match(line).groupdict()
89 except TypeError:
90 return
91
92 result = {
93 'message': 'ABK',
94 'talker': fields['talker'],
95 'chan': fields['chan'],
96 }
97
98 for field in ('mmsi', 'message_id', 'seq_num', 'ack_type'):
99 result[field] = util.MaybeToNumber(fields[field])
100
101 return result
102
103
104 ADS_RE_STR = (
105 NMEA_HEADER_RE_STR +
106 r'(?P<sentence>ADS),'
107 r'(?P<id>[^,]+?),'
108 r'(?P<time_utc>(?P<hours>\d\d)(?P<minutes>\d\d)(?P<seconds>\d\d\.\d*))?,'
109 r'(?P<alarm>)[AV]?,'
110 r'(?P<time_sync_method>\d)?,'
111 r'(?P<pos_src>[EINS])?,'
112 r'(?P<time_src>[EIN])?' +
113 NMEA_CHECKSUM_RE_STR
114 )
115
116 ADS_RE = re.compile(ADS_RE_STR)
117
118
119 def HandleAds(line):
120 """Decode Automatic Device Status (ADS)."""
121 try:
122 fields = ADS_RE.match(line).groupdict()
123 except TypeError:
124 return
125
126 TimeUtc(fields)
127
128 return {
129 'message': 'ADS',
130 'talker': fields['talker'],
131 'id': fields['id'],
132 'alarm': fields['alarm'],
133 'time_sync_method': util.MaybeToNumber(fields['time_sync_method']),
134 'pos_src': fields['pos_src'],
135 'time_src': fields['time_src'],
136 'when': fields['when'],
137 }
138
139
140 ALR_RE_STR = (
141 NMEA_HEADER_RE_STR +
142 r'(?P<sentence>ALR),'
143 r'(?P<time_utc>(?P<hours>\d\d)(?P<minutes>\d\d)(?P<seconds>\d\d\.\d*))?,'
144 r'(?P<id>\d+)?,'
145 r'(?P<condition>[AV]),'
146 r'(?P<ack_state>[AV]),'
147 r'(?P<text>[^*]*)' +
148 NMEA_CHECKSUM_RE_STR
149 )
150
151 ALR_RE = re.compile(ALR_RE_STR)
152
153
154 def HandleAlr(line):
155 """Decode Set Alarm State (ALR)."""
156 try:
157 fields = ALR_RE.match(line).groupdict()
158 except TypeError:
159 return
160
161 seconds, fractional_seconds = FloatSplit(float(fields['seconds']))
162 microseconds = int(math.floor(fractional_seconds * 1e6))
163
164 when = datetime.time(
165 int(fields['hours']),
166 int(fields['minutes']),
167 seconds,
168 microseconds
169 )
170
171 result = {
172 'ack_state_raw': fields['ack_state'],
173 'condition_raw': fields['condition'],
174 'id': fields['id'],
175 'message': 'ALR',
176 'talker': fields['talker'],
177 'text': fields['text'],
178 'time': when,
179 }
180 if fields['ack_state'] in 'AV':
181 result['ack_state'] = ('A' == fields['ack_state'])
182 if fields['condition'] in 'AV':
183 result['condition'] = ('A' == fields['condition'])
184
185 return result
186
187
188 BBM_RE_STR = (
189 NMEA_HEADER_RE_STR +
190 r'(?P<sentence>BBM),'
191 r'(?P<sen_tot>\d),'
192 r'(?P<sen_num>\d),'
193 r'(?P<seq_num>\d),'
194 r'(?P<chan>\d),'
195 r'(?P<message_id>\d),'
196 r'(?P<body>[^,*]*),'
197 r'(?P<fill_bits>\d)' +
198 NMEA_CHECKSUM_RE_STR
199 )
200
201 BBM_RE = re.compile(BBM_RE_STR)
202
203
204 def HandleBbm(line):
205 """Decode Binary Broadcast Message (BBM) sentence."""
206 try:
207 fields = BBM_RE.match(line).groupdict()
208 except TypeError:
209 return
210
211 result = {
212 'message': 'BBM',
213 'talker': fields['talker'],
214 'body': fields['body'],
215 }
216
217 for field in ('sen_tot', 'sen_num', 'seq_num', 'chan', 'message_id',
218 'fill_bits'):
219 result[field] = util.MaybeToNumber(fields[field])
220
221 return result
222
223
224 FSR_RE_STR = (
225 NMEA_HEADER_RE_STR +
226 r'(?P<sentence>FSR),'
227 r'(?P<id>[^,]+)?,'
228 r'(?P<time_utc>(?P<hours>\d\d)(?P<minutes>\d\d)(?P<seconds>\d\d(\.\d*)?))?,'
229 r'(?P<chan>[A-Z])?,'
230 r'(?P<slots_recv>\d+)?,'
231 r'(?P<slots_self>\d+)?,'
232 r'(?P<crc_fails>\d+)?,'
233 r'(?P<slots_reserved>\d+)?,'
234 r'(?P<slots_reserved_self>\d+)?,'
235 r'(?P<noise_db>[-]?\d+)?,'
236 r'(?P<slots_above_noise>\d+(\.d*)?)?' +
237 NMEA_CHECKSUM_RE_STR
238 )
239
240 FSR_RE = re.compile(FSR_RE_STR)
241
242
243 def HandleFsr(line):
244 try:
245 fields = FSR_RE.match(line).groupdict()
246 except TypeError:
247 return
248
249 seconds, fractional_seconds = FloatSplit(float(fields['seconds']))
250 microseconds = int(math.floor(fractional_seconds * 1e6))
251
252 when = datetime.time(
253 int(fields['hours']),
254 int(fields['minutes']),
255 seconds,
256 microseconds
257 )
258
259 result = {
260 'message': 'FSR',
261 'id': fields['id'],
262 'chan': fields['chan'],
263 'time': when,
264 }
265 for field in ('slots_recv', 'slots_self', 'crc_fails', 'slots_reserved',
266 'slots_reserved_self', 'noise_db', 'slots_above_noise'):
267 if fields[field] is not None and fields[field]:
268 result[field] = util.MaybeToNumber(fields[field])
269
270 return result
271
272
273 GGA_RE_STR = (
274 NMEA_HEADER_RE_STR +
275 r'(?P<sentence>GGA),'
276 r'(?P<time_utc>(?P<hours>\d\d)(?P<minutes>\d\d)(?P<seconds>\d\d\.\d*))?,'
277 r'(?P<latitude>(?P<lat_deg>\d\d)(?P<lat_min>\d\d\.\d*))?,'
278 r'(?P<latitude_hemisphere>[NS])?,'
279 r'(?P<longitude>(?P<lon_deg>\d{3})(?P<lon_min>\d\d\.\d*))?,'
280 r'(?P<longitude_hemisphere>[EW])?,'
281 r'(?P<gps_quality>\d+)?,'
282 r'(?P<satellites>\d+)?,'
283 r'(?P<hdop>\d+\.\d+)?,'
284 r'(?P<antenna_height>[+-]?\d+(\.\d+)?)?,'
285 r'(?P<antenna_height_units>M)?,'
286 r'(?P<geoidal_height>[+-]?\d+(\.\d+)?)?,'
287 r'(?P<geoidal_height_units>M)?,'
288 r'(?P<differential_ref_station>[A-Z0-9.]*)?,'
289 r'(?P<differential_age_sec>\d+)?'
290 + NMEA_CHECKSUM_RE_STR
291 )
292
293 GGA_RE = re.compile(GGA_RE_STR)
294
295
296 def HandleGga(line):
297 try:
298 fields = GGA_RE.match(line).groupdict()
299 except TypeError:
300 return
301
302 seconds, fractional_seconds = FloatSplit(float(fields['seconds']))
303 microseconds = int(math.floor(fractional_seconds * 1e6))
304
305 when = datetime.time(
306 int(fields['hours']),
307 int(fields['minutes']),
308 seconds,
309 microseconds
310 )
311
312 x = int(fields['lon_deg']) + float(fields['lon_min']) / 60.0
313 if fields['longitude_hemisphere'] == 'W':
314 x = -x
315
316 y = int(fields['lat_deg']) + float(fields['lat_min']) / 60.0
317 if fields['latitude_hemisphere'] == 'S':
318 y = -y
319
320 result = {
321 'message': 'GGA',
322 'time': when,
323 'longitude': x,
324 'latitude': y,
325 }
326 for field in ('gps_quality', 'satellites', 'hdop', 'antenna_height',
327 'antenna_height_units', 'geoidal_height',
328 'geoidal_height_units', 'differential_ref_station',
329 'differential_age_sec'):
330 if fields[field] is not None and fields[field]:
331 result[field] = util.MaybeToNumber(fields[field])
332
333 return result
334
335
336 TXT_RE_STR = (
337 NMEA_HEADER_RE_STR +
338 r'(?P<sentence>TXT),'
339 r'(?P<sen_tot>\d+)?,'
340 r'(?P<sen_num>\d+)?,'
341 r'(?P<seq_num>\d+)?,'
342 r'(?P<text>[^*]*)?'
343 + NMEA_CHECKSUM_RE_STR
344 )
345
346 TXT_RE = re.compile(TXT_RE_STR)
347
348
349 def HandleTxt(line):
350 """Decode Text Transmission (TXT).
351
352 TODO(schwehr): Handle encoded characters. e.g. ^21 is a '!'.
353
354 Args:
355 line: A string containing a NMEA TXT message.
356
357 Returns:
358 A dictionary with the decoded fields or None if it cannot decode
359 the message.
360 """
361 try:
362 fields = TXT_RE.match(line).groupdict()
363 except TypeError:
364 return
365
366 result = {
367 'message': 'TXT',
368 'talker': fields['talker'],
369 'text': fields['text'],
370 }
371
372 for field in ('sen_tot', 'sen_num', 'seq_num'):
373 result[field] = util.MaybeToNumber(fields[field])
374
375 return result
376
377
378 # Time in UTC.
379 ZDA_RE_STR = (
380 NMEA_HEADER_RE_STR +
381 r'(?P<sentence>ZDA),'
382 r'(?P<time_utc>(?P<hours>\d\d)(?P<minutes>\d\d)(?P<seconds>\d\d(\.\d*)?))?,'
383 r'(?P<day>\d\d)?,'
384 r'(?P<month>\d\d)?,'
385 r'(?P<year>\d{4})?,'
386 r'(?P<zone_hours>[+-]?(\d+))?,'
387 r'(?P<zone_minutes>(\d+))?' # ',?'
388 + NMEA_CHECKSUM_RE_STR
389 )
390
391 ZDA_RE = re.compile(ZDA_RE_STR)
392
393
394 def FloatSplit(value):
395 base = math.trunc(value)
396 fractional = value - base
397 return base, fractional
398
399
400 def HandleZda(line):
401 try:
402 fields = ZDA_RE.match(line).groupdict()
403 except TypeError:
404 return
405
406 for field in ('year', 'month', 'day', 'hours', 'minutes', 'zone_hours',
407 'zone_minutes'):
408 if fields[field] is not None and fields[field]:
409 fields[field] = util.MaybeToNumber(fields[field])
410
411 seconds, fractional_seconds = FloatSplit(float(fields['seconds']))
412 microseconds = int(math.floor(fractional_seconds * 1e6))
413 when = datetime.datetime(
414 fields['year'],
415 fields['month'],
416 fields['day'],
417 fields['hours'],
418 fields['minutes'],
419 seconds,
420 microseconds)
421
422 # TODO(schwehr): Convert this to Unix UTC seconds.
423 return {
424 'message': 'ZDA',
425 'talker': fields['talker'],
426 'datetime': when,
427 'zone_hours': fields['zone_hours'],
428 'zone_minutes': fields['zone_minutes'],
429 }
430
431
432 HANDLERS = {
433 'ABK': HandleAbk,
434 'ADS': HandleAds,
435 'ALR': HandleAlr,
436 'BBM': HandleBbm,
437 'FSR': HandleFsr,
438 'GGA': HandleGga,
439 'TXT': HandleTxt,
440 'ZDA': HandleZda
441 }
442
443
444 def DecodeLine(line):
445 """Decode a NMEA line.
446
447 Args:
448 line: A string with single line containing a possible NMEA sentence.
449
450 Returns:
451 A dict mapping the message and sentence fields or None if it is unable
452 to decode the line.
453 """
454 line = line.rstrip()
455 try:
456 sentence = NMEA_SENTENCE_RE.match(line).groupdict()['sentence']
457 except AttributeError:
458 # Not NMEA.
459 return
460
461 if sentence not in HANDLERS:
462 logger.info('skipping: %s', line)
463 return
464
465 try:
466 message = HANDLERS[sentence](line)
467 except AttributeError:
468 logger.info('Unable to decode line with handle: %s', line)
469 return
470
471 return message