1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2008-01-09 $'.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 'Spare',
54 'SOG',
55 'PositionAccuracy',
56 'longitude',
57 'latitude',
58 'COG',
59 'TrueHeading',
60 'TimeStamp',
61 'Spare2',
62 'name',
63 'shipandcargo',
64 'dimA',
65 'dimB',
66 'dimC',
67 'dimD',
68 'fixtype',
69 'RAIM',
70 'DTE',
71 'Spare3',
72 )
73
74 fieldListPostgres = (
75 'MessageID',
76 'RepeatIndicator',
77 'UserID',
78 'Spare',
79 'SOG',
80 'PositionAccuracy',
81 'Position',
82 'COG',
83 'TrueHeading',
84 'TimeStamp',
85 'Spare2',
86 'name',
87 'shipandcargo',
88 'dimA',
89 'dimB',
90 'dimC',
91 'dimD',
92 'fixtype',
93 'RAIM',
94 'DTE',
95 'Spare3',
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 - Spare(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 - Spare2(uint): Not used. Should be set to zero. Researched for future use. (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 - Spare3(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 - Spare(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 - Spare2(uint): Not used. Should be set to zero. Researched for future use. (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 - Spare3(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['Spare']=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['Spare2']=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['Spare3']=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>Spare</td>\n")
389 out.write("<td>uint</td>\n")
390 if 'Spare' in params:
391 out.write(" <td>"+str(params['Spare'])+"</td>\n")
392 out.write(" <td>"+str(params['Spare'])+"</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>Spare2</td>\n")
468 out.write("<td>uint</td>\n")
469 if 'Spare2' in params:
470 out.write(" <td>"+str(params['Spare2'])+"</td>\n")
471 out.write(" <td>"+str(params['Spare2'])+"</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>Spare3</td>\n")
570 out.write("<td>uint</td>\n")
571 if 'Spare3' in params:
572 out.write(" <td>"+str(params['Spare3'])+"</td>\n")
573 out.write(" <td>"+str(params['Spare3'])+"</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 - Spare(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 - Spare2(uint): Not used. Should be set to zero. Researched for future use. (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 - Spare3(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 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\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 'Spare2' in params: out.write(" Spare2: "+str(params['Spare2'])+"\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 'Spare3' in params: out.write(" Spare3: "+str(params['Spare3'])+"\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 dbTableName='b_pos_and_shipdata_broken'
957 'Database table name'
958
959 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
960 ,addCoastGuardFields=True
961 ,dbType='postgres'
962 ):
963 '''
964 Return the SQL CREATE command for this message type
965 @param outfile: file like object to print to.
966 @param fields: which fields to put in the create. Defaults to all.
967 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
968 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
969 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
970 @type addCoastGuardFields: bool
971 @return: sql create string
972 @rtype: str
973
974 @see: sqlCreate
975 '''
976
977 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
978
979 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
980 '''
981 Return the sqlhelp object to create the table.
982
983 @param fields: which fields to put in the create. Defaults to all.
984 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
985 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
986 @type addCoastGuardFields: bool
987 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
988 @return: An object that can be used to generate a return
989 @rtype: sqlhelp.create
990 '''
991 if None == fields: fields = fieldList
992 import sqlhelp
993 c = sqlhelp.create('b_pos_and_shipdata_broken',dbType=dbType)
994 c.addPrimaryKey()
995 if 'MessageID' in fields: c.addInt ('MessageID')
996 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
997 if 'UserID' in fields: c.addInt ('UserID')
998 if 'Spare' in fields: c.addInt ('Spare')
999 if 'SOG' in fields: c.addDecimal('SOG',4,1)
1000 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy')
1001 if dbType != 'postgres':
1002 if 'longitude' in fields: c.addDecimal('longitude',8,5)
1003 if dbType != 'postgres':
1004 if 'latitude' in fields: c.addDecimal('latitude',8,5)
1005 if 'COG' in fields: c.addDecimal('COG',4,1)
1006 if 'TrueHeading' in fields: c.addInt ('TrueHeading')
1007 if 'TimeStamp' in fields: c.addInt ('TimeStamp')
1008 if 'Spare2' in fields: c.addInt ('Spare2')
1009 if 'name' in fields: c.addVarChar('name',20)
1010 if 'shipandcargo' in fields: c.addInt ('shipandcargo')
1011 if 'dimA' in fields: c.addInt ('dimA')
1012 if 'dimB' in fields: c.addInt ('dimB')
1013 if 'dimC' in fields: c.addInt ('dimC')
1014 if 'dimD' in fields: c.addInt ('dimD')
1015 if 'fixtype' in fields: c.addInt ('fixtype')
1016 if 'RAIM' in fields: c.addBool('RAIM')
1017 if 'DTE' in fields: c.addInt ('DTE')
1018 if 'Spare3' in fields: c.addInt ('Spare3')
1019
1020 if addCoastGuardFields:
1021
1022
1023
1024
1025
1026 c.addVarChar('cg_r',15)
1027 c.addInt('cg_sec')
1028
1029 c.addTimestamp('cg_timestamp')
1030
1031 if dbType == 'postgres':
1032
1033
1034 c.addPostGIS('Position','POINT',2,SRID=4326);
1035
1036 return c
1037
1038 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
1039 '''
1040 Return the SQL INSERT command for this message type
1041 @param params: dictionary of values keyed by field name
1042 @param outfile: file like object to print to.
1043 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
1044 @return: sql create string
1045 @rtype: str
1046
1047 @see: sqlCreate
1048 '''
1049 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
1050
1051
1052 -def sqlInsert(params,extraParams=None,dbType='postgres'):
1053 '''
1054 Give the SQL INSERT statement
1055 @param params: dict keyed by field name of values
1056 @param extraParams: any extra fields that you have created beyond the normal ais message fields
1057 @rtype: sqlhelp.insert
1058 @return: insert class instance
1059 @todo: allow optional type checking of params?
1060 @warning: this will take invalid keys happily and do what???
1061 '''
1062 import sqlhelp
1063 i = sqlhelp.insert('b_pos_and_shipdata_broken',dbType=dbType)
1064
1065 if dbType=='postgres':
1066 finished = []
1067 for key in params:
1068 if key in finished:
1069 continue
1070
1071 if key not in toPgFields and key not in fromPgFields:
1072 if type(params[key])==Decimal: i.add(key,float(params[key]))
1073 else: i.add(key,params[key])
1074 else:
1075 if key in fromPgFields:
1076 val = params[key]
1077
1078 i.addPostGIS(key,val)
1079 finished.append(key)
1080 else:
1081
1082 pgName = toPgFields[key]
1083
1084 valStr=pgTypes[pgName]+'('
1085 vals = []
1086 for nonPgKey in fromPgFields[pgName]:
1087 vals.append(str(params[nonPgKey]))
1088 finished.append(nonPgKey)
1089 valStr+=' '.join(vals)+')'
1090 i.addPostGIS(pgName,valStr)
1091 else:
1092 for key in params:
1093 if type(params[key])==Decimal: i.add(key,float(params[key]))
1094 else: i.add(key,params[key])
1095
1096 if None != extraParams:
1097 for key in extraParams:
1098 i.add(key,extraParams[key])
1099
1100 return i
1101
1102
1103
1104
1105
1108 '''
1109 Return the LaTeX definition table for this message type
1110 @param outfile: file like object to print to.
1111 @type outfile: file obj
1112 @return: LaTeX table string via the outfile
1113 @rtype: str
1114
1115 '''
1116 o = outfile
1117
1118 o.write('''
1119 \\begin{table}%[htb]
1120 \\centering
1121 \\begin{tabular}{|l|c|l|}
1122 \\hline
1123 Parameter & Number of bits & Description
1124 \\\\ \\hline\\hline
1125 MessageID & 6 & AIS message number. Must be 19 \\\\ \hline
1126 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
1127 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
1128 Spare & 8 & Reseverd for definition by a compentent regional or local authority. Should be set to zero. \\\\ \hline
1129 SOG & 10 & Speed over ground \\\\ \hline
1130 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline
1131 longitude & 28 & Location of the vessel East West location \\\\ \hline
1132 latitude & 27 & Location of the vessel North South location \\\\ \hline
1133 COG & 12 & Course over ground \\\\ \hline
1134 TrueHeading & 9 & True heading (relative to true North) \\\\ \hline
1135 TimeStamp & 6 & UTC second when the report was generated \\\\ \hline
1136 Spare2 & 4 & Not used. Should be set to zero. Researched for future use. \\\\ \hline
1137 name & 120 & Vessel name \\\\ \hline
1138 shipandcargo & 8 & Type of ship and cargo type \\\\ \hline
1139 dimA & 9 & Distance from bow to reference position \\\\ \hline
1140 dimB & 9 & Distance from reference position to stern \\\\ \hline
1141 dimC & 6 & Distance from port side to reference position \\\\ \hline
1142 dimD & 6 & Distance from reference position to starboard side \\\\ \hline
1143 fixtype & 4 & Method used for positioning \\\\ \hline
1144 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline
1145 DTE & 1 & Data terminal ready \\\\ \hline
1146 Spare3 & 5 & Not used. Should be set to zero\\\\ \\hline \\hline
1147 Total bits & 312 & Appears to take 2 slots with 112 pad bits to fill the last slot \\\\ \\hline
1148 \\end{tabular}
1149 \\caption{AIS message number 19: Extended Class B equipment position report - NOT WORKING IN NOAADATA}
1150 \\label{tab:b_pos_and_shipdata_broken}
1151 \\end{table}
1152 ''')
1153
1154
1155
1156
1157
1158 -def textDefinitionTable(outfile=sys.stdout
1159 ,delim='\t'
1160 ):
1161 '''
1162 Return the text definition table for this message type
1163 @param outfile: file like object to print to.
1164 @type outfile: file obj
1165 @return: text table string via the outfile
1166 @rtype: str
1167
1168 '''
1169 o = outfile
1170 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
1171 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 19
1172 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
1173 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
1174 Spare'''+delim+'''8'''+delim+'''Reseverd for definition by a compentent regional or local authority. Should be set to zero.
1175 SOG'''+delim+'''10'''+delim+'''Speed over ground
1176 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes
1177 longitude'''+delim+'''28'''+delim+'''Location of the vessel East West location
1178 latitude'''+delim+'''27'''+delim+'''Location of the vessel North South location
1179 COG'''+delim+'''12'''+delim+'''Course over ground
1180 TrueHeading'''+delim+'''9'''+delim+'''True heading (relative to true North)
1181 TimeStamp'''+delim+'''6'''+delim+'''UTC second when the report was generated
1182 Spare2'''+delim+'''4'''+delim+'''Not used. Should be set to zero. Researched for future use.
1183 name'''+delim+'''120'''+delim+'''Vessel name
1184 shipandcargo'''+delim+'''8'''+delim+'''Type of ship and cargo type
1185 dimA'''+delim+'''9'''+delim+'''Distance from bow to reference position
1186 dimB'''+delim+'''9'''+delim+'''Distance from reference position to stern
1187 dimC'''+delim+'''6'''+delim+'''Distance from port side to reference position
1188 dimD'''+delim+'''6'''+delim+'''Distance from reference position to starboard side
1189 fixtype'''+delim+'''4'''+delim+'''Method used for positioning
1190 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag
1191 DTE'''+delim+'''1'''+delim+'''Data terminal ready
1192 Spare3'''+delim+'''5'''+delim+'''Not used. Should be set to zero
1193 Total bits'''+delim+'''312'''+delim+'''Appears to take 2 slots with 112 pad bits to fill the last slot''')
1194
1195
1196
1197
1198
1199 import unittest
1201 '''Return a params file base on the testvalue tags.
1202 @rtype: dict
1203 @return: params based on testvalue tags
1204 '''
1205 params = {}
1206 params['MessageID'] = 19
1207 params['RepeatIndicator'] = 1
1208 params['UserID'] = 1193046
1209 params['Spare'] = 0
1210 params['SOG'] = Decimal('101.9')
1211 params['PositionAccuracy'] = 1
1212 params['longitude'] = Decimal('-122.16328055555556')
1213 params['latitude'] = Decimal('37.424458333333334')
1214 params['COG'] = Decimal('34.5')
1215 params['TrueHeading'] = 41
1216 params['TimeStamp'] = 35
1217 params['Spare2'] = 0
1218 params['name'] = 'BLACK PEARL@@@@@@@@@'
1219 params['shipandcargo'] = 55
1220 params['dimA'] = 10
1221 params['dimB'] = 11
1222 params['dimC'] = 12
1223 params['dimD'] = 13
1224 params['fixtype'] = 1
1225 params['RAIM'] = False
1226 params['DTE'] = 0
1227 params['Spare3'] = 0
1228
1229 return params
1230
1232 '''Use testvalue tag text from each type to build test case the b_pos_and_shipdata_broken message'''
1234
1235 params = testParams()
1236 bits = encode(params)
1237 r = decode(bits)
1238
1239
1240 self.failUnlessEqual(r['MessageID'],params['MessageID'])
1241 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
1242 self.failUnlessEqual(r['UserID'],params['UserID'])
1243 self.failUnlessEqual(r['Spare'],params['Spare'])
1244 self.failUnlessAlmostEqual(r['SOG'],params['SOG'],1)
1245 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy'])
1246 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
1247 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
1248 self.failUnlessAlmostEqual(r['COG'],params['COG'],1)
1249 self.failUnlessEqual(r['TrueHeading'],params['TrueHeading'])
1250 self.failUnlessEqual(r['TimeStamp'],params['TimeStamp'])
1251 self.failUnlessEqual(r['Spare2'],params['Spare2'])
1252 self.failUnlessEqual(r['name'],params['name'])
1253 self.failUnlessEqual(r['shipandcargo'],params['shipandcargo'])
1254 self.failUnlessEqual(r['dimA'],params['dimA'])
1255 self.failUnlessEqual(r['dimB'],params['dimB'])
1256 self.failUnlessEqual(r['dimC'],params['dimC'])
1257 self.failUnlessEqual(r['dimD'],params['dimD'])
1258 self.failUnlessEqual(r['fixtype'],params['fixtype'])
1259 self.failUnlessEqual(r['RAIM'],params['RAIM'])
1260 self.failUnlessEqual(r['DTE'],params['DTE'])
1261 self.failUnlessEqual(r['Spare3'],params['Spare3'])
1262
1264 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
1265 help='decode a "b_pos_and_shipdata_broken" AIS message')
1266 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
1267 help='encode a "b_pos_and_shipdata_broken" AIS message')
1268 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
1269 ,help='Field parameter value [default: %default]')
1270 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
1271 ,help='Field parameter value [default: %default]')
1272 parser.add_option('--SOG-field', dest='SOGField',default=Decimal('102.3'),metavar='udecimal',type='string'
1273 ,help='Field parameter value [default: %default]')
1274 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int'
1275 ,help='Field parameter value [default: %default]')
1276 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
1277 ,help='Field parameter value [default: %default]')
1278 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
1279 ,help='Field parameter value [default: %default]')
1280 parser.add_option('--COG-field', dest='COGField',default=Decimal('360'),metavar='udecimal',type='string'
1281 ,help='Field parameter value [default: %default]')
1282 parser.add_option('--TrueHeading-field', dest='TrueHeadingField',default=511,metavar='uint',type='int'
1283 ,help='Field parameter value [default: %default]')
1284 parser.add_option('--TimeStamp-field', dest='TimeStampField',default=60,metavar='uint',type='int'
1285 ,help='Field parameter value [default: %default]')
1286 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string'
1287 ,help='Field parameter value [default: %default]')
1288 parser.add_option('--shipandcargo-field', dest='shipandcargoField',default=0,metavar='uint',type='int'
1289 ,help='Field parameter value [default: %default]')
1290 parser.add_option('--dimA-field', dest='dimAField',default=0,metavar='uint',type='int'
1291 ,help='Field parameter value [default: %default]')
1292 parser.add_option('--dimB-field', dest='dimBField',default=0,metavar='uint',type='int'
1293 ,help='Field parameter value [default: %default]')
1294 parser.add_option('--dimC-field', dest='dimCField',default=0,metavar='uint',type='int'
1295 ,help='Field parameter value [default: %default]')
1296 parser.add_option('--dimD-field', dest='dimDField',default=0,metavar='uint',type='int'
1297 ,help='Field parameter value [default: %default]')
1298 parser.add_option('--fixtype-field', dest='fixtypeField',default=0,metavar='uint',type='int'
1299 ,help='Field parameter value [default: %default]')
1300 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int'
1301 ,help='Field parameter value [default: %default]')
1302 parser.add_option('--DTE-field', dest='DTEField',metavar='uint',type='int'
1303 ,help='Field parameter value [default: %default]')
1304
1305
1306 if __name__=='__main__':
1307
1308 from optparse import OptionParser
1309 parser = OptionParser(usage="%prog [options]",
1310 version="%prog "+__version__)
1311
1312 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
1313 help='run the documentation tests')
1314 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
1315 help='run the unit tests')
1316 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
1317 help='Make the test output verbose')
1318
1319
1320
1321 typeChoices = ('binary','nmeapayload','nmea')
1322 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
1323 ,default='nmeapayload'
1324 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
1325
1326
1327 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
1328 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
1329 ,default='std'
1330 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
1331
1332 parser.add_option('-o','--output',dest='outputFileName',default=None,
1333 help='Name of the python file to write [default: stdout]')
1334
1335 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
1336 choices=fieldList,
1337 help='Which fields to include in the output. Currently only for csv output [default: all]')
1338
1339 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
1340 help='Print the field name for csv')
1341
1342 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
1343 help='Print out an sql create command for the table.')
1344
1345 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
1346 help='Print a LaTeX table of the type')
1347
1348 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
1349 help='Print delimited table of the type (for Word table importing)')
1350 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
1351 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
1352
1353
1354 dbChoices = ('sqlite','postgres')
1355 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
1356 ,choices=dbChoices,type='choice'
1357 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
1358
1359 addMsgOptions(parser)
1360
1361 (options,args) = parser.parse_args()
1362 success=True
1363
1364 if options.doctest:
1365 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
1366 sys.argv= [sys.argv[0]]
1367 if options.verbose: sys.argv.append('-v')
1368 import doctest
1369 numfail,numtests=doctest.testmod()
1370 if numfail==0: print 'ok'
1371 else:
1372 print 'FAILED'
1373 success=False
1374
1375 if not success: sys.exit('Something Failed')
1376 del success
1377
1378 if options.unittest:
1379 sys.argv = [sys.argv[0]]
1380 if options.verbose: sys.argv.append('-v')
1381 unittest.main()
1382
1383 outfile = sys.stdout
1384 if None!=options.outputFileName:
1385 outfile = file(options.outputFileName,'w')
1386
1387
1388 if options.doEncode:
1389
1390 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1391 if None==options.UserIDField: parser.error("missing value for UserIDField")
1392 if None==options.SOGField: parser.error("missing value for SOGField")
1393 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField")
1394 if None==options.longitudeField: parser.error("missing value for longitudeField")
1395 if None==options.latitudeField: parser.error("missing value for latitudeField")
1396 if None==options.COGField: parser.error("missing value for COGField")
1397 if None==options.TrueHeadingField: parser.error("missing value for TrueHeadingField")
1398 if None==options.TimeStampField: parser.error("missing value for TimeStampField")
1399 if None==options.nameField: parser.error("missing value for nameField")
1400 if None==options.shipandcargoField: parser.error("missing value for shipandcargoField")
1401 if None==options.dimAField: parser.error("missing value for dimAField")
1402 if None==options.dimBField: parser.error("missing value for dimBField")
1403 if None==options.dimCField: parser.error("missing value for dimCField")
1404 if None==options.dimDField: parser.error("missing value for dimDField")
1405 if None==options.fixtypeField: parser.error("missing value for fixtypeField")
1406 if None==options.RAIMField: parser.error("missing value for RAIMField")
1407 if None==options.DTEField: parser.error("missing value for DTEField")
1408 msgDict={
1409 'MessageID': '19',
1410 'RepeatIndicator': options.RepeatIndicatorField,
1411 'UserID': options.UserIDField,
1412 'Spare': '0',
1413 'SOG': options.SOGField,
1414 'PositionAccuracy': options.PositionAccuracyField,
1415 'longitude': options.longitudeField,
1416 'latitude': options.latitudeField,
1417 'COG': options.COGField,
1418 'TrueHeading': options.TrueHeadingField,
1419 'TimeStamp': options.TimeStampField,
1420 'Spare2': '0',
1421 'name': options.nameField,
1422 'shipandcargo': options.shipandcargoField,
1423 'dimA': options.dimAField,
1424 'dimB': options.dimBField,
1425 'dimC': options.dimCField,
1426 'dimD': options.dimDField,
1427 'fixtype': options.fixtypeField,
1428 'RAIM': options.RAIMField,
1429 'DTE': options.DTEField,
1430 'Spare3': '0',
1431 }
1432
1433 bits = encode(msgDict)
1434 if 'binary'==options.ioType: print str(bits)
1435 elif 'nmeapayload'==options.ioType:
1436
1437 print "bitLen",len(bits)
1438 bitLen=len(bits)
1439 if bitLen%6!=0:
1440 bits = bits + BitVector(size=(6 - (bitLen%6)))
1441 print "result:",binary.bitvectoais6(bits)[0]
1442
1443
1444
1445 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1446 else: sys.exit('ERROR: unknown ioType. Help!')
1447
1448
1449 if options.sqlCreate:
1450 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1451
1452 if options.latexDefinitionTable:
1453 latexDefinitionTable(outfile)
1454
1455
1456 if options.textDefinitionTable:
1457 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1458
1459 if options.printCsvfieldList:
1460
1461 if None == options.fieldList: options.fieldList = fieldList
1462 import StringIO
1463 buf = StringIO.StringIO()
1464 for field in options.fieldList:
1465 buf.write(field+',')
1466 result = buf.getvalue()
1467 if result[-1] == ',': print result[:-1]
1468 else: print result
1469
1470 if options.doDecode:
1471 if len(args)==0: args = sys.stdin
1472 for msg in args:
1473 bv = None
1474
1475 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1476
1477
1478 bv = binary.ais6tobitvec(msg.split(',')[5])
1479 else:
1480
1481 binaryMsg=True
1482 for c in msg:
1483 if c not in ('0','1'):
1484 binaryMsg=False
1485 break
1486 if binaryMsg:
1487 bv = BitVector(bitstring=msg)
1488 else:
1489 bv = binary.ais6tobitvec(msg)
1490
1491 printFields(decode(bv)
1492 ,out=outfile
1493 ,format=options.outputType
1494 ,fieldList=options.fieldList
1495 ,dbType=options.dbType
1496 )
1497