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 'type',
54 'name',
55 'PositionAccuracy',
56 'longitude',
57 'latitude',
58 'dim',
59 'FixType',
60 'timestamp',
61 'OffPosition',
62 'RegionalApp',
63 'RAIM',
64 'Spare',
65 )
66
67 fieldListPostgres = (
68 'MessageID',
69 'RepeatIndicator',
70 'UserID',
71 'type',
72 'name',
73 'PositionAccuracy',
74 'Position',
75 'dim',
76 'FixType',
77 'timestamp',
78 'OffPosition',
79 'RegionalApp',
80 'RAIM',
81 'Spare',
82 )
83
84 toPgFields = {
85 'longitude':'Position',
86 'latitude':'Position',
87 }
88 '''
89 Go to the Postgis field names from the straight field name
90 '''
91
92 fromPgFields = {
93 'Position':('longitude','latitude',),
94 }
95 '''
96 Go from the Postgis field names to the straight field name
97 '''
98
99 pgTypes = {
100 'Position':'POINT',
101 }
102 '''
103 Lookup table for each postgis field name to get its type.
104 '''
105
106 -def encode(params, validate=False):
107 '''Create a AidsToNavReport binary message payload to pack into an AIS Msg AidsToNavReport.
108
109 Fields in params:
110 - MessageID(uint): AIS message number. Must be 21 aka 'F' (field automatically set to "21")
111 - RepeatIndicator(uint): Indicated how many times a message has been repeated
112 - UserID(uint): Unique ship identification number (MMSI)
113 - type(uint): IALA type of aid-to-navigation
114 - name(aisstr6): Name of the aid-to-navigation
115 - PositionAccuracy(uint): Accuracy of positioning fixes
116 - longitude(decimal): Location of the AtoN East West location
117 - latitude(decimal): Location of the AtoN North South location
118 - dim(uint): FIX: break this out.
119 - FixType(uint): Type of electronic position fixing device
120 - timestamp(uint): UTC second when report was generated
121 - OffPosition(bool): True when the AtoN is off station
122 - RegionalApp(uint): Should be set to zero (field automatically set to "0")
123 - RAIM(bool): Receiver autonomous integrity monitoring flag
124 - Spare(uint): Not Used (field automatically set to "0")
125 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
126 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
127 @rtype: BitVector
128 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
129 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
130 '''
131
132 bvList = []
133 bvList.append(binary.setBitVectorSize(BitVector(intVal=21),6))
134 if 'RepeatIndicator' in params:
135 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
136 else:
137 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
138 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
139 if 'type' in params:
140 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),5))
141 else:
142 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),5))
143 if 'name' in params:
144 bvList.append(aisstring.encode(params['name'],120))
145 else:
146 bvList.append(aisstring.encode('@@@@@@@@@@@@@@@@@@@@',120))
147 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['PositionAccuracy']),1))
148 if 'longitude' in params:
149 bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28))
150 else:
151 bvList.append(binary.bvFromSignedInt(108600000,28))
152 if 'latitude' in params:
153 bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27))
154 else:
155 bvList.append(binary.bvFromSignedInt(54600000,27))
156 if 'dim' in params:
157 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dim']),30))
158 else:
159 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),30))
160 if 'FixType' in params:
161 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['FixType']),4))
162 else:
163 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4))
164 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['timestamp']),6))
165 if params["OffPosition"]: bvList.append(TrueBV)
166 else: bvList.append(FalseBV)
167 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),8))
168 if params["RAIM"]: bvList.append(TrueBV)
169 else: bvList.append(FalseBV)
170 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),3))
171
172 return binary.joinBV(bvList)
173
174 -def decode(bv, validate=False):
175 '''Unpack a AidsToNavReport message
176
177 Fields in params:
178 - MessageID(uint): AIS message number. Must be 21 aka 'F' (field automatically set to "21")
179 - RepeatIndicator(uint): Indicated how many times a message has been repeated
180 - UserID(uint): Unique ship identification number (MMSI)
181 - type(uint): IALA type of aid-to-navigation
182 - name(aisstr6): Name of the aid-to-navigation
183 - PositionAccuracy(uint): Accuracy of positioning fixes
184 - longitude(decimal): Location of the AtoN East West location
185 - latitude(decimal): Location of the AtoN North South location
186 - dim(uint): FIX: break this out.
187 - FixType(uint): Type of electronic position fixing device
188 - timestamp(uint): UTC second when report was generated
189 - OffPosition(bool): True when the AtoN is off station
190 - RegionalApp(uint): Should be set to zero (field automatically set to "0")
191 - RAIM(bool): Receiver autonomous integrity monitoring flag
192 - Spare(uint): Not Used (field automatically set to "0")
193 @type bv: BitVector
194 @param bv: Bits defining a message
195 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
196 @rtype: dict
197 @return: params
198 '''
199
200
201
202
203 r = {}
204 r['MessageID']=21
205 r['RepeatIndicator']=int(bv[6:8])
206 r['UserID']=int(bv[8:38])
207 r['type']=int(bv[38:43])
208 r['name']=aisstring.decode(bv[43:163])
209 r['PositionAccuracy']=int(bv[163:164])
210 r['longitude']=Decimal(binary.signedIntFromBV(bv[164:192]))/Decimal('600000')
211 r['latitude']=Decimal(binary.signedIntFromBV(bv[192:219]))/Decimal('600000')
212 r['dim']=int(bv[219:249])
213 r['FixType']=int(bv[249:253])
214 r['timestamp']=int(bv[253:259])
215 r['OffPosition']=bool(int(bv[259:260]))
216 r['RegionalApp']=0
217 r['RAIM']=bool(int(bv[268:269]))
218 r['Spare']=0
219 return r
220
223
226
229
231 return int(bv[38:43])
232
235
237 return int(bv[163:164])
238
241
244
246 return int(bv[219:249])
247
249 return int(bv[249:253])
250
252 return int(bv[253:259])
253
255 return bool(int(bv[259:260]))
256
259
261 return bool(int(bv[268:269]))
262
265
266
268 out.write("<h3>AidsToNavReport</h3>\n")
269 out.write("<table border=\"1\">\n")
270 out.write("<tr bgcolor=\"orange\">\n")
271 out.write("<th align=\"left\">Field Name</th>\n")
272 out.write("<th align=\"left\">Type</th>\n")
273 out.write("<th align=\"left\">Value</th>\n")
274 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
275 out.write("<th align=\"left\">Units</th>\n")
276 out.write("\n")
277 out.write("<tr>\n")
278 out.write("<td>MessageID</td>\n")
279 out.write("<td>uint</td>\n")
280 if 'MessageID' in params:
281 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
282 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
283 out.write("</tr>\n")
284 out.write("\n")
285 out.write("<tr>\n")
286 out.write("<td>RepeatIndicator</td>\n")
287 out.write("<td>uint</td>\n")
288 if 'RepeatIndicator' in params:
289 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n")
290 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut:
291 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>")
292 else:
293 out.write("<td><i>Missing LUT entry</i></td>")
294 out.write("</tr>\n")
295 out.write("\n")
296 out.write("<tr>\n")
297 out.write("<td>UserID</td>\n")
298 out.write("<td>uint</td>\n")
299 if 'UserID' in params:
300 out.write(" <td>"+str(params['UserID'])+"</td>\n")
301 out.write(" <td>"+str(params['UserID'])+"</td>\n")
302 out.write("</tr>\n")
303 out.write("\n")
304 out.write("<tr>\n")
305 out.write("<td>type</td>\n")
306 out.write("<td>uint</td>\n")
307 if 'type' in params:
308 out.write(" <td>"+str(params['type'])+"</td>\n")
309 if str(params['type']) in typeDecodeLut:
310 out.write("<td>"+typeDecodeLut[str(params['type'])]+"</td>")
311 else:
312 out.write("<td><i>Missing LUT entry</i></td>")
313 out.write("</tr>\n")
314 out.write("\n")
315 out.write("<tr>\n")
316 out.write("<td>name</td>\n")
317 out.write("<td>aisstr6</td>\n")
318 if 'name' in params:
319 out.write(" <td>"+str(params['name'])+"</td>\n")
320 out.write(" <td>"+str(params['name'])+"</td>\n")
321 out.write("</tr>\n")
322 out.write("\n")
323 out.write("<tr>\n")
324 out.write("<td>PositionAccuracy</td>\n")
325 out.write("<td>uint</td>\n")
326 if 'PositionAccuracy' in params:
327 out.write(" <td>"+str(params['PositionAccuracy'])+"</td>\n")
328 if str(params['PositionAccuracy']) in PositionAccuracyDecodeLut:
329 out.write("<td>"+PositionAccuracyDecodeLut[str(params['PositionAccuracy'])]+"</td>")
330 else:
331 out.write("<td><i>Missing LUT entry</i></td>")
332 out.write("</tr>\n")
333 out.write("\n")
334 out.write("<tr>\n")
335 out.write("<td>longitude</td>\n")
336 out.write("<td>decimal</td>\n")
337 if 'longitude' in params:
338 out.write(" <td>"+str(params['longitude'])+"</td>\n")
339 out.write(" <td>"+str(params['longitude'])+"</td>\n")
340 out.write("<td>degrees</td>\n")
341 out.write("</tr>\n")
342 out.write("\n")
343 out.write("<tr>\n")
344 out.write("<td>latitude</td>\n")
345 out.write("<td>decimal</td>\n")
346 if 'latitude' in params:
347 out.write(" <td>"+str(params['latitude'])+"</td>\n")
348 out.write(" <td>"+str(params['latitude'])+"</td>\n")
349 out.write("<td>degrees</td>\n")
350 out.write("</tr>\n")
351 out.write("\n")
352 out.write("<tr>\n")
353 out.write("<td>dim</td>\n")
354 out.write("<td>uint</td>\n")
355 if 'dim' in params:
356 out.write(" <td>"+str(params['dim'])+"</td>\n")
357 out.write(" <td>"+str(params['dim'])+"</td>\n")
358 out.write("</tr>\n")
359 out.write("\n")
360 out.write("<tr>\n")
361 out.write("<td>FixType</td>\n")
362 out.write("<td>uint</td>\n")
363 if 'FixType' in params:
364 out.write(" <td>"+str(params['FixType'])+"</td>\n")
365 if str(params['FixType']) in FixTypeDecodeLut:
366 out.write("<td>"+FixTypeDecodeLut[str(params['FixType'])]+"</td>")
367 else:
368 out.write("<td><i>Missing LUT entry</i></td>")
369 out.write("</tr>\n")
370 out.write("\n")
371 out.write("<tr>\n")
372 out.write("<td>timestamp</td>\n")
373 out.write("<td>uint</td>\n")
374 if 'timestamp' in params:
375 out.write(" <td>"+str(params['timestamp'])+"</td>\n")
376 if str(params['timestamp']) in timestampDecodeLut:
377 out.write("<td>"+timestampDecodeLut[str(params['timestamp'])]+"</td>")
378 else:
379 out.write("<td><i>Missing LUT entry</i></td>")
380 out.write("</tr>\n")
381 out.write("\n")
382 out.write("<tr>\n")
383 out.write("<td>OffPosition</td>\n")
384 out.write("<td>bool</td>\n")
385 if 'OffPosition' in params:
386 out.write(" <td>"+str(params['OffPosition'])+"</td>\n")
387 if str(params['OffPosition']) in OffPositionDecodeLut:
388 out.write("<td>"+OffPositionDecodeLut[str(params['OffPosition'])]+"</td>")
389 else:
390 out.write("<td><i>Missing LUT entry</i></td>")
391 out.write("</tr>\n")
392 out.write("\n")
393 out.write("<tr>\n")
394 out.write("<td>RegionalApp</td>\n")
395 out.write("<td>uint</td>\n")
396 if 'RegionalApp' in params:
397 out.write(" <td>"+str(params['RegionalApp'])+"</td>\n")
398 out.write(" <td>"+str(params['RegionalApp'])+"</td>\n")
399 out.write("</tr>\n")
400 out.write("\n")
401 out.write("<tr>\n")
402 out.write("<td>RAIM</td>\n")
403 out.write("<td>bool</td>\n")
404 if 'RAIM' in params:
405 out.write(" <td>"+str(params['RAIM'])+"</td>\n")
406 if str(params['RAIM']) in RAIMDecodeLut:
407 out.write("<td>"+RAIMDecodeLut[str(params['RAIM'])]+"</td>")
408 else:
409 out.write("<td><i>Missing LUT entry</i></td>")
410 out.write("</tr>\n")
411 out.write("\n")
412 out.write("<tr>\n")
413 out.write("<td>Spare</td>\n")
414 out.write("<td>uint</td>\n")
415 if 'Spare' in params:
416 out.write(" <td>"+str(params['Spare'])+"</td>\n")
417 out.write(" <td>"+str(params['Spare'])+"</td>\n")
418 out.write("</tr>\n")
419 out.write("</table>\n")
420
421
423 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
424 out.write("\ <Placemark>\n")
425 out.write("\t <name>"+str(params['UserID'])+"</name>\n")
426 out.write("\t\t<description>\n")
427 import StringIO
428 buf = StringIO.StringIO()
429 printHtml(params,buf)
430 import cgi
431 out.write(cgi.escape(buf.getvalue()))
432 out.write("\t\t</description>\n")
433 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
434 out.write("\t\t<Point>\n")
435 out.write("\t\t\t<coordinates>")
436 out.write(str(params['longitude']))
437 out.write(',')
438 out.write(str(params['latitude']))
439 out.write(",0</coordinates>\n")
440 out.write("\t\t</Point>\n")
441 out.write("\t</Placemark>\n")
442
443 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
444 '''Print a AidsToNavReport message to stdout.
445
446 Fields in params:
447 - MessageID(uint): AIS message number. Must be 21 aka 'F' (field automatically set to "21")
448 - RepeatIndicator(uint): Indicated how many times a message has been repeated
449 - UserID(uint): Unique ship identification number (MMSI)
450 - type(uint): IALA type of aid-to-navigation
451 - name(aisstr6): Name of the aid-to-navigation
452 - PositionAccuracy(uint): Accuracy of positioning fixes
453 - longitude(decimal): Location of the AtoN East West location
454 - latitude(decimal): Location of the AtoN North South location
455 - dim(uint): FIX: break this out.
456 - FixType(uint): Type of electronic position fixing device
457 - timestamp(uint): UTC second when report was generated
458 - OffPosition(bool): True when the AtoN is off station
459 - RegionalApp(uint): Should be set to zero (field automatically set to "0")
460 - RAIM(bool): Receiver autonomous integrity monitoring flag
461 - Spare(uint): Not Used (field automatically set to "0")
462 @param params: Dictionary of field names/values.
463 @param out: File like object to write to
464 @rtype: stdout
465 @return: text to out
466 '''
467
468 if 'std'==format:
469 out.write("AidsToNavReport:\n")
470 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
471 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
472 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
473 if 'type' in params: out.write(" type: "+str(params['type'])+"\n")
474 if 'name' in params: out.write(" name: "+str(params['name'])+"\n")
475 if 'PositionAccuracy' in params: out.write(" PositionAccuracy: "+str(params['PositionAccuracy'])+"\n")
476 if 'longitude' in params: out.write(" longitude: "+str(params['longitude'])+"\n")
477 if 'latitude' in params: out.write(" latitude: "+str(params['latitude'])+"\n")
478 if 'dim' in params: out.write(" dim: "+str(params['dim'])+"\n")
479 if 'FixType' in params: out.write(" FixType: "+str(params['FixType'])+"\n")
480 if 'timestamp' in params: out.write(" timestamp: "+str(params['timestamp'])+"\n")
481 if 'OffPosition' in params: out.write(" OffPosition: "+str(params['OffPosition'])+"\n")
482 if 'RegionalApp' in params: out.write(" RegionalApp: "+str(params['RegionalApp'])+"\n")
483 if 'RAIM' in params: out.write(" RAIM: "+str(params['RAIM'])+"\n")
484 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
485 elif 'csv'==format:
486 if None == options.fieldList:
487 options.fieldList = fieldList
488 needComma = False;
489 for field in fieldList:
490 if needComma: out.write(',')
491 needComma = True
492 if field in params:
493 out.write(str(params[field]))
494
495 out.write("\n")
496 elif 'html'==format:
497 printHtml(params,out)
498 elif 'sql'==format:
499 sqlInsertStr(params,out,dbType=dbType)
500 elif 'kml'==format:
501 printKml(params,out)
502 elif 'kml-full'==format:
503 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
504 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
505 out.write("<Document>\n")
506 out.write(" <name>AidsToNavReport</name>\n")
507 printKml(params,out)
508 out.write("</Document>\n")
509 out.write("</kml>\n")
510 else:
511 print "ERROR: unknown format:",format
512 assert False
513
514 return
515
516 RepeatIndicatorEncodeLut = {
517 'default':'0',
518 'do not repeat any more':'3',
519 }
520
521 RepeatIndicatorDecodeLut = {
522 '0':'default',
523 '3':'do not repeat any more',
524 }
525
526 typeEncodeLut = {
527 'Default, Type of A to N not specified':'0',
528 'Reference point':'1',
529 'RACON':'2',
530 'Off Shore Structure':'3',
531 'Spare':'4',
532 'Light, without sectors':'5',
533 'Light, with sectors':'6',
534 'Leading Light Front':'7',
535 'Leading Light Rear':'8',
536 'Beacon, Cardinal N':'9',
537 'Beacon, Cardinal E':'10',
538 'Beacon, Cardinal S':'11',
539 'Beacon, Cardinal W':'12',
540 'Beacon, Port hand':'13',
541 'Beacon, Starbord hand':'14',
542 'Beacon, Preferred channel port hand':'15',
543 'Beacon, Preferred channel starboard hand':'16',
544 'Beacon, Isolated danger':'17',
545 'Beacon, Safe water':'18',
546 'Beacon, Special mark':'19',
547 'Cardinal Mark N':'20',
548 'Cardinal Mark E':'21',
549 'Cardinal Mark S':'22',
550 'Cardinal Mark W':'23',
551 'Port hand Mark':'24',
552 'Starbord hand Mark':'25',
553 'Preferred Channel Port hand':'26',
554 'Preferred Channel Starboard hand':'27',
555 'Isolated danger':'28',
556 'Safe water':'29',
557 'Special Mark':'30',
558 'Light Vessel/LANBY':'31',
559 }
560
561 typeDecodeLut = {
562 '0':'Default, Type of A to N not specified',
563 '1':'Reference point',
564 '2':'RACON',
565 '3':'Off Shore Structure',
566 '4':'Spare',
567 '5':'Light, without sectors',
568 '6':'Light, with sectors',
569 '7':'Leading Light Front',
570 '8':'Leading Light Rear',
571 '9':'Beacon, Cardinal N',
572 '10':'Beacon, Cardinal E',
573 '11':'Beacon, Cardinal S',
574 '12':'Beacon, Cardinal W',
575 '13':'Beacon, Port hand',
576 '14':'Beacon, Starbord hand',
577 '15':'Beacon, Preferred channel port hand',
578 '16':'Beacon, Preferred channel starboard hand',
579 '17':'Beacon, Isolated danger',
580 '18':'Beacon, Safe water',
581 '19':'Beacon, Special mark',
582 '20':'Cardinal Mark N',
583 '21':'Cardinal Mark E',
584 '22':'Cardinal Mark S',
585 '23':'Cardinal Mark W',
586 '24':'Port hand Mark',
587 '25':'Starbord hand Mark',
588 '26':'Preferred Channel Port hand',
589 '27':'Preferred Channel Starboard hand',
590 '28':'Isolated danger',
591 '29':'Safe water',
592 '30':'Special Mark',
593 '31':'Light Vessel/LANBY',
594 }
595
596 PositionAccuracyEncodeLut = {
597 'low (greater than 10 m)':'0',
598 'high (less than 10 m)':'1',
599 }
600
601 PositionAccuracyDecodeLut = {
602 '0':'low (greater than 10 m)',
603 '1':'high (less than 10 m)',
604 }
605
606 FixTypeEncodeLut = {
607 'Undefined (default)':'0',
608 'GPS':'1',
609 'GLONASS':'2',
610 'Combined GPS/GLONASS':'3',
611 'Loran-C':'4',
612 'Chayka':'5',
613 'Integrated Navigation System':'6',
614 'surveyed':'7',
615 'not used - 8':'8',
616 'not used - 9':'9',
617 'not used - 10':'10',
618 'not used - 11':'11',
619 'not used - 12':'12',
620 'not used - 13':'13',
621 'not used - 14':'14',
622 'not used - 15':'15',
623 }
624
625 FixTypeDecodeLut = {
626 '0':'Undefined (default)',
627 '1':'GPS',
628 '2':'GLONASS',
629 '3':'Combined GPS/GLONASS',
630 '4':'Loran-C',
631 '5':'Chayka',
632 '6':'Integrated Navigation System',
633 '7':'surveyed',
634 '8':'not used - 8',
635 '9':'not used - 9',
636 '10':'not used - 10',
637 '11':'not used - 11',
638 '12':'not used - 12',
639 '13':'not used - 13',
640 '14':'not used - 14',
641 '15':'not used - 15',
642 }
643
644 timestampEncodeLut = {
645 'Positioning system is in manual mode':'61',
646 'Electronic position fixing system operates in estimated mode':'62',
647 'Positioning system is inoperative':'63',
648 }
649
650 timestampDecodeLut = {
651 '61':'Positioning system is in manual mode',
652 '62':'Electronic position fixing system operates in estimated mode',
653 '63':'Positioning system is inoperative',
654 }
655
656 OffPositionEncodeLut = {
657 'On position':'False',
658 'Off position':'True',
659 }
660
661 OffPositionDecodeLut = {
662 'False':'On position',
663 'True':'Off position',
664 }
665
666 RAIMEncodeLut = {
667 'not in use':'False',
668 'in use':'True',
669 }
670
671 RAIMDecodeLut = {
672 'False':'not in use',
673 'True':'in use',
674 }
675
676
677
678
679
680 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
681 ,addCoastGuardFields=True
682 ,dbType='postgres'
683 ):
684 '''
685 Return the SQL CREATE command for this message type
686 @param outfile: file like object to print to.
687 @param fields: which fields to put in the create. Defaults to all.
688 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
689 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
690 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
691 @type addCoastGuardFields: bool
692 @return: sql create string
693 @rtype: str
694
695 @see: sqlCreate
696 '''
697
698 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
699
700 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
701 '''
702 Return the sqlhelp object to create the table.
703
704 @param fields: which fields to put in the create. Defaults to all.
705 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
706 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
707 @type addCoastGuardFields: bool
708 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
709 @return: An object that can be used to generate a return
710 @rtype: sqlhelp.create
711 '''
712 if None == fields: fields = fieldList
713 import sqlhelp
714 c = sqlhelp.create('AidsToNavReport',dbType=dbType)
715 c.addPrimaryKey()
716 if 'MessageID' in fields: c.addInt ('MessageID')
717 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
718 if 'UserID' in fields: c.addInt ('UserID')
719 if 'type' in fields: c.addInt ('type')
720 if 'name' in fields: c.addVarChar('name',20)
721 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy')
722 if dbType != 'postgres':
723 if 'longitude' in fields: c.addDecimal('longitude',8,5)
724 if dbType != 'postgres':
725 if 'latitude' in fields: c.addDecimal('latitude',8,5)
726 if 'dim' in fields: c.addInt ('dim')
727 if 'FixType' in fields: c.addInt ('FixType')
728 if 'timestamp' in fields: c.addInt ('timestamp')
729 if 'OffPosition' in fields: c.addBool('OffPosition')
730 if 'RegionalApp' in fields: c.addInt ('RegionalApp')
731 if 'RAIM' in fields: c.addBool('RAIM')
732 if 'Spare' in fields: c.addInt ('Spare')
733
734 if addCoastGuardFields:
735
736
737
738
739
740 c.addVarChar('cg_r',15)
741 c.addInt('cg_sec')
742
743 c.addTimestamp('cg_timestamp')
744
745 if dbType == 'postgres':
746
747
748 c.addPostGIS('Position','POINT',2,SRID=4326);
749
750 return c
751
752 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
753 '''
754 Return the SQL INSERT command for this message type
755 @param params: dictionary of values keyed by field name
756 @param outfile: file like object to print to.
757 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
758 @return: sql create string
759 @rtype: str
760
761 @see: sqlCreate
762 '''
763 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
764
765
766 -def sqlInsert(params,extraParams=None,dbType='postgres'):
767 '''
768 Give the SQL INSERT statement
769 @param params: dict keyed by field name of values
770 @param extraParams: any extra fields that you have created beyond the normal ais message fields
771 @rtype: sqlhelp.insert
772 @return: insert class instance
773 @todo: allow optional type checking of params?
774 @warning: this will take invalid keys happily and do what???
775 '''
776 import sqlhelp
777 i = sqlhelp.insert('AidsToNavReport',dbType=dbType)
778
779 if dbType=='postgres':
780 finished = []
781 for key in params:
782 if key in finished:
783 continue
784
785 if key not in toPgFields and key not in fromPgFields:
786 if type(params[key])==Decimal: i.add(key,float(params[key]))
787 else: i.add(key,params[key])
788 else:
789 if key in fromPgFields:
790 val = params[key]
791
792 i.addPostGIS(key,val)
793 finished.append(key)
794 else:
795
796 pgName = toPgFields[key]
797
798 valStr=pgTypes[pgName]+'('
799 vals = []
800 for nonPgKey in fromPgFields[pgName]:
801 vals.append(str(params[nonPgKey]))
802 finished.append(nonPgKey)
803 valStr+=' '.join(vals)+')'
804 i.addPostGIS(pgName,valStr)
805 else:
806 for key in params:
807 if type(params[key])==Decimal: i.add(key,float(params[key]))
808 else: i.add(key,params[key])
809
810 if None != extraParams:
811 for key in extraParams:
812 i.add(key,extraParams[key])
813
814 return i
815
816
817
818
819
822 '''
823 Return the LaTeX definition table for this message type
824 @param outfile: file like object to print to.
825 @type outfile: file obj
826 @return: LaTeX table string via the outfile
827 @rtype: str
828
829 '''
830 o = outfile
831
832 o.write('''
833 \\begin{table}%[htb]
834 \\centering
835 \\begin{tabular}{|l|c|l|}
836 \\hline
837 Parameter & Number of bits & Description
838 \\\\ \\hline\\hline
839 MessageID & 6 & AIS message number. Must be 21 aka 'F' \\\\ \hline
840 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
841 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
842 type & 5 & IALA type of aid-to-navigation \\\\ \hline
843 name & 120 & Name of the aid-to-navigation \\\\ \hline
844 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline
845 longitude & 28 & Location of the AtoN East West location \\\\ \hline
846 latitude & 27 & Location of the AtoN North South location \\\\ \hline
847 dim & 30 & FIX: break this out. \\\\ \hline
848 FixType & 4 & Type of electronic position fixing device \\\\ \hline
849 timestamp & 6 & UTC second when report was generated \\\\ \hline
850 OffPosition & 1 & True when the AtoN is off station \\\\ \hline
851 RegionalApp & 8 & Should be set to zero \\\\ \hline
852 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline
853 Spare & 3 & Not Used\\\\ \\hline \\hline
854 Total bits & 272 & Appears to take 2 slots with 152 pad bits to fill the last slot \\\\ \\hline
855 \\end{tabular}
856 \\caption{AIS message number 21: Used by a station mounted on an aid-to-navigation. Note IALA A-124 P.19 for more bits than are here. Also covered in A-126 in ANNEX 1 - MESSAGE 21 in IALA Recommendation A-126 on the use of AIS in Marine Aids to Navigation Serves Ed 1.1. This has optional extensions. What is the IALA Page 7 that Mueller refered to for the RegioanlApp field?}
857 \\label{tab:AidsToNavReport}
858 \\end{table}
859 ''')
860
861
862
863
864
865 -def textDefinitionTable(outfile=sys.stdout
866 ,delim='\t'
867 ):
868 '''
869 Return the text definition table for this message type
870 @param outfile: file like object to print to.
871 @type outfile: file obj
872 @return: text table string via the outfile
873 @rtype: str
874
875 '''
876 o = outfile
877 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
878 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 21 aka 'F'
879 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
880 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
881 type'''+delim+'''5'''+delim+'''IALA type of aid-to-navigation
882 name'''+delim+'''120'''+delim+'''Name of the aid-to-navigation
883 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes
884 longitude'''+delim+'''28'''+delim+'''Location of the AtoN East West location
885 latitude'''+delim+'''27'''+delim+'''Location of the AtoN North South location
886 dim'''+delim+'''30'''+delim+'''FIX: break this out.
887 FixType'''+delim+'''4'''+delim+'''Type of electronic position fixing device
888 timestamp'''+delim+'''6'''+delim+'''UTC second when report was generated
889 OffPosition'''+delim+'''1'''+delim+'''True when the AtoN is off station
890 RegionalApp'''+delim+'''8'''+delim+'''Should be set to zero
891 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag
892 Spare'''+delim+'''3'''+delim+'''Not Used
893 Total bits'''+delim+'''272'''+delim+'''Appears to take 2 slots with 152 pad bits to fill the last slot''')
894
895
896
897
898
899 import unittest
901 '''Return a params file base on the testvalue tags.
902 @rtype: dict
903 @return: params based on testvalue tags
904 '''
905 params = {}
906 params['MessageID'] = 21
907 params['RepeatIndicator'] = 1
908 params['UserID'] = 1193046
909 params['type'] = 28
910 params['name'] = 'BUNCH OF ROCKS ATON@'
911 params['PositionAccuracy'] = 1
912 params['longitude'] = Decimal('-122.16328055555556')
913 params['latitude'] = Decimal('37.424458333333334')
914 params['dim'] = 0
915 params['FixType'] = 2
916 params['timestamp'] = 62
917 params['OffPosition'] = False
918 params['RegionalApp'] = 0
919 params['RAIM'] = False
920 params['Spare'] = 0
921
922 return params
923
925 '''Use testvalue tag text from each type to build test case the AidsToNavReport message'''
927
928 params = testParams()
929 bits = encode(params)
930 r = decode(bits)
931
932
933 self.failUnlessEqual(r['MessageID'],params['MessageID'])
934 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
935 self.failUnlessEqual(r['UserID'],params['UserID'])
936 self.failUnlessEqual(r['type'],params['type'])
937 self.failUnlessEqual(r['name'],params['name'])
938 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy'])
939 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
940 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
941 self.failUnlessEqual(r['dim'],params['dim'])
942 self.failUnlessEqual(r['FixType'],params['FixType'])
943 self.failUnlessEqual(r['timestamp'],params['timestamp'])
944 self.failUnlessEqual(r['OffPosition'],params['OffPosition'])
945 self.failUnlessEqual(r['RegionalApp'],params['RegionalApp'])
946 self.failUnlessEqual(r['RAIM'],params['RAIM'])
947 self.failUnlessEqual(r['Spare'],params['Spare'])
948
950 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
951 help='decode a "AidsToNavReport" AIS message')
952 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
953 help='encode a "AidsToNavReport" AIS message')
954 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
955 ,help='Field parameter value [default: %default]')
956 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
957 ,help='Field parameter value [default: %default]')
958 parser.add_option('--type-field', dest='typeField',default=0,metavar='uint',type='int'
959 ,help='Field parameter value [default: %default]')
960 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string'
961 ,help='Field parameter value [default: %default]')
962 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int'
963 ,help='Field parameter value [default: %default]')
964 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
965 ,help='Field parameter value [default: %default]')
966 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
967 ,help='Field parameter value [default: %default]')
968 parser.add_option('--dim-field', dest='dimField',default=0,metavar='uint',type='int'
969 ,help='Field parameter value [default: %default]')
970 parser.add_option('--FixType-field', dest='FixTypeField',default=0,metavar='uint',type='int'
971 ,help='Field parameter value [default: %default]')
972 parser.add_option('--timestamp-field', dest='timestampField',metavar='uint',type='int'
973 ,help='Field parameter value [default: %default]')
974 parser.add_option('--OffPosition-field', dest='OffPositionField',metavar='bool',type='int'
975 ,help='Field parameter value [default: %default]')
976 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int'
977 ,help='Field parameter value [default: %default]')
978
979
980 if __name__=='__main__':
981
982 from optparse import OptionParser
983 parser = OptionParser(usage="%prog [options]",
984 version="%prog "+__version__)
985
986 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
987 help='run the documentation tests')
988 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
989 help='run the unit tests')
990 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
991 help='Make the test output verbose')
992
993
994
995 typeChoices = ('binary','nmeapayload','nmea')
996 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
997 ,default='nmeapayload'
998 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
999
1000
1001 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
1002 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
1003 ,default='std'
1004 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
1005
1006 parser.add_option('-o','--output',dest='outputFileName',default=None,
1007 help='Name of the python file to write [default: stdout]')
1008
1009 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
1010 choices=fieldList,
1011 help='Which fields to include in the output. Currently only for csv output [default: all]')
1012
1013 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
1014 help='Print the field name for csv')
1015
1016 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
1017 help='Print out an sql create command for the table.')
1018
1019 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
1020 help='Print a LaTeX table of the type')
1021
1022 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
1023 help='Print delimited table of the type (for Word table importing)')
1024 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
1025 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
1026
1027
1028 dbChoices = ('sqlite','postgres')
1029 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
1030 ,choices=dbChoices,type='choice'
1031 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
1032
1033 addMsgOptions(parser)
1034
1035 (options,args) = parser.parse_args()
1036 success=True
1037
1038 if options.doctest:
1039 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
1040 sys.argv= [sys.argv[0]]
1041 if options.verbose: sys.argv.append('-v')
1042 import doctest
1043 numfail,numtests=doctest.testmod()
1044 if numfail==0: print 'ok'
1045 else:
1046 print 'FAILED'
1047 success=False
1048
1049 if not success: sys.exit('Something Failed')
1050 del success
1051
1052 if options.unittest:
1053 sys.argv = [sys.argv[0]]
1054 if options.verbose: sys.argv.append('-v')
1055 unittest.main()
1056
1057 outfile = sys.stdout
1058 if None!=options.outputFileName:
1059 outfile = file(options.outputFileName,'w')
1060
1061
1062 if options.doEncode:
1063
1064 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1065 if None==options.UserIDField: parser.error("missing value for UserIDField")
1066 if None==options.typeField: parser.error("missing value for typeField")
1067 if None==options.nameField: parser.error("missing value for nameField")
1068 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField")
1069 if None==options.longitudeField: parser.error("missing value for longitudeField")
1070 if None==options.latitudeField: parser.error("missing value for latitudeField")
1071 if None==options.dimField: parser.error("missing value for dimField")
1072 if None==options.FixTypeField: parser.error("missing value for FixTypeField")
1073 if None==options.timestampField: parser.error("missing value for timestampField")
1074 if None==options.OffPositionField: parser.error("missing value for OffPositionField")
1075 if None==options.RAIMField: parser.error("missing value for RAIMField")
1076 msgDict={
1077 'MessageID': '21',
1078 'RepeatIndicator': options.RepeatIndicatorField,
1079 'UserID': options.UserIDField,
1080 'type': options.typeField,
1081 'name': options.nameField,
1082 'PositionAccuracy': options.PositionAccuracyField,
1083 'longitude': options.longitudeField,
1084 'latitude': options.latitudeField,
1085 'dim': options.dimField,
1086 'FixType': options.FixTypeField,
1087 'timestamp': options.timestampField,
1088 'OffPosition': options.OffPositionField,
1089 'RegionalApp': '0',
1090 'RAIM': options.RAIMField,
1091 'Spare': '0',
1092 }
1093
1094 bits = encode(msgDict)
1095 if 'binary'==options.ioType: print str(bits)
1096 elif 'nmeapayload'==options.ioType:
1097
1098 print "bitLen",len(bits)
1099 bitLen=len(bits)
1100 if bitLen%6!=0:
1101 bits = bits + BitVector(size=(6 - (bitLen%6)))
1102 print "result:",binary.bitvectoais6(bits)[0]
1103
1104
1105
1106 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1107 else: sys.exit('ERROR: unknown ioType. Help!')
1108
1109
1110 if options.sqlCreate:
1111 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1112
1113 if options.latexDefinitionTable:
1114 latexDefinitionTable(outfile)
1115
1116
1117 if options.textDefinitionTable:
1118 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1119
1120 if options.printCsvfieldList:
1121
1122 if None == options.fieldList: options.fieldList = fieldList
1123 import StringIO
1124 buf = StringIO.StringIO()
1125 for field in options.fieldList:
1126 buf.write(field+',')
1127 result = buf.getvalue()
1128 if result[-1] == ',': print result[:-1]
1129 else: print result
1130
1131 if options.doDecode:
1132 if len(args)==0: args = sys.stdin
1133 for msg in args:
1134 bv = None
1135
1136 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1137
1138
1139 bv = binary.ais6tobitvec(msg.split(',')[5])
1140 else:
1141
1142 binaryMsg=True
1143 for c in msg:
1144 if c not in ('0','1'):
1145 binaryMsg=False
1146 break
1147 if binaryMsg:
1148 bv = BitVector(bitstring=msg)
1149 else:
1150 bv = binary.ais6tobitvec(msg)
1151
1152 printFields(decode(bv)
1153 ,out=outfile
1154 ,format=options.outputType
1155 ,fieldList=options.fieldList
1156 ,dbType=options.dbType
1157 )
1158