1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-12-04 $'.split()[1]
5 __author__ = 'xmlbinmsg'
6
7 __doc__='''
8
9 Autogenerated python functions to serialize/deserialize binary messages.
10
11 Generated by: ./aisxmlbinmsg2py.py
12
13 Need to then wrap these functions with the outer AIS packet and then
14 convert the whole binary blob to a NMEA string. Those functions are
15 not currently provided in this file.
16
17 serialize: python to ais binary
18 deserialize: ais binary to python
19
20 The generated code uses translators.py, binary.py, and aisstring.py
21 which should be packaged with the resulting files.
22
23
24 @requires: U{epydoc<http://epydoc.sourceforge.net/>} > 3.0alpha3
25 @requires: U{BitVector<http://cheeseshop.python.org/pypi/BitVector>}
26
27 @author: '''+__author__+'''
28 @version: ''' + __version__ +'''
29 @var __date__: Date of last svn commit
30 @undocumented: __version__ __author__ __doc__ parser
31 @status: under development
32 @license: Generated code has no license
33 @todo: FIX: put in a description of the message here with fields and types.
34 '''
35
36 import sys
37 from decimal import Decimal
38 from BitVector import BitVector
39
40 import binary, aisstring
41
42
43 TrueBV = BitVector(bitstring="1")
44 "Why always rebuild the True bit? This should speed things up a bunch"
45 FalseBV = BitVector(bitstring="0")
46 "Why always rebuild the False bit? This should speed things up a bunch"
47
48
49 fieldList = (
50 'MessageID',
51 'RepeatIndicator',
52 'UserID',
53 'Reserved1',
54 'SOG',
55 'PositionAccuracy',
56 'longitude',
57 'latitude',
58 'COG',
59 'TrueHeading',
60 'TimeStamp',
61 'Reserved2',
62 'name',
63 'shipandcargo',
64 'dimA',
65 'dimB',
66 'dimC',
67 'dimD',
68 'fixtype',
69 'RAIM',
70 'DTE',
71 'Spare',
72 )
73
74 fieldListPostgres = (
75 'MessageID',
76 'RepeatIndicator',
77 'UserID',
78 'Reserved1',
79 'SOG',
80 'PositionAccuracy',
81 'Position',
82 'COG',
83 'TrueHeading',
84 'TimeStamp',
85 'Reserved2',
86 'name',
87 'shipandcargo',
88 'dimA',
89 'dimB',
90 'dimC',
91 'dimD',
92 'fixtype',
93 'RAIM',
94 'DTE',
95 'Spare',
96 )
97
98 toPgFields = {
99 'longitude':'Position',
100 'latitude':'Position',
101 }
102 '''
103 Go to the Postgis field names from the straight field name
104 '''
105
106 fromPgFields = {
107 'Position':('longitude','latitude',),
108 }
109 '''
110 Go from the Postgis field names to the straight field name
111 '''
112
113 pgTypes = {
114 'Position':'POINT',
115 }
116 '''
117 Lookup table for each postgis field name to get its type.
118 '''
119
120 -def encode(params, validate=False):
121 '''Create a b_pos_and_shipdata_broken binary message payload to pack into an AIS Msg b_pos_and_shipdata_broken.
122
123 Fields in params:
124 - MessageID(uint): AIS message number. Must be 19 (field automatically set to "19")
125 - RepeatIndicator(uint): Indicated how many times a message has been repeated
126 - UserID(uint): Unique ship identification number (MMSI)
127 - Reserved1(uint): Reseverd for definition by a compentent regional or local authority. Should be set to zero. (field automatically set to "0")
128 - SOG(udecimal): Speed over ground
129 - PositionAccuracy(uint): Accuracy of positioning fixes
130 - longitude(decimal): Location of the vessel East West location
131 - latitude(decimal): Location of the vessel North South location
132 - COG(udecimal): Course over ground
133 - TrueHeading(uint): True heading (relative to true North)
134 - TimeStamp(uint): UTC second when the report was generated
135 - Reserved2(uint): Reseverd for definition by a compentent regional authority. (field automatically set to "0")
136 - name(aisstr6): Vessel name
137 - shipandcargo(uint): what
138 - dimA(uint): Distance from bow to reference position
139 - dimB(uint): Distance from reference position to stern
140 - dimC(uint): Distance from port side to reference position
141 - dimD(uint): Distance from reference position to starboard side
142 - fixtype(uint): Method used for positioning
143 - RAIM(bool): Receiver autonomous integrity monitoring flag
144 - DTE(uint): Data terminal ready
145 - Spare(uint): Not used. Should be set to zero (field automatically set to "0")
146 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
147 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
148 @rtype: BitVector
149 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
150 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
151 '''
152
153 bvList = []
154 bvList.append(binary.setBitVectorSize(BitVector(intVal=19),6))
155 if 'RepeatIndicator' in params:
156 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
157 else:
158 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
159 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
160 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),8))
161 if 'SOG' in params:
162 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['SOG'])*Decimal('10')))),10))
163 else:
164 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)),10))
165 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['PositionAccuracy']),1))
166 if 'longitude' in params:
167 bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28))
168 else:
169 bvList.append(binary.bvFromSignedInt(108600000,28))
170 if 'latitude' in params:
171 bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27))
172 else:
173 bvList.append(binary.bvFromSignedInt(54600000,27))
174 if 'COG' in params:
175 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['COG'])*Decimal('10')))),12))
176 else:
177 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(3600)),12))
178 if 'TrueHeading' in params:
179 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TrueHeading']),9))
180 else:
181 bvList.append(binary.setBitVectorSize(BitVector(intVal=511),9))
182 if 'TimeStamp' in params:
183 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TimeStamp']),6))
184 else:
185 bvList.append(binary.setBitVectorSize(BitVector(intVal=60),6))
186 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4))
187 if 'name' in params:
188 bvList.append(aisstring.encode(params['name'],120))
189 else:
190 bvList.append(aisstring.encode('@@@@@@@@@@@@@@@@@@@@',120))
191 if 'shipandcargo' in params:
192 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['shipandcargo']),8))
193 else:
194 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),8))
195 if 'dimA' in params:
196 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dimA']),9))
197 else:
198 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),9))
199 if 'dimB' in params:
200 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dimB']),9))
201 else:
202 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),9))
203 if 'dimC' in params:
204 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dimC']),6))
205 else:
206 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),6))
207 if 'dimD' in params:
208 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dimD']),6))
209 else:
210 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),6))
211 if 'fixtype' in params:
212 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['fixtype']),4))
213 else:
214 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4))
215 if params["RAIM"]: bvList.append(TrueBV)
216 else: bvList.append(FalseBV)
217 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['DTE']),1))
218 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),5))
219
220 return binary.joinBV(bvList)
221
222 -def decode(bv, validate=False):
223 '''Unpack a b_pos_and_shipdata_broken message
224
225 Fields in params:
226 - MessageID(uint): AIS message number. Must be 19 (field automatically set to "19")
227 - RepeatIndicator(uint): Indicated how many times a message has been repeated
228 - UserID(uint): Unique ship identification number (MMSI)
229 - Reserved1(uint): Reseverd for definition by a compentent regional or local authority. Should be set to zero. (field automatically set to "0")
230 - SOG(udecimal): Speed over ground
231 - PositionAccuracy(uint): Accuracy of positioning fixes
232 - longitude(decimal): Location of the vessel East West location
233 - latitude(decimal): Location of the vessel North South location
234 - COG(udecimal): Course over ground
235 - TrueHeading(uint): True heading (relative to true North)
236 - TimeStamp(uint): UTC second when the report was generated
237 - Reserved2(uint): Reseverd for definition by a compentent regional authority. (field automatically set to "0")
238 - name(aisstr6): Vessel name
239 - shipandcargo(uint): what
240 - dimA(uint): Distance from bow to reference position
241 - dimB(uint): Distance from reference position to stern
242 - dimC(uint): Distance from port side to reference position
243 - dimD(uint): Distance from reference position to starboard side
244 - fixtype(uint): Method used for positioning
245 - RAIM(bool): Receiver autonomous integrity monitoring flag
246 - DTE(uint): Data terminal ready
247 - Spare(uint): Not used. Should be set to zero (field automatically set to "0")
248 @type bv: BitVector
249 @param bv: Bits defining a message
250 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
251 @rtype: dict
252 @return: params
253 '''
254
255
256
257
258 r = {}
259 r['MessageID']=19
260 r['RepeatIndicator']=int(bv[6:8])
261 r['UserID']=int(bv[8:38])
262 r['Reserved1']=0
263 r['SOG']=Decimal(int(bv[46:56]))/Decimal('10')
264 r['PositionAccuracy']=int(bv[56:57])
265 r['longitude']=Decimal(binary.signedIntFromBV(bv[57:85]))/Decimal('600000')
266 r['latitude']=Decimal(binary.signedIntFromBV(bv[85:112]))/Decimal('600000')
267 r['COG']=Decimal(int(bv[112:124]))/Decimal('10')
268 r['TrueHeading']=int(bv[124:133])
269 r['TimeStamp']=int(bv[133:139])
270 r['Reserved2']=0
271 r['name']=aisstring.decode(bv[143:263])
272 r['shipandcargo']=int(bv[263:271])
273 r['dimA']=int(bv[271:280])
274 r['dimB']=int(bv[280:289])
275 r['dimC']=int(bv[289:295])
276 r['dimD']=int(bv[295:301])
277 r['fixtype']=int(bv[301:305])
278 r['RAIM']=bool(int(bv[305:306]))
279 r['DTE']=int(bv[306:307])
280 r['Spare']=0
281 return r
282
285
288
291
294
296 return Decimal(int(bv[46:56]))/Decimal('10')
297
299 return int(bv[56:57])
300
303
306
308 return Decimal(int(bv[112:124]))/Decimal('10')
309
311 return int(bv[124:133])
312
314 return int(bv[133:139])
315
318
321
323 return int(bv[263:271])
324
326 return int(bv[271:280])
327
329 return int(bv[280:289])
330
332 return int(bv[289:295])
333
335 return int(bv[295:301])
336
338 return int(bv[301:305])
339
341 return bool(int(bv[305:306]))
342
344 return int(bv[306:307])
345
348
349
351 out.write("<h3>b_pos_and_shipdata_broken</h3>\n")
352 out.write("<table border=\"1\">\n")
353 out.write("<tr bgcolor=\"orange\">\n")
354 out.write("<th align=\"left\">Field Name</th>\n")
355 out.write("<th align=\"left\">Type</th>\n")
356 out.write("<th align=\"left\">Value</th>\n")
357 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
358 out.write("<th align=\"left\">Units</th>\n")
359 out.write("\n")
360 out.write("<tr>\n")
361 out.write("<td>MessageID</td>\n")
362 out.write("<td>uint</td>\n")
363 if 'MessageID' in params:
364 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
365 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
366 out.write("</tr>\n")
367 out.write("\n")
368 out.write("<tr>\n")
369 out.write("<td>RepeatIndicator</td>\n")
370 out.write("<td>uint</td>\n")
371 if 'RepeatIndicator' in params:
372 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n")
373 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut:
374 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>")
375 else:
376 out.write("<td><i>Missing LUT entry</i></td>")
377 out.write("</tr>\n")
378 out.write("\n")
379 out.write("<tr>\n")
380 out.write("<td>UserID</td>\n")
381 out.write("<td>uint</td>\n")
382 if 'UserID' in params:
383 out.write(" <td>"+str(params['UserID'])+"</td>\n")
384 out.write(" <td>"+str(params['UserID'])+"</td>\n")
385 out.write("</tr>\n")
386 out.write("\n")
387 out.write("<tr>\n")
388 out.write("<td>Reserved1</td>\n")
389 out.write("<td>uint</td>\n")
390 if 'Reserved1' in params:
391 out.write(" <td>"+str(params['Reserved1'])+"</td>\n")
392 out.write(" <td>"+str(params['Reserved1'])+"</td>\n")
393 out.write("</tr>\n")
394 out.write("\n")
395 out.write("<tr>\n")
396 out.write("<td>SOG</td>\n")
397 out.write("<td>udecimal</td>\n")
398 if 'SOG' in params:
399 out.write(" <td>"+str(params['SOG'])+"</td>\n")
400 if str(params['SOG']) in SOGDecodeLut:
401 out.write("<td>"+SOGDecodeLut[str(params['SOG'])]+"</td>")
402 else:
403 out.write("<td><i>Missing LUT entry</i></td>")
404 out.write("<td>knots</td>\n")
405 out.write("</tr>\n")
406 out.write("\n")
407 out.write("<tr>\n")
408 out.write("<td>PositionAccuracy</td>\n")
409 out.write("<td>uint</td>\n")
410 if 'PositionAccuracy' in params:
411 out.write(" <td>"+str(params['PositionAccuracy'])+"</td>\n")
412 if str(params['PositionAccuracy']) in PositionAccuracyDecodeLut:
413 out.write("<td>"+PositionAccuracyDecodeLut[str(params['PositionAccuracy'])]+"</td>")
414 else:
415 out.write("<td><i>Missing LUT entry</i></td>")
416 out.write("</tr>\n")
417 out.write("\n")
418 out.write("<tr>\n")
419 out.write("<td>longitude</td>\n")
420 out.write("<td>decimal</td>\n")
421 if 'longitude' in params:
422 out.write(" <td>"+str(params['longitude'])+"</td>\n")
423 out.write(" <td>"+str(params['longitude'])+"</td>\n")
424 out.write("<td>degrees</td>\n")
425 out.write("</tr>\n")
426 out.write("\n")
427 out.write("<tr>\n")
428 out.write("<td>latitude</td>\n")
429 out.write("<td>decimal</td>\n")
430 if 'latitude' in params:
431 out.write(" <td>"+str(params['latitude'])+"</td>\n")
432 out.write(" <td>"+str(params['latitude'])+"</td>\n")
433 out.write("<td>degrees</td>\n")
434 out.write("</tr>\n")
435 out.write("\n")
436 out.write("<tr>\n")
437 out.write("<td>COG</td>\n")
438 out.write("<td>udecimal</td>\n")
439 if 'COG' in params:
440 out.write(" <td>"+str(params['COG'])+"</td>\n")
441 out.write(" <td>"+str(params['COG'])+"</td>\n")
442 out.write("<td>degrees</td>\n")
443 out.write("</tr>\n")
444 out.write("\n")
445 out.write("<tr>\n")
446 out.write("<td>TrueHeading</td>\n")
447 out.write("<td>uint</td>\n")
448 if 'TrueHeading' in params:
449 out.write(" <td>"+str(params['TrueHeading'])+"</td>\n")
450 out.write(" <td>"+str(params['TrueHeading'])+"</td>\n")
451 out.write("<td>degrees</td>\n")
452 out.write("</tr>\n")
453 out.write("\n")
454 out.write("<tr>\n")
455 out.write("<td>TimeStamp</td>\n")
456 out.write("<td>uint</td>\n")
457 if 'TimeStamp' in params:
458 out.write(" <td>"+str(params['TimeStamp'])+"</td>\n")
459 if str(params['TimeStamp']) in TimeStampDecodeLut:
460 out.write("<td>"+TimeStampDecodeLut[str(params['TimeStamp'])]+"</td>")
461 else:
462 out.write("<td><i>Missing LUT entry</i></td>")
463 out.write("<td>seconds</td>\n")
464 out.write("</tr>\n")
465 out.write("\n")
466 out.write("<tr>\n")
467 out.write("<td>Reserved2</td>\n")
468 out.write("<td>uint</td>\n")
469 if 'Reserved2' in params:
470 out.write(" <td>"+str(params['Reserved2'])+"</td>\n")
471 out.write(" <td>"+str(params['Reserved2'])+"</td>\n")
472 out.write("</tr>\n")
473 out.write("\n")
474 out.write("<tr>\n")
475 out.write("<td>name</td>\n")
476 out.write("<td>aisstr6</td>\n")
477 if 'name' in params:
478 out.write(" <td>"+str(params['name'])+"</td>\n")
479 out.write(" <td>"+str(params['name'])+"</td>\n")
480 out.write("</tr>\n")
481 out.write("\n")
482 out.write("<tr>\n")
483 out.write("<td>shipandcargo</td>\n")
484 out.write("<td>uint</td>\n")
485 if 'shipandcargo' in params:
486 out.write(" <td>"+str(params['shipandcargo'])+"</td>\n")
487 if str(params['shipandcargo']) in shipandcargoDecodeLut:
488 out.write("<td>"+shipandcargoDecodeLut[str(params['shipandcargo'])]+"</td>")
489 else:
490 out.write("<td><i>Missing LUT entry</i></td>")
491 out.write("</tr>\n")
492 out.write("\n")
493 out.write("<tr>\n")
494 out.write("<td>dimA</td>\n")
495 out.write("<td>uint</td>\n")
496 if 'dimA' in params:
497 out.write(" <td>"+str(params['dimA'])+"</td>\n")
498 out.write(" <td>"+str(params['dimA'])+"</td>\n")
499 out.write("<td>m</td>\n")
500 out.write("</tr>\n")
501 out.write("\n")
502 out.write("<tr>\n")
503 out.write("<td>dimB</td>\n")
504 out.write("<td>uint</td>\n")
505 if 'dimB' in params:
506 out.write(" <td>"+str(params['dimB'])+"</td>\n")
507 out.write(" <td>"+str(params['dimB'])+"</td>\n")
508 out.write("<td>m</td>\n")
509 out.write("</tr>\n")
510 out.write("\n")
511 out.write("<tr>\n")
512 out.write("<td>dimC</td>\n")
513 out.write("<td>uint</td>\n")
514 if 'dimC' in params:
515 out.write(" <td>"+str(params['dimC'])+"</td>\n")
516 if str(params['dimC']) in dimCDecodeLut:
517 out.write("<td>"+dimCDecodeLut[str(params['dimC'])]+"</td>")
518 else:
519 out.write("<td><i>Missing LUT entry</i></td>")
520 out.write("<td>m</td>\n")
521 out.write("</tr>\n")
522 out.write("\n")
523 out.write("<tr>\n")
524 out.write("<td>dimD</td>\n")
525 out.write("<td>uint</td>\n")
526 if 'dimD' in params:
527 out.write(" <td>"+str(params['dimD'])+"</td>\n")
528 if str(params['dimD']) in dimDDecodeLut:
529 out.write("<td>"+dimDDecodeLut[str(params['dimD'])]+"</td>")
530 else:
531 out.write("<td><i>Missing LUT entry</i></td>")
532 out.write("<td>m</td>\n")
533 out.write("</tr>\n")
534 out.write("\n")
535 out.write("<tr>\n")
536 out.write("<td>fixtype</td>\n")
537 out.write("<td>uint</td>\n")
538 if 'fixtype' in params:
539 out.write(" <td>"+str(params['fixtype'])+"</td>\n")
540 if str(params['fixtype']) in fixtypeDecodeLut:
541 out.write("<td>"+fixtypeDecodeLut[str(params['fixtype'])]+"</td>")
542 else:
543 out.write("<td><i>Missing LUT entry</i></td>")
544 out.write("</tr>\n")
545 out.write("\n")
546 out.write("<tr>\n")
547 out.write("<td>RAIM</td>\n")
548 out.write("<td>bool</td>\n")
549 if 'RAIM' in params:
550 out.write(" <td>"+str(params['RAIM'])+"</td>\n")
551 if str(params['RAIM']) in RAIMDecodeLut:
552 out.write("<td>"+RAIMDecodeLut[str(params['RAIM'])]+"</td>")
553 else:
554 out.write("<td><i>Missing LUT entry</i></td>")
555 out.write("</tr>\n")
556 out.write("\n")
557 out.write("<tr>\n")
558 out.write("<td>DTE</td>\n")
559 out.write("<td>uint</td>\n")
560 if 'DTE' in params:
561 out.write(" <td>"+str(params['DTE'])+"</td>\n")
562 if str(params['DTE']) in DTEDecodeLut:
563 out.write("<td>"+DTEDecodeLut[str(params['DTE'])]+"</td>")
564 else:
565 out.write("<td><i>Missing LUT entry</i></td>")
566 out.write("</tr>\n")
567 out.write("\n")
568 out.write("<tr>\n")
569 out.write("<td>Spare</td>\n")
570 out.write("<td>uint</td>\n")
571 if 'Spare' in params:
572 out.write(" <td>"+str(params['Spare'])+"</td>\n")
573 out.write(" <td>"+str(params['Spare'])+"</td>\n")
574 out.write("</tr>\n")
575 out.write("</table>\n")
576
577
579 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
580 out.write("\ <Placemark>\n")
581 out.write("\t <name>"+str(params['UserID'])+"</name>\n")
582 out.write("\t\t<description>\n")
583 import StringIO
584 buf = StringIO.StringIO()
585 printHtml(params,buf)
586 import cgi
587 out.write(cgi.escape(buf.getvalue()))
588 out.write("\t\t</description>\n")
589 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
590 out.write("\t\t<Point>\n")
591 out.write("\t\t\t<coordinates>")
592 out.write(str(params['longitude']))
593 out.write(',')
594 out.write(str(params['latitude']))
595 out.write(",0</coordinates>\n")
596 out.write("\t\t</Point>\n")
597 out.write("\t</Placemark>\n")
598
599 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
600 '''Print a b_pos_and_shipdata_broken message to stdout.
601
602 Fields in params:
603 - MessageID(uint): AIS message number. Must be 19 (field automatically set to "19")
604 - RepeatIndicator(uint): Indicated how many times a message has been repeated
605 - UserID(uint): Unique ship identification number (MMSI)
606 - Reserved1(uint): Reseverd for definition by a compentent regional or local authority. Should be set to zero. (field automatically set to "0")
607 - SOG(udecimal): Speed over ground
608 - PositionAccuracy(uint): Accuracy of positioning fixes
609 - longitude(decimal): Location of the vessel East West location
610 - latitude(decimal): Location of the vessel North South location
611 - COG(udecimal): Course over ground
612 - TrueHeading(uint): True heading (relative to true North)
613 - TimeStamp(uint): UTC second when the report was generated
614 - Reserved2(uint): Reseverd for definition by a compentent regional authority. (field automatically set to "0")
615 - name(aisstr6): Vessel name
616 - shipandcargo(uint): what
617 - dimA(uint): Distance from bow to reference position
618 - dimB(uint): Distance from reference position to stern
619 - dimC(uint): Distance from port side to reference position
620 - dimD(uint): Distance from reference position to starboard side
621 - fixtype(uint): Method used for positioning
622 - RAIM(bool): Receiver autonomous integrity monitoring flag
623 - DTE(uint): Data terminal ready
624 - Spare(uint): Not used. Should be set to zero (field automatically set to "0")
625 @param params: Dictionary of field names/values.
626 @param out: File like object to write to
627 @rtype: stdout
628 @return: text to out
629 '''
630
631 if 'std'==format:
632 out.write("b_pos_and_shipdata_broken:\n")
633 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
634 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
635 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
636 if 'Reserved1' in params: out.write(" Reserved1: "+str(params['Reserved1'])+"\n")
637 if 'SOG' in params: out.write(" SOG: "+str(params['SOG'])+"\n")
638 if 'PositionAccuracy' in params: out.write(" PositionAccuracy: "+str(params['PositionAccuracy'])+"\n")
639 if 'longitude' in params: out.write(" longitude: "+str(params['longitude'])+"\n")
640 if 'latitude' in params: out.write(" latitude: "+str(params['latitude'])+"\n")
641 if 'COG' in params: out.write(" COG: "+str(params['COG'])+"\n")
642 if 'TrueHeading' in params: out.write(" TrueHeading: "+str(params['TrueHeading'])+"\n")
643 if 'TimeStamp' in params: out.write(" TimeStamp: "+str(params['TimeStamp'])+"\n")
644 if 'Reserved2' in params: out.write(" Reserved2: "+str(params['Reserved2'])+"\n")
645 if 'name' in params: out.write(" name: "+str(params['name'])+"\n")
646 if 'shipandcargo' in params: out.write(" shipandcargo: "+str(params['shipandcargo'])+"\n")
647 if 'dimA' in params: out.write(" dimA: "+str(params['dimA'])+"\n")
648 if 'dimB' in params: out.write(" dimB: "+str(params['dimB'])+"\n")
649 if 'dimC' in params: out.write(" dimC: "+str(params['dimC'])+"\n")
650 if 'dimD' in params: out.write(" dimD: "+str(params['dimD'])+"\n")
651 if 'fixtype' in params: out.write(" fixtype: "+str(params['fixtype'])+"\n")
652 if 'RAIM' in params: out.write(" RAIM: "+str(params['RAIM'])+"\n")
653 if 'DTE' in params: out.write(" DTE: "+str(params['DTE'])+"\n")
654 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
655 elif 'csv'==format:
656 if None == options.fieldList:
657 options.fieldList = fieldList
658 needComma = False;
659 for field in fieldList:
660 if needComma: out.write(',')
661 needComma = True
662 if field in params:
663 out.write(str(params[field]))
664
665 out.write("\n")
666 elif 'html'==format:
667 printHtml(params,out)
668 elif 'sql'==format:
669 sqlInsertStr(params,out,dbType=dbType)
670 elif 'kml'==format:
671 printKml(params,out)
672 elif 'kml-full'==format:
673 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
674 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
675 out.write("<Document>\n")
676 out.write(" <name>b_pos_and_shipdata_broken</name>\n")
677 printKml(params,out)
678 out.write("</Document>\n")
679 out.write("</kml>\n")
680 else:
681 print "ERROR: unknown format:",format
682 assert False
683
684 return
685
686 RepeatIndicatorEncodeLut = {
687 'default':'0',
688 'do not repeat any more':'3',
689 }
690
691 RepeatIndicatorDecodeLut = {
692 '0':'default',
693 '3':'do not repeat any more',
694 }
695
696 SOGEncodeLut = {
697 '102.2 knots or higher':'102.2',
698 }
699
700 SOGDecodeLut = {
701 '102.2':'102.2 knots or higher',
702 }
703
704 PositionAccuracyEncodeLut = {
705 'low (greater than 10 m)':'0',
706 'high (less than 10 m)':'1',
707 }
708
709 PositionAccuracyDecodeLut = {
710 '0':'low (greater than 10 m)',
711 '1':'high (less than 10 m)',
712 }
713
714 TimeStampEncodeLut = {
715 'not available/default':'60',
716 'manual input':'61',
717 'dead reckoning':'62',
718 'inoperative':'63',
719 }
720
721 TimeStampDecodeLut = {
722 '60':'not available/default',
723 '61':'manual input',
724 '62':'dead reckoning',
725 '63':'inoperative',
726 }
727
728 shipandcargoEncodeLut = {
729 'Wing in ground (WIG), all ships of this type':'20',
730 'Wing in ground (WIG), Hazardous catagory A':'21',
731 'Wing in ground (WIG), Hazardous catagory B':'22',
732 'Wing in ground (WIG), Hazardous catagory C':'23',
733 'Wing in ground (WIG), Hazardous catagory D':'24',
734 'Wing in ground (WIG), Reserved for future use':'25',
735 'Wing in ground (WIG), Reserved for future use':'26',
736 'Wing in ground (WIG), Reserved for future use':'27',
737 'Wing in ground (WIG), Reserved for future use':'28',
738 'Wing in ground (WIG), No additional information':'29',
739 'fishing':'30',
740 'towing':'31',
741 'towing length exceeds 200m or breadth exceeds 25m':'32',
742 'dredging or underwater ops':'33',
743 'diving ops':'34',
744 'military ops':'35',
745 'sailing':'36',
746 'pleasure craft':'37',
747 'reserved':'38',
748 'reserved':'39',
749 'High speed craft (HSC), all ships of this type':'40',
750 'High speed craft (HSC), Hazardous catagory A':'41',
751 'High speed craft (HSC), Hazardous catagory B':'42',
752 'High speed craft (HSC), Hazardous catagory C':'43',
753 'High speed craft (HSC), Hazardous catagory D':'44',
754 'High speed craft (HSC), Reserved for future use':'45',
755 'High speed craft (HSC), Reserved for future use':'46',
756 'High speed craft (HSC), Reserved for future use':'47',
757 'High speed craft (HSC), Reserved for future use':'48',
758 'High speed craft (HSC), No additional information':'49',
759 'pilot vessel':'50',
760 'search and rescue vessel':'51',
761 'tug':'52',
762 'port tender':'53',
763 'anti-polution equipment':'54',
764 'law enforcement':'55',
765 'spare - local vessel':'56',
766 'spare - local vessel':'57',
767 'medical transport':'58',
768 'ship according to RR Resolution No. 18':'59',
769 'passenger, all ships of this type':'60',
770 'passenger, Hazardous catagory A':'61',
771 'passenger, Hazardous catagory B':'62',
772 'passenger, Hazardous catagory C':'63',
773 'passenger, Hazardous catagory D':'64',
774 'passenger, Reserved for future use':'65',
775 'passenger, Reserved for future use':'66',
776 'passenger, Reserved for future use':'67',
777 'passenger, Reserved for future use':'68',
778 'passenger, No additional information':'69',
779 'cargo, all ships of this type':'70',
780 'cargo, Hazardous catagory A':'71',
781 'cargo, Hazardous catagory B':'72',
782 'cargo, Hazardous catagory C':'73',
783 'cargo, Hazardous catagory D':'74',
784 'cargo, Reserved for future use':'75',
785 'cargo, Reserved for future use':'76',
786 'cargo, Reserved for future use':'77',
787 'cargo, Reserved for future use':'78',
788 'cargo, No additional information':'79',
789 'tanker, all ships of this type':'80',
790 'tanker, Hazardous catagory A':'81',
791 'tanker, Hazardous catagory B':'82',
792 'tanker, Hazardous catagory C':'83',
793 'tanker, Hazardous catagory D':'84',
794 'tanker, Reserved for future use':'85',
795 'tanker, Reserved for future use':'86',
796 'tanker, Reserved for future use':'87',
797 'tanker, Reserved for future use':'88',
798 'tanker, No additional information':'89',
799 'other type, all ships of this type':'90',
800 'other type, Hazardous catagory A':'91',
801 'other type, Hazardous catagory B':'92',
802 'other type, Hazardous catagory C':'93',
803 'other type, Hazardous catagory D':'94',
804 'other type, Reserved for future use':'95',
805 'other type, Reserved for future use':'96',
806 'other type, Reserved for future use':'97',
807 'other type, Reserved for future use':'98',
808 'other type, No additional information':'99',
809 }
810
811 shipandcargoDecodeLut = {
812 '20':'Wing in ground (WIG), all ships of this type',
813 '21':'Wing in ground (WIG), Hazardous catagory A',
814 '22':'Wing in ground (WIG), Hazardous catagory B',
815 '23':'Wing in ground (WIG), Hazardous catagory C',
816 '24':'Wing in ground (WIG), Hazardous catagory D',
817 '25':'Wing in ground (WIG), Reserved for future use',
818 '26':'Wing in ground (WIG), Reserved for future use',
819 '27':'Wing in ground (WIG), Reserved for future use',
820 '28':'Wing in ground (WIG), Reserved for future use',
821 '29':'Wing in ground (WIG), No additional information',
822 '30':'fishing',
823 '31':'towing',
824 '32':'towing length exceeds 200m or breadth exceeds 25m',
825 '33':'dredging or underwater ops',
826 '34':'diving ops',
827 '35':'military ops',
828 '36':'sailing',
829 '37':'pleasure craft',
830 '38':'reserved',
831 '39':'reserved',
832 '40':'High speed craft (HSC), all ships of this type',
833 '41':'High speed craft (HSC), Hazardous catagory A',
834 '42':'High speed craft (HSC), Hazardous catagory B',
835 '43':'High speed craft (HSC), Hazardous catagory C',
836 '44':'High speed craft (HSC), Hazardous catagory D',
837 '45':'High speed craft (HSC), Reserved for future use',
838 '46':'High speed craft (HSC), Reserved for future use',
839 '47':'High speed craft (HSC), Reserved for future use',
840 '48':'High speed craft (HSC), Reserved for future use',
841 '49':'High speed craft (HSC), No additional information',
842 '50':'pilot vessel',
843 '51':'search and rescue vessel',
844 '52':'tug',
845 '53':'port tender',
846 '54':'anti-polution equipment',
847 '55':'law enforcement',
848 '56':'spare - local vessel',
849 '57':'spare - local vessel',
850 '58':'medical transport',
851 '59':'ship according to RR Resolution No. 18',
852 '60':'passenger, all ships of this type',
853 '61':'passenger, Hazardous catagory A',
854 '62':'passenger, Hazardous catagory B',
855 '63':'passenger, Hazardous catagory C',
856 '64':'passenger, Hazardous catagory D',
857 '65':'passenger, Reserved for future use',
858 '66':'passenger, Reserved for future use',
859 '67':'passenger, Reserved for future use',
860 '68':'passenger, Reserved for future use',
861 '69':'passenger, No additional information',
862 '70':'cargo, all ships of this type',
863 '71':'cargo, Hazardous catagory A',
864 '72':'cargo, Hazardous catagory B',
865 '73':'cargo, Hazardous catagory C',
866 '74':'cargo, Hazardous catagory D',
867 '75':'cargo, Reserved for future use',
868 '76':'cargo, Reserved for future use',
869 '77':'cargo, Reserved for future use',
870 '78':'cargo, Reserved for future use',
871 '79':'cargo, No additional information',
872 '80':'tanker, all ships of this type',
873 '81':'tanker, Hazardous catagory A',
874 '82':'tanker, Hazardous catagory B',
875 '83':'tanker, Hazardous catagory C',
876 '84':'tanker, Hazardous catagory D',
877 '85':'tanker, Reserved for future use',
878 '86':'tanker, Reserved for future use',
879 '87':'tanker, Reserved for future use',
880 '88':'tanker, Reserved for future use',
881 '89':'tanker, No additional information',
882 '90':'other type, all ships of this type',
883 '91':'other type, Hazardous catagory A',
884 '92':'other type, Hazardous catagory B',
885 '93':'other type, Hazardous catagory C',
886 '94':'other type, Hazardous catagory D',
887 '95':'other type, Reserved for future use',
888 '96':'other type, Reserved for future use',
889 '97':'other type, Reserved for future use',
890 '98':'other type, Reserved for future use',
891 '99':'other type, No additional information',
892 }
893
894 dimCEncodeLut = {
895 '63 m or greater':'63',
896 }
897
898 dimCDecodeLut = {
899 '63':'63 m or greater',
900 }
901
902 dimDEncodeLut = {
903 '63 m or greater':'63',
904 }
905
906 dimDDecodeLut = {
907 '63':'63 m or greater',
908 }
909
910 fixtypeEncodeLut = {
911 'undefined':'0',
912 'GPS':'1',
913 'GLONASS':'2',
914 'combined GPS/GLONASS':'3',
915 'Loran-C':'4',
916 'Chayka':'5',
917 'integrated navigation system':'6',
918 'surveyed':'7',
919 }
920
921 fixtypeDecodeLut = {
922 '0':'undefined',
923 '1':'GPS',
924 '2':'GLONASS',
925 '3':'combined GPS/GLONASS',
926 '4':'Loran-C',
927 '5':'Chayka',
928 '6':'integrated navigation system',
929 '7':'surveyed',
930 }
931
932 RAIMEncodeLut = {
933 'not in use':'False',
934 'in use':'True',
935 }
936
937 RAIMDecodeLut = {
938 'False':'not in use',
939 'True':'in use',
940 }
941
942 DTEEncodeLut = {
943 'available':'0',
944 'not available':'1',
945 }
946
947 DTEDecodeLut = {
948 '0':'available',
949 '1':'not available',
950 }
951
952
953
954
955
956 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
957 ,addCoastGuardFields=True
958 ,dbType='postgres'
959 ):
960 '''
961 Return the SQL CREATE command for this message type
962 @param outfile: file like object to print to.
963 @param fields: which fields to put in the create. Defaults to all.
964 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
965 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
966 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
967 @type addCoastGuardFields: bool
968 @return: sql create string
969 @rtype: str
970
971 @see: sqlCreate
972 '''
973
974 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
975
976 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
977 '''
978 Return the sqlhelp object to create the table.
979
980 @param fields: which fields to put in the create. Defaults to all.
981 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
982 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
983 @type addCoastGuardFields: bool
984 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
985 @return: An object that can be used to generate a return
986 @rtype: sqlhelp.create
987 '''
988 if None == fields: fields = fieldList
989 import sqlhelp
990 c = sqlhelp.create('b_pos_and_shipdata_broken',dbType=dbType)
991 c.addPrimaryKey()
992 if 'MessageID' in fields: c.addInt ('MessageID')
993 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
994 if 'UserID' in fields: c.addInt ('UserID')
995 if 'Reserved1' in fields: c.addInt ('Reserved1')
996 if 'SOG' in fields: c.addDecimal('SOG',4,1)
997 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy')
998 if dbType != 'postgres':
999 if 'longitude' in fields: c.addDecimal('longitude',8,5)
1000 if dbType != 'postgres':
1001 if 'latitude' in fields: c.addDecimal('latitude',8,5)
1002 if 'COG' in fields: c.addDecimal('COG',4,1)
1003 if 'TrueHeading' in fields: c.addInt ('TrueHeading')
1004 if 'TimeStamp' in fields: c.addInt ('TimeStamp')
1005 if 'Reserved2' in fields: c.addInt ('Reserved2')
1006 if 'name' in fields: c.addVarChar('name',20)
1007 if 'shipandcargo' in fields: c.addInt ('shipandcargo')
1008 if 'dimA' in fields: c.addInt ('dimA')
1009 if 'dimB' in fields: c.addInt ('dimB')
1010 if 'dimC' in fields: c.addInt ('dimC')
1011 if 'dimD' in fields: c.addInt ('dimD')
1012 if 'fixtype' in fields: c.addInt ('fixtype')
1013 if 'RAIM' in fields: c.addBool('RAIM')
1014 if 'DTE' in fields: c.addInt ('DTE')
1015 if 'Spare' in fields: c.addInt ('Spare')
1016
1017 if addCoastGuardFields:
1018
1019
1020
1021
1022
1023 c.addVarChar('cg_r',15)
1024 c.addInt('cg_sec')
1025
1026 c.addTimestamp('cg_timestamp')
1027
1028 if dbType == 'postgres':
1029
1030
1031 c.addPostGIS('Position','POINT',2,SRID=4326);
1032
1033 return c
1034
1035 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
1036 '''
1037 Return the SQL INSERT command for this message type
1038 @param params: dictionary of values keyed by field name
1039 @param outfile: file like object to print to.
1040 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
1041 @return: sql create string
1042 @rtype: str
1043
1044 @see: sqlCreate
1045 '''
1046 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
1047
1048
1049 -def sqlInsert(params,extraParams=None,dbType='postgres'):
1050 '''
1051 Give the SQL INSERT statement
1052 @param params: dict keyed by field name of values
1053 @param extraParams: any extra fields that you have created beyond the normal ais message fields
1054 @rtype: sqlhelp.insert
1055 @return: insert class instance
1056 @todo: allow optional type checking of params?
1057 @warning: this will take invalid keys happily and do what???
1058 '''
1059 import sqlhelp
1060 i = sqlhelp.insert('b_pos_and_shipdata_broken',dbType=dbType)
1061
1062 if dbType=='postgres':
1063 finished = []
1064 for key in params:
1065 if key in finished:
1066 continue
1067
1068 if key not in toPgFields and key not in fromPgFields:
1069 if type(params[key])==Decimal: i.add(key,float(params[key]))
1070 else: i.add(key,params[key])
1071 else:
1072 if key in fromPgFields:
1073 val = params[key]
1074
1075 i.addPostGIS(key,val)
1076 finished.append(key)
1077 else:
1078
1079 pgName = toPgFields[key]
1080
1081 valStr=pgTypes[pgName]+'('
1082 vals = []
1083 for nonPgKey in fromPgFields[pgName]:
1084 vals.append(str(params[nonPgKey]))
1085 finished.append(nonPgKey)
1086 valStr+=' '.join(vals)+')'
1087 i.addPostGIS(pgName,valStr)
1088 else:
1089 for key in params:
1090 if type(params[key])==Decimal: i.add(key,float(params[key]))
1091 else: i.add(key,params[key])
1092
1093 if None != extraParams:
1094 for key in extraParams:
1095 i.add(key,extraParams[key])
1096
1097 return i
1098
1099
1100
1101
1102
1105 '''
1106 Return the LaTeX definition table for this message type
1107 @param outfile: file like object to print to.
1108 @type outfile: file obj
1109 @return: LaTeX table string via the outfile
1110 @rtype: str
1111
1112 '''
1113 o = outfile
1114
1115 o.write('''
1116 \\begin{table}%[htb]
1117 \\centering
1118 \\begin{tabular}{|l|c|l|}
1119 \\hline
1120 Parameter & Number of bits & Description
1121 \\\\ \\hline\\hline
1122 MessageID & 6 & AIS message number. Must be 19 \\\\ \hline
1123 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
1124 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
1125 Reserved1 & 8 & Reseverd for definition by a compentent regional or local authority. Should be set to zero. \\\\ \hline
1126 SOG & 10 & Speed over ground \\\\ \hline
1127 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline
1128 longitude & 28 & Location of the vessel East West location \\\\ \hline
1129 latitude & 27 & Location of the vessel North South location \\\\ \hline
1130 COG & 12 & Course over ground \\\\ \hline
1131 TrueHeading & 9 & True heading (relative to true North) \\\\ \hline
1132 TimeStamp & 6 & UTC second when the report was generated \\\\ \hline
1133 Reserved2 & 4 & Reseverd for definition by a compentent regional authority. \\\\ \hline
1134 name & 120 & Vessel name \\\\ \hline
1135 shipandcargo & 8 & Type of ship and cargo type \\\\ \hline
1136 dimA & 9 & Distance from bow to reference position \\\\ \hline
1137 dimB & 9 & Distance from reference position to stern \\\\ \hline
1138 dimC & 6 & Distance from port side to reference position \\\\ \hline
1139 dimD & 6 & Distance from reference position to starboard side \\\\ \hline
1140 fixtype & 4 & Method used for positioning \\\\ \hline
1141 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline
1142 DTE & 1 & Data terminal ready \\\\ \hline
1143 Spare & 5 & Not used. Should be set to zero\\\\ \\hline \\hline
1144 Total bits & 312 & Appears to take 2 slots with 112 pad bits to fill the last slot \\\\ \\hline
1145 \\end{tabular}
1146 \\caption{AIS message number 19: Extended Class B equipment position report - NOT WORKING IN NOAADATA}
1147 \\label{tab:b_pos_and_shipdata_broken}
1148 \\end{table}
1149 ''')
1150
1151
1152
1153
1154
1155 -def textDefinitionTable(outfile=sys.stdout
1156 ,delim='\t'
1157 ):
1158 '''
1159 Return the text definition table for this message type
1160 @param outfile: file like object to print to.
1161 @type outfile: file obj
1162 @return: text table string via the outfile
1163 @rtype: str
1164
1165 '''
1166 o = outfile
1167 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
1168 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 19
1169 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
1170 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
1171 Reserved1'''+delim+'''8'''+delim+'''Reseverd for definition by a compentent regional or local authority. Should be set to zero.
1172 SOG'''+delim+'''10'''+delim+'''Speed over ground
1173 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes
1174 longitude'''+delim+'''28'''+delim+'''Location of the vessel East West location
1175 latitude'''+delim+'''27'''+delim+'''Location of the vessel North South location
1176 COG'''+delim+'''12'''+delim+'''Course over ground
1177 TrueHeading'''+delim+'''9'''+delim+'''True heading (relative to true North)
1178 TimeStamp'''+delim+'''6'''+delim+'''UTC second when the report was generated
1179 Reserved2'''+delim+'''4'''+delim+'''Reseverd for definition by a compentent regional authority.
1180 name'''+delim+'''120'''+delim+'''Vessel name
1181 shipandcargo'''+delim+'''8'''+delim+'''Type of ship and cargo type
1182 dimA'''+delim+'''9'''+delim+'''Distance from bow to reference position
1183 dimB'''+delim+'''9'''+delim+'''Distance from reference position to stern
1184 dimC'''+delim+'''6'''+delim+'''Distance from port side to reference position
1185 dimD'''+delim+'''6'''+delim+'''Distance from reference position to starboard side
1186 fixtype'''+delim+'''4'''+delim+'''Method used for positioning
1187 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag
1188 DTE'''+delim+'''1'''+delim+'''Data terminal ready
1189 Spare'''+delim+'''5'''+delim+'''Not used. Should be set to zero
1190 Total bits'''+delim+'''312'''+delim+'''Appears to take 2 slots with 112 pad bits to fill the last slot''')
1191
1192
1193
1194
1195
1196 import unittest
1198 '''Return a params file base on the testvalue tags.
1199 @rtype: dict
1200 @return: params based on testvalue tags
1201 '''
1202 params = {}
1203 params['MessageID'] = 19
1204 params['RepeatIndicator'] = 1
1205 params['UserID'] = 1193046
1206 params['Reserved1'] = 0
1207 params['SOG'] = Decimal('101.9')
1208 params['PositionAccuracy'] = 1
1209 params['longitude'] = Decimal('-122.16328055555556')
1210 params['latitude'] = Decimal('37.424458333333334')
1211 params['COG'] = Decimal('34.5')
1212 params['TrueHeading'] = 41
1213 params['TimeStamp'] = 35
1214 params['Reserved2'] = 0
1215 params['name'] = 'BLACK PEARL@@@@@@@@@'
1216 params['shipandcargo'] = 55
1217 params['dimA'] = 10
1218 params['dimB'] = 11
1219 params['dimC'] = 12
1220 params['dimD'] = 13
1221 params['fixtype'] = 1
1222 params['RAIM'] = False
1223 params['DTE'] = 0
1224 params['Spare'] = 0
1225
1226 return params
1227
1229 '''Use testvalue tag text from each type to build test case the b_pos_and_shipdata_broken message'''
1231
1232 params = testParams()
1233 bits = encode(params)
1234 r = decode(bits)
1235
1236
1237 self.failUnlessEqual(r['MessageID'],params['MessageID'])
1238 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
1239 self.failUnlessEqual(r['UserID'],params['UserID'])
1240 self.failUnlessEqual(r['Reserved1'],params['Reserved1'])
1241 self.failUnlessAlmostEqual(r['SOG'],params['SOG'],1)
1242 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy'])
1243 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
1244 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
1245 self.failUnlessAlmostEqual(r['COG'],params['COG'],1)
1246 self.failUnlessEqual(r['TrueHeading'],params['TrueHeading'])
1247 self.failUnlessEqual(r['TimeStamp'],params['TimeStamp'])
1248 self.failUnlessEqual(r['Reserved2'],params['Reserved2'])
1249 self.failUnlessEqual(r['name'],params['name'])
1250 self.failUnlessEqual(r['shipandcargo'],params['shipandcargo'])
1251 self.failUnlessEqual(r['dimA'],params['dimA'])
1252 self.failUnlessEqual(r['dimB'],params['dimB'])
1253 self.failUnlessEqual(r['dimC'],params['dimC'])
1254 self.failUnlessEqual(r['dimD'],params['dimD'])
1255 self.failUnlessEqual(r['fixtype'],params['fixtype'])
1256 self.failUnlessEqual(r['RAIM'],params['RAIM'])
1257 self.failUnlessEqual(r['DTE'],params['DTE'])
1258 self.failUnlessEqual(r['Spare'],params['Spare'])
1259
1261 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
1262 help='decode a "b_pos_and_shipdata_broken" AIS message')
1263 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
1264 help='encode a "b_pos_and_shipdata_broken" AIS message')
1265 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
1266 ,help='Field parameter value [default: %default]')
1267 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
1268 ,help='Field parameter value [default: %default]')
1269 parser.add_option('--SOG-field', dest='SOGField',default=Decimal('102.3'),metavar='udecimal',type='string'
1270 ,help='Field parameter value [default: %default]')
1271 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int'
1272 ,help='Field parameter value [default: %default]')
1273 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
1274 ,help='Field parameter value [default: %default]')
1275 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
1276 ,help='Field parameter value [default: %default]')
1277 parser.add_option('--COG-field', dest='COGField',default=Decimal('360'),metavar='udecimal',type='string'
1278 ,help='Field parameter value [default: %default]')
1279 parser.add_option('--TrueHeading-field', dest='TrueHeadingField',default=511,metavar='uint',type='int'
1280 ,help='Field parameter value [default: %default]')
1281 parser.add_option('--TimeStamp-field', dest='TimeStampField',default=60,metavar='uint',type='int'
1282 ,help='Field parameter value [default: %default]')
1283 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string'
1284 ,help='Field parameter value [default: %default]')
1285 parser.add_option('--shipandcargo-field', dest='shipandcargoField',default=0,metavar='uint',type='int'
1286 ,help='Field parameter value [default: %default]')
1287 parser.add_option('--dimA-field', dest='dimAField',default=0,metavar='uint',type='int'
1288 ,help='Field parameter value [default: %default]')
1289 parser.add_option('--dimB-field', dest='dimBField',default=0,metavar='uint',type='int'
1290 ,help='Field parameter value [default: %default]')
1291 parser.add_option('--dimC-field', dest='dimCField',default=0,metavar='uint',type='int'
1292 ,help='Field parameter value [default: %default]')
1293 parser.add_option('--dimD-field', dest='dimDField',default=0,metavar='uint',type='int'
1294 ,help='Field parameter value [default: %default]')
1295 parser.add_option('--fixtype-field', dest='fixtypeField',default=0,metavar='uint',type='int'
1296 ,help='Field parameter value [default: %default]')
1297 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int'
1298 ,help='Field parameter value [default: %default]')
1299 parser.add_option('--DTE-field', dest='DTEField',metavar='uint',type='int'
1300 ,help='Field parameter value [default: %default]')
1301
1302
1303 if __name__=='__main__':
1304
1305 from optparse import OptionParser
1306 parser = OptionParser(usage="%prog [options]",
1307 version="%prog "+__version__)
1308
1309 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
1310 help='run the documentation tests')
1311 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
1312 help='run the unit tests')
1313 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
1314 help='Make the test output verbose')
1315
1316
1317
1318 typeChoices = ('binary','nmeapayload','nmea')
1319 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
1320 ,default='nmeapayload'
1321 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
1322
1323
1324 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
1325 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
1326 ,default='std'
1327 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
1328
1329 parser.add_option('-o','--output',dest='outputFileName',default=None,
1330 help='Name of the python file to write [default: stdout]')
1331
1332 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
1333 choices=fieldList,
1334 help='Which fields to include in the output. Currently only for csv output [default: all]')
1335
1336 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
1337 help='Print the field name for csv')
1338
1339 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
1340 help='Print out an sql create command for the table.')
1341
1342 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
1343 help='Print a LaTeX table of the type')
1344
1345 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
1346 help='Print delimited table of the type (for Word table importing)')
1347 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
1348 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
1349
1350
1351 dbChoices = ('sqlite','postgres')
1352 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
1353 ,choices=dbChoices,type='choice'
1354 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
1355
1356 addMsgOptions(parser)
1357
1358 (options,args) = parser.parse_args()
1359 success=True
1360
1361 if options.doctest:
1362 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
1363 sys.argv= [sys.argv[0]]
1364 if options.verbose: sys.argv.append('-v')
1365 import doctest
1366 numfail,numtests=doctest.testmod()
1367 if numfail==0: print 'ok'
1368 else:
1369 print 'FAILED'
1370 success=False
1371
1372 if not success: sys.exit('Something Failed')
1373 del success
1374
1375 if options.unittest:
1376 sys.argv = [sys.argv[0]]
1377 if options.verbose: sys.argv.append('-v')
1378 unittest.main()
1379
1380 outfile = sys.stdout
1381 if None!=options.outputFileName:
1382 outfile = file(options.outputFileName,'w')
1383
1384
1385 if options.doEncode:
1386
1387 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1388 if None==options.UserIDField: parser.error("missing value for UserIDField")
1389 if None==options.SOGField: parser.error("missing value for SOGField")
1390 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField")
1391 if None==options.longitudeField: parser.error("missing value for longitudeField")
1392 if None==options.latitudeField: parser.error("missing value for latitudeField")
1393 if None==options.COGField: parser.error("missing value for COGField")
1394 if None==options.TrueHeadingField: parser.error("missing value for TrueHeadingField")
1395 if None==options.TimeStampField: parser.error("missing value for TimeStampField")
1396 if None==options.nameField: parser.error("missing value for nameField")
1397 if None==options.shipandcargoField: parser.error("missing value for shipandcargoField")
1398 if None==options.dimAField: parser.error("missing value for dimAField")
1399 if None==options.dimBField: parser.error("missing value for dimBField")
1400 if None==options.dimCField: parser.error("missing value for dimCField")
1401 if None==options.dimDField: parser.error("missing value for dimDField")
1402 if None==options.fixtypeField: parser.error("missing value for fixtypeField")
1403 if None==options.RAIMField: parser.error("missing value for RAIMField")
1404 if None==options.DTEField: parser.error("missing value for DTEField")
1405 msgDict={
1406 'MessageID': '19',
1407 'RepeatIndicator': options.RepeatIndicatorField,
1408 'UserID': options.UserIDField,
1409 'Reserved1': '0',
1410 'SOG': options.SOGField,
1411 'PositionAccuracy': options.PositionAccuracyField,
1412 'longitude': options.longitudeField,
1413 'latitude': options.latitudeField,
1414 'COG': options.COGField,
1415 'TrueHeading': options.TrueHeadingField,
1416 'TimeStamp': options.TimeStampField,
1417 'Reserved2': '0',
1418 'name': options.nameField,
1419 'shipandcargo': options.shipandcargoField,
1420 'dimA': options.dimAField,
1421 'dimB': options.dimBField,
1422 'dimC': options.dimCField,
1423 'dimD': options.dimDField,
1424 'fixtype': options.fixtypeField,
1425 'RAIM': options.RAIMField,
1426 'DTE': options.DTEField,
1427 'Spare': '0',
1428 }
1429
1430 bits = encode(msgDict)
1431 if 'binary'==options.ioType: print str(bits)
1432 elif 'nmeapayload'==options.ioType:
1433
1434 print "bitLen",len(bits)
1435 bitLen=len(bits)
1436 if bitLen%6!=0:
1437 bits = bits + BitVector(size=(6 - (bitLen%6)))
1438 print "result:",binary.bitvectoais6(bits)[0]
1439
1440
1441
1442 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1443 else: sys.exit('ERROR: unknown ioType. Help!')
1444
1445
1446 if options.sqlCreate:
1447 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1448
1449 if options.latexDefinitionTable:
1450 latexDefinitionTable(outfile)
1451
1452
1453 if options.textDefinitionTable:
1454 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1455
1456 if options.printCsvfieldList:
1457
1458 if None == options.fieldList: options.fieldList = fieldList
1459 import StringIO
1460 buf = StringIO.StringIO()
1461 for field in options.fieldList:
1462 buf.write(field+',')
1463 result = buf.getvalue()
1464 if result[-1] == ',': print result[:-1]
1465 else: print result
1466
1467 if options.doDecode:
1468 if len(args)==0: args = sys.stdin
1469 for msg in args:
1470 bv = None
1471
1472 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1473
1474
1475 bv = binary.ais6tobitvec(msg.split(',')[5])
1476 else:
1477
1478 binaryMsg=True
1479 for c in msg:
1480 if c not in ('0','1'):
1481 binaryMsg=False
1482 break
1483 if binaryMsg:
1484 bv = BitVector(bitstring=msg)
1485 else:
1486 bv = binary.ais6tobitvec(msg)
1487
1488 printFields(decode(bv)
1489 ,out=outfile
1490 ,format=options.outputType
1491 ,fieldList=options.fieldList
1492 ,dbType=options.dbType
1493 )
1494