1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-04-07 $'.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 c.addPostGIS('Position','POINT',2);
747
748 return c
749
750 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
751 '''
752 Return the SQL INSERT command for this message type
753 @param params: dictionary of values keyed by field name
754 @param outfile: file like object to print to.
755 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
756 @return: sql create string
757 @rtype: str
758
759 @see: sqlCreate
760 '''
761 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
762
763
764 -def sqlInsert(params,extraParams=None,dbType='postgres'):
765 '''
766 Give the SQL INSERT statement
767 @param params: dict keyed by field name of values
768 @param extraParams: any extra fields that you have created beyond the normal ais message fields
769 @rtype: sqlhelp.insert
770 @return: insert class instance
771 @todo: allow optional type checking of params?
772 @warning: this will take invalid keys happily and do what???
773 '''
774 import sqlhelp
775 i = sqlhelp.insert('AidsToNavReport',dbType=dbType)
776
777 if dbType=='postgres':
778 finished = []
779 for key in params:
780 if key in finished:
781 continue
782
783 if key not in toPgFields and key not in fromPgFields:
784 if type(params[key])==Decimal: i.add(key,float(params[key]))
785 else: i.add(key,params[key])
786 else:
787 if key in fromPgFields:
788 val = params[key]
789
790 i.addPostGIS(key,val)
791 finished.append(key)
792 else:
793
794 pgName = toPgFields[key]
795
796 valStr=pgTypes[pgName]+'('
797 vals = []
798 for nonPgKey in fromPgFields[pgName]:
799 vals.append(str(params[nonPgKey]))
800 finished.append(nonPgKey)
801 valStr+=' '.join(vals)+')'
802 i.addPostGIS(pgName,valStr)
803 else:
804 for key in params:
805 if type(params[key])==Decimal: i.add(key,float(params[key]))
806 else: i.add(key,params[key])
807
808 if None != extraParams:
809 for key in extraParams:
810 i.add(key,extraParams[key])
811
812 return i
813
814
815
816
817
820 '''
821 Return the LaTeX definition table for this message type
822 @param outfile: file like object to print to.
823 @type outfile: file obj
824 @return: LaTeX table string via the outfile
825 @rtype: str
826
827 '''
828 o = outfile
829
830 o.write('''
831 \\begin{table}%[htb]
832 \\centering
833 \\begin{tabular}{|l|c|l|}
834 \\hline
835 Parameter & Number of bits & Description
836 \\\\ \\hline\\hline
837 MessageID & 6 & AIS message number. Must be 21 aka 'F' \\\\ \hline
838 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
839 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
840 type & 5 & IALA type of aid-to-navigation \\\\ \hline
841 name & 120 & Name of the aid-to-navigation \\\\ \hline
842 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline
843 longitude & 28 & Location of the AtoN East West location \\\\ \hline
844 latitude & 27 & Location of the AtoN North South location \\\\ \hline
845 dim & 30 & FIX: break this out. \\\\ \hline
846 FixType & 4 & Type of electronic position fixing device \\\\ \hline
847 timestamp & 6 & UTC second when report was generated \\\\ \hline
848 OffPosition & 1 & True when the AtoN is off station \\\\ \hline
849 RegionalApp & 8 & Should be set to zero \\\\ \hline
850 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline
851 Spare & 3 & Not Used\\\\ \\hline \\hline
852 Total bits & 272 & Appears to take 2 slots with 152 pad bits to fill the last slot \\\\ \\hline
853 \\end{tabular}
854 \\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}
855 \\label{tab:AidsToNavReport}
856 \\end{table}
857 ''')
858
859
860
861
862
863 -def textDefinitionTable(outfile=sys.stdout
864 ,delim='\t'
865 ):
866 '''
867 Return the text definition table for this message type
868 @param outfile: file like object to print to.
869 @type outfile: file obj
870 @return: text table string via the outfile
871 @rtype: str
872
873 '''
874 o = outfile
875 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
876 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 21 aka 'F'
877 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
878 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
879 type'''+delim+'''5'''+delim+'''IALA type of aid-to-navigation
880 name'''+delim+'''120'''+delim+'''Name of the aid-to-navigation
881 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes
882 longitude'''+delim+'''28'''+delim+'''Location of the AtoN East West location
883 latitude'''+delim+'''27'''+delim+'''Location of the AtoN North South location
884 dim'''+delim+'''30'''+delim+'''FIX: break this out.
885 FixType'''+delim+'''4'''+delim+'''Type of electronic position fixing device
886 timestamp'''+delim+'''6'''+delim+'''UTC second when report was generated
887 OffPosition'''+delim+'''1'''+delim+'''True when the AtoN is off station
888 RegionalApp'''+delim+'''8'''+delim+'''Should be set to zero
889 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag
890 Spare'''+delim+'''3'''+delim+'''Not Used
891 Total bits'''+delim+'''272'''+delim+'''Appears to take 2 slots with 152 pad bits to fill the last slot''')
892
893
894
895
896
897 import unittest
899 '''Return a params file base on the testvalue tags.
900 @rtype: dict
901 @return: params based on testvalue tags
902 '''
903 params = {}
904 params['MessageID'] = 21
905 params['RepeatIndicator'] = 1
906 params['UserID'] = 1193046
907 params['type'] = 28
908 params['name'] = 'BUNCH OF ROCKS ATON@'
909 params['PositionAccuracy'] = 1
910 params['longitude'] = Decimal('-122.16328055555556')
911 params['latitude'] = Decimal('37.424458333333334')
912 params['dim'] = 0
913 params['FixType'] = 2
914 params['timestamp'] = 62
915 params['OffPosition'] = False
916 params['RegionalApp'] = 0
917 params['RAIM'] = False
918 params['Spare'] = 0
919
920 return params
921
923 '''Use testvalue tag text from each type to build test case the AidsToNavReport message'''
925
926 params = testParams()
927 bits = encode(params)
928 r = decode(bits)
929
930
931 self.failUnlessEqual(r['MessageID'],params['MessageID'])
932 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
933 self.failUnlessEqual(r['UserID'],params['UserID'])
934 self.failUnlessEqual(r['type'],params['type'])
935 self.failUnlessEqual(r['name'],params['name'])
936 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy'])
937 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5)
938 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5)
939 self.failUnlessEqual(r['dim'],params['dim'])
940 self.failUnlessEqual(r['FixType'],params['FixType'])
941 self.failUnlessEqual(r['timestamp'],params['timestamp'])
942 self.failUnlessEqual(r['OffPosition'],params['OffPosition'])
943 self.failUnlessEqual(r['RegionalApp'],params['RegionalApp'])
944 self.failUnlessEqual(r['RAIM'],params['RAIM'])
945 self.failUnlessEqual(r['Spare'],params['Spare'])
946
948 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
949 help='decode a "AidsToNavReport" AIS message')
950 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
951 help='encode a "AidsToNavReport" AIS message')
952 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
953 ,help='Field parameter value [default: %default]')
954 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
955 ,help='Field parameter value [default: %default]')
956 parser.add_option('--type-field', dest='typeField',default=0,metavar='uint',type='int'
957 ,help='Field parameter value [default: %default]')
958 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string'
959 ,help='Field parameter value [default: %default]')
960 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int'
961 ,help='Field parameter value [default: %default]')
962 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string'
963 ,help='Field parameter value [default: %default]')
964 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string'
965 ,help='Field parameter value [default: %default]')
966 parser.add_option('--dim-field', dest='dimField',default=0,metavar='uint',type='int'
967 ,help='Field parameter value [default: %default]')
968 parser.add_option('--FixType-field', dest='FixTypeField',default=0,metavar='uint',type='int'
969 ,help='Field parameter value [default: %default]')
970 parser.add_option('--timestamp-field', dest='timestampField',metavar='uint',type='int'
971 ,help='Field parameter value [default: %default]')
972 parser.add_option('--OffPosition-field', dest='OffPositionField',metavar='bool',type='int'
973 ,help='Field parameter value [default: %default]')
974 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int'
975 ,help='Field parameter value [default: %default]')
976
977
978 if __name__=='__main__':
979
980 from optparse import OptionParser
981 parser = OptionParser(usage="%prog [options]",
982 version="%prog "+__version__)
983
984 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
985 help='run the documentation tests')
986 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
987 help='run the unit tests')
988 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
989 help='Make the test output verbose')
990
991
992
993 typeChoices = ('binary','nmeapayload','nmea')
994 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
995 ,default='nmeapayload'
996 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
997
998
999 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
1000 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
1001 ,default='std'
1002 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
1003
1004 parser.add_option('-o','--output',dest='outputFileName',default=None,
1005 help='Name of the python file to write [default: stdout]')
1006
1007 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
1008 choices=fieldList,
1009 help='Which fields to include in the output. Currently only for csv output [default: all]')
1010
1011 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
1012 help='Print the field name for csv')
1013
1014 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
1015 help='Print out an sql create command for the table.')
1016
1017 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
1018 help='Print a LaTeX table of the type')
1019
1020 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
1021 help='Print delimited table of the type (for Word table importing)')
1022 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
1023 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
1024
1025
1026 dbChoices = ('sqlite','postgres')
1027 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
1028 ,choices=dbChoices,type='choice'
1029 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
1030
1031 addMsgOptions(parser)
1032
1033 (options,args) = parser.parse_args()
1034 success=True
1035
1036 if options.doctest:
1037 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
1038 sys.argv= [sys.argv[0]]
1039 if options.verbose: sys.argv.append('-v')
1040 import doctest
1041 numfail,numtests=doctest.testmod()
1042 if numfail==0: print 'ok'
1043 else:
1044 print 'FAILED'
1045 success=False
1046
1047 if not success: sys.exit('Something Failed')
1048 del success
1049
1050 if options.unittest:
1051 sys.argv = [sys.argv[0]]
1052 if options.verbose: sys.argv.append('-v')
1053 unittest.main()
1054
1055 outfile = sys.stdout
1056 if None!=options.outputFileName:
1057 outfile = file(options.outputFileName,'w')
1058
1059
1060 if options.doEncode:
1061
1062 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1063 if None==options.UserIDField: parser.error("missing value for UserIDField")
1064 if None==options.typeField: parser.error("missing value for typeField")
1065 if None==options.nameField: parser.error("missing value for nameField")
1066 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField")
1067 if None==options.longitudeField: parser.error("missing value for longitudeField")
1068 if None==options.latitudeField: parser.error("missing value for latitudeField")
1069 if None==options.dimField: parser.error("missing value for dimField")
1070 if None==options.FixTypeField: parser.error("missing value for FixTypeField")
1071 if None==options.timestampField: parser.error("missing value for timestampField")
1072 if None==options.OffPositionField: parser.error("missing value for OffPositionField")
1073 if None==options.RAIMField: parser.error("missing value for RAIMField")
1074 msgDict={
1075 'MessageID': '21',
1076 'RepeatIndicator': options.RepeatIndicatorField,
1077 'UserID': options.UserIDField,
1078 'type': options.typeField,
1079 'name': options.nameField,
1080 'PositionAccuracy': options.PositionAccuracyField,
1081 'longitude': options.longitudeField,
1082 'latitude': options.latitudeField,
1083 'dim': options.dimField,
1084 'FixType': options.FixTypeField,
1085 'timestamp': options.timestampField,
1086 'OffPosition': options.OffPositionField,
1087 'RegionalApp': '0',
1088 'RAIM': options.RAIMField,
1089 'Spare': '0',
1090 }
1091
1092 bits = encode(msgDict)
1093 if 'binary'==options.ioType: print str(bits)
1094 elif 'nmeapayload'==options.ioType:
1095
1096 print "bitLen",len(bits)
1097 bitLen=len(bits)
1098 if bitLen%6!=0:
1099 bits = bits + BitVector(size=(6 - (bitLen%6)))
1100 print "result:",binary.bitvectoais6(bits)[0]
1101
1102
1103
1104 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1105 else: sys.exit('ERROR: unknown ioType. Help!')
1106
1107
1108 if options.sqlCreate:
1109 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1110
1111 if options.latexDefinitionTable:
1112 latexDefinitionTable(outfile)
1113
1114
1115 if options.textDefinitionTable:
1116 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1117
1118 if options.printCsvfieldList:
1119
1120 if None == options.fieldList: options.fieldList = fieldList
1121 import StringIO
1122 buf = StringIO.StringIO()
1123 for field in options.fieldList:
1124 buf.write(field+',')
1125 result = buf.getvalue()
1126 if result[-1] == ',': print result[:-1]
1127 else: print result
1128
1129 if options.doDecode:
1130 for msg in args:
1131 bv = None
1132
1133 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1134
1135
1136 bv = binary.ais6tobitvec(msg.split(',')[5])
1137 else:
1138
1139 binaryMsg=True
1140 for c in msg:
1141 if c not in ('0','1'):
1142 binaryMsg=False
1143 break
1144 if binaryMsg:
1145 bv = BitVector(bitstring=msg)
1146 else:
1147 bv = binary.ais6tobitvec(msg)
1148
1149 printFields(decode(bv)
1150 ,out=outfile
1151 ,format=options.outputType
1152 ,fieldList=options.fieldList
1153 ,dbType=options.dbType
1154 )
1155