Debian Codegraph @

ais/stream/__init__.py

raw symbols SCIP
1 # Based on ais_normalize.py from https://github.com/schwehr/noaadata
2
3 import sys
4 import traceback
5 import warnings
6
7 import ais
8 from ais.stream import checksum
9
10 warnings.warn(
11 "The stream module is deprecated and will be removed in 1.0",
12 FutureWarning,
13 stacklevel=2
14 )
15
16
17 def ErrorPrinter(e,
18 stats,
19 verbose=False,
20 max_errors=None, # In % of total number of input lines
21 **kw):
22 if max_errors != None and float(stats["error_num_total"]) / float(stats["line_num"]) * 100.0 > max_errors:
23 raise TooManyErrorsError(**stats)
24 if verbose:
25 sys.stderr.write('%s\n' % e)
26
27
28 # def ErrorRaiser(e, stats, **kw):
29 # raise e
30
31
32 class StreamError(Exception):
33
34 description = 'Stream error'
35
36 def __init__(self, **kw):
37 self.kw = kw
38 self.kw['description'] = self.description
39
40 def __str__(self):
41 return '%(description)s: %(line_num)s: %(line)s' % self.kw
42
43
44 class InvalidChecksumError(StreamError):
45 description = 'Invalid checksum'
46
47
48 class InvalidChecksumInConstructedError(StreamError):
49 description = 'Invalid checksum in constructed one-liner'
50
51
52 class NoStationFoundError(StreamError):
53 description = 'No station found'
54
55
56 class TooFewFieldsError(StreamError):
57 description = 'Too few fields'
58
59 def __str__(self):
60 return '%(description)s, got %(fields)s but needed 6: %(line_num)s: %(line)s' % self.kw
61
62
63 class MissingTimestampsError(StreamError):
64 description = 'Timestamps missing'
65
66 def __str__(self):
67 return '%(description)s: %(line_num)s: %(line)s, parts: %(parts)s' % self.kw
68
69 class DifferingTimestampsError(StreamError):
70 description = 'Timestamps not all the same'
71
72 def __str__(self):
73 return '%(description)s for %(timestamp)s: %(line_num)s: %(line)s, parts: %(parts)s' % self.kw
74
75 class OnlyMessageEndError(StreamError):
76 description = 'Do not have the preceeding packets for'
77
78 def __str__(self):
79 return '%(description)s for %(bufferSlot)s:\n%(line)s\n' % self.kw
80
81 class UnfinishedMessagesError(StreamError):
82 description = 'Unfinished messages at end of file'
83
84 def __str__(self):
85 return '%(description)s:\n%(buffers)s\n' % self.kw
86
87
88 class TooManyErrorsError(StreamError):
89 description = 'Too many errors'
90
91 def __str__(self):
92 res = dict(self.kw)
93 res['error_lines'] = ""
94 if 'error_num' in res:
95 res['error_lines'] = "\n" + "\n".join(" %s: %s" % (error, num) for error, num in res['error_num'].iteritems())
96 return '%(description)s: %(error_num_total)s errors in %(line_num)s lines:%(error_lines)s' % res
97
98
99 def parseTagBlock(line):
100 if not line.startswith("\\"):
101 return {}, line
102 tagblock, line = line[1:].split("\\", 1)
103 tagblock, checksum = tagblock.rsplit("*", 1)
104
105 tags = {}
106 for field in tagblock.split(","):
107 key, value = field.split(":")
108
109 if key == 'c':
110 key = 'timestamp'
111 value = int(value)
112 # This can be either seconds or milliseconds...
113 if value > 40000000000:
114 value = value / 1000.0
115 elif key == 'n':
116 key = 'line_count'
117 value = int(value)
118 elif key == 'r':
119 key = 'relative_time'
120 value = int(value)
121 elif key == 'd':
122 key = 'destination'
123 elif key == 's':
124 key = 'station'
125 elif key == 't':
126 key = 'text'
127 elif key == 'g':
128 key = 'group'
129 value = dict(zip(["sentence", "groupsize", "id"],
130 [int(part) for part in value.split("-")]))
131
132 tags["tagblock_" + key] = value
133 return tags, line
134
135
136 def add_error_to_stats(e, stats):
137 if "error_num_total" not in stats:
138 stats["error_num_total"] = 0
139 stats["error_num_total"] += 1
140 if "error_num" not in stats:
141 stats["error_num"] = {}
142 name = getattr(e, "description", getattr(e, "message", str(type(e))))
143 if name not in stats["error_num"]:
144 stats["error_num"][name] = 0
145 stats["error_num"][name] += 1
146
147
148 def normalize(nmea=sys.stdin,
149 uscg=True,
150 validate_checksum=True,
151 allow_unknown=False,
152 window=2,
153 ignore_tagblock_station=False,
154 treat_ab_equal=False,
155 pass_invalid_checksums=False,
156 allow_missing_timestamps=False,
157 errorcb=ErrorPrinter,
158 stats=None,
159 **kw):
160 """Assemble multi-line messages
161
162 Args:
163 nmea: iterator of lines to read
164 window: number of seconds to allow the later parts of a multiline message to span
165 """
166
167 buffers = {} # Put partial messages in a queue by station so that they can be reassembled
168 if stats is None: stats={}
169 stats['line_num'] = stats.pop('line_num', 0)
170 stats['error_num_total'] = stats.pop('error_num_total', 0)
171 stats['invalid_checksums'] = stats.pop('invalid_checksums', 0)
172
173 def report_error(e):
174 add_error_to_stats(e, stats)
175 errorcb(e, stats, **kw)
176
177 if not uscg:
178 report_error('Need to make a faster version that does not worry about the extra args and stations dict')
179 assert False
180
181 for idx, origline in enumerate(nmea):
182 try:
183 tagblock, line = parseTagBlock(origline)
184
185 line = line.strip() + '\n' # Get rid of DOS issues.
186 stats["line_num"] += 1
187 if len(line) < 7 or line[3:6] not in ('VDM', 'VDO'):
188 yield tagblock, line, origline
189 continue
190
191 if validate_checksum and not checksum.isChecksumValid(line):
192 stats["invalid_checksums"] += 1
193 report_error(InvalidChecksumError(line_num=stats["line_num"], line=line.strip()))
194 if not pass_invalid_checksums:
195 continue
196
197 fields = line.split(',')
198
199 if len(fields) < 6:
200 report_error(TooFewFieldsError(line_num=stats["line_num"],
201 line=line.strip(),
202 fields=len(fields)))
203 continue
204
205 # Total NMEA lines that compose this message [1..9].
206 totNumSentences = int(fields[1])
207 if 1 == totNumSentences:
208 # A single line needs no work, so pass it along.
209 yield tagblock, line, origline
210 continue
211
212 sentenceNum = int(fields[2]) # Message sequence number 1..9 (packetNum)
213 payload = fields[5] # AIS binary data encoded in whacky ways
214 timestamp = fields[-1].strip() # Seconds since Epoch UTC. Always the last field
215
216 station = None # USCG Receive Stations # if None==station:
217 for i in range(len(fields)-1, 5, -1):
218 if len(fields[i]) and fields[i][0] in ('r', 'b'):
219 station = fields[i]
220 break # Found it so ditch the for loop.
221
222 if ignore_tagblock_station:
223 tagblock_station = None
224 else:
225 tagblock_station = tagblock.get('tagblock_station', None)
226
227 if station is None and allow_unknown:
228 station = 'UNKNOWN'
229
230 if station is None and tagblock_station is None:
231 report_error(NoStationFoundError(line_num=stats["line_num"], line=line.strip()))
232 continue
233
234 bufferSlot = (tagblock_station, station, fields[3]) # seqId and Channel make a unique stream
235
236 if not treat_ab_equal:
237 bufferSlot += (fields[4],) # channel id
238
239 newPacket = {"payload": payload,
240 "timestamp": timestamp,
241 "tagblock": tagblock,
242 "origline": origline}
243 if sentenceNum == 1:
244 buffers[bufferSlot] = [newPacket] # Overwrite any partials
245 continue
246
247 if totNumSentences == sentenceNum:
248 # Finished a message
249 if bufferSlot not in buffers:
250 report_error(OnlyMessageEndError(line=line, bufferSlot=bufferSlot))
251 continue
252 buffers[bufferSlot].append(newPacket)
253 parts = buffers[bufferSlot] # Now have all the pieces.
254 del buffers[bufferSlot] # Clear out the used packets to save memory.
255
256 # Sanity check
257 ok = True
258 ts1 = None
259 for part in parts:
260 try:
261 ts1 = float(part['timestamp'])
262 ts2 = float(timestamp)
263 except ValueError:
264 try:
265 ts1 = float(part['tagblock']['tagblock_timestamp'])
266 ts2 = float(tagblock['tagblock_timestamp'])
267 except:
268 if allow_missing_timestamps:
269 ts1 = 0
270 ts2 = 0
271 else:
272 report_error(MissingTimestampsError(line_num=stats["line_num"],
273 line=line.strip(),
274 timestamp=timestamp, parts=parts))
275 ok = False
276 break
277 if ts1 > ts2+window or ts1 < ts2-window:
278 report_error(DifferingTimestampsError(line_num=stats["line_num"],
279 line=line.strip(),
280 timestamp=timestamp, parts=parts))
281 ok = False
282 break
283 if not ok:
284 continue
285
286 payload = ''.join([p['payload'] for p in parts])
287 tagblock = {}
288 for p in reversed(parts):
289 tagblock.update(p['tagblock'])
290
291 # Try to mirror the packet as much as possible... same seqId and channel.
292 checksumed_str = ','.join((fields[0], '1,1', fields[3], fields[4],
293 payload, fields[6].split('*')[0]+'*'))
294 if ts1 == 0:
295 # allowed missing timestamp and it is missing
296 if len(fields[7:-1]) == 0:
297 out_str = checksumed_str + checksum.checksumStr(checksumed_str)
298 else:
299 out_str = checksumed_str + checksum.checksumStr(checksumed_str) +',' + ','.join(fields[7:-1])
300 else:
301 out_str = checksumed_str + checksum.checksumStr(checksumed_str) +',' + ','.join(fields[7:])
302
303 if not checksum.isChecksumValid(out_str):
304 report_error(InvalidChecksumInConstructedError(line_num=stats["line_num"], line=line.strip()))
305
306 out_str = out_str.strip()+'\n' # FIX: Why do I have to do this last strip?
307 origstr = ''.join([p['origline'] for p in parts])
308
309 yield tagblock, out_str, origstr
310
311 continue
312
313 buffers[bufferSlot].append(newPacket)
314 except TooManyErrorsError:
315 raise
316 except Exception as inst:
317 report_error(inst)
318
319 if buffers:
320 report_error(UnfinishedMessagesError(buffers=buffers))
321
322
323 def decode(nmea=sys.stdin,
324 errorcb=ErrorPrinter,
325 keep_nmea=False,
326 stats=None,
327 **kw):
328 """Decodes a stream of AIS messages. Takes the same arguments as normalize."""
329
330 if stats is None: stats={}
331
332 def report_error(e):
333 add_error_to_stats(e, stats)
334 errorcb(e, stats, **kw)
335
336 for tagblock, line, origline in normalize(nmea=nmea, errorcb=errorcb, stats=stats, **kw):
337 try:
338 body = ''.join(line.split(',')[5])
339 pad = int(line.split('*')[0][-1])
340 res = ais.decode(body, pad)
341 res.update(tagblock)
342 if keep_nmea:
343 res['nmea'] = origline
344 yield res
345 except TooManyErrorsError:
346 raise
347 except Exception as e:
348 report_error(e)