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