Package ais :: Module ais_msg_21
[hide private]
[frames] | no frames]

Source Code for Module ais.ais_msg_21

   1  #!/usr/bin/env python 
   2   
   3  __version__ = '$Revision: 4791 $'.split()[1] 
   4  __date__ = '$Date: 2007-02-18 $'.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  # FIX: check to see if these will be needed 
  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 #Would be nice to check the bit count here.. 198 #if validate: 199 # assert (len(bv)==FIX: SOME NUMBER) 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
218 -def decodeMessageID(bv, validate=False):
219 return 21
220
221 -def decodeRepeatIndicator(bv, validate=False):
222 return int(bv[6:8])
223
224 -def decodeUserID(bv, validate=False):
225 return int(bv[8:38])
226
227 -def decodetype(bv, validate=False):
228 return int(bv[38:43])
229
230 -def decodename(bv, validate=False):
231 return aisstring.decode(bv[43:163])
232
233 -def decodePositionAccuracy(bv, validate=False):
234 return int(bv[163:164])
235
236 -def decodePosition_longitude(bv, validate=False):
237 return Decimal(binary.signedIntFromBV(bv[164:192]))/Decimal('600000')
238
239 -def decodePosition_latitude(bv, validate=False):
240 return Decimal(binary.signedIntFromBV(bv[192:219]))/Decimal('600000')
241
242 -def decodedim(bv, validate=False):
243 return int(bv[219:249])
244
245 -def decodeFixType(bv, validate=False):
246 return int(bv[249:253])
247
248 -def decodetimestamp(bv, validate=False):
249 return int(bv[253:259])
250
251 -def decodeOffPosition(bv, validate=False):
252 return bool(int(bv[259:260]))
253
254 -def decodeRegionalApp(bv, validate=False):
255 return 0
256
257 -def decodeRAIM(bv, validate=False):
258 return bool(int(bv[268:269]))
259
260 -def decodeSpare(bv, validate=False):
261 return 0
262 263
264 -def printHtml(params, out=sys.stdout):
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
419 -def printKml(params, out=sys.stdout):
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 AidsToNavReport 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("AidsToNavReport:\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 # else: leave it empty 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 # Nothing to return
512 513 RepeatIndicatorEncodeLut = { 514 'default':'0', 515 'do not repeat any more':'3', 516 } #RepeatIndicatorEncodeLut 517 518 RepeatIndicatorDecodeLut = { 519 '0':'default', 520 '3':'do not repeat any more', 521 } # RepeatIndicatorEncodeLut 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 } #typeEncodeLut 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 } # typeEncodeLut 592 593 PositionAccuracyEncodeLut = { 594 'low (greater than 10 m)':'0', 595 'high (less than 10 m)':'1', 596 } #PositionAccuracyEncodeLut 597 598 PositionAccuracyDecodeLut = { 599 '0':'low (greater than 10 m)', 600 '1':'high (less than 10 m)', 601 } # PositionAccuracyEncodeLut 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 } #FixTypeEncodeLut 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 } # FixTypeEncodeLut 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 } #timestampEncodeLut 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 } # timestampEncodeLut 652 653 OffPositionEncodeLut = { 654 'On position':'False', 655 'Off position':'True', 656 } #OffPositionEncodeLut 657 658 OffPositionDecodeLut = { 659 'False':'On position', 660 'True':'Off position', 661 } # OffPositionEncodeLut 662 663 RAIMEncodeLut = { 664 'not in use':'False', 665 'in use':'True', 666 } #RAIMEncodeLut 667 668 RAIMDecodeLut = { 669 'False':'not in use', 670 'True':'in use', 671 } # RAIMEncodeLut 672 673 ###################################################################### 674 # SQL SUPPORT 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 # c.addInt('cg_rssi') # Relative signal strength indicator 730 # c.addInt('cg_d') # dBm receive strength 731 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 732 # c.addInt('cg_S') # Slot received in 733 # c.addVarChar('cg_x',10) # Idonno 734 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 735 c.addInt('cg_sec') # UTC seconds since the epoch 736 737 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 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 continue 773 774 if key not in toPgFields and key not in fromPgFields: 775 if type(params[key])==Decimal: i.add(key,float(params[key])) 776 else: i.add(key,params[key]) 777 else: 778 if key in fromPgFields: 779 val = params[key] 780 # Had better be a WKT type like POINT(-88.1 30.321) 781 i.addPostGIS(key,val) 782 finished.append(key) 783 else: 784 # Need to construct the type. 785 pgName = toPgFields[key] 786 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 787 valStr=pgTypes[pgName]+'(' 788 vals = [] 789 for nonPgKey in fromPgFields[pgName]: 790 vals.append(str(params[nonPgKey])) 791 finished.append(nonPgKey) 792 valStr+=' '.join(vals)+')' 793 i.addPostGIS(pgName,valStr) 794 else: 795 for key in params: 796 if type(params[key])==Decimal: i.add(key,float(params[key])) 797 else: i.add(key,params[key]) 798 799 if None != extraParams: 800 for key in extraParams: 801 i.add(key,extraParams[key]) 802 803 return i
804 805 806 ###################################################################### 807 # UNIT TESTING 808 ###################################################################### 809 import unittest
810 -def testParams():
811 '''Return a params file base on the testvalue tags. 812 @rtype: dict 813 @return: params based on testvalue tags 814 ''' 815 params = {} 816 params['MessageID'] = 21 817 params['RepeatIndicator'] = 1 818 params['UserID'] = 1193046 819 params['type'] = 28 820 params['name'] = 'BUNCH OF ROCKS ATON@' 821 params['PositionAccuracy'] = 1 822 params['Position_longitude'] = Decimal('-122.16328055555556') 823 params['Position_latitude'] = Decimal('37.424458333333334') 824 params['dim'] = 0 825 params['FixType'] = 2 826 params['timestamp'] = 62 827 params['OffPosition'] = False 828 params['RegionalApp'] = 0 829 params['RAIM'] = False 830 params['Spare'] = 0 831 832 return params
833
834 -class TestAidsToNavReport(unittest.TestCase):
835 '''Use testvalue tag text from each type to build test case the AidsToNavReport message'''
836 - def testEncodeDecode(self):
837 838 params = testParams() 839 bits = encode(params) 840 r = decode(bits) 841 842 # Check that each parameter came through ok. 843 self.failUnlessEqual(r['MessageID'],params['MessageID']) 844 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 845 self.failUnlessEqual(r['UserID'],params['UserID']) 846 self.failUnlessEqual(r['type'],params['type']) 847 self.failUnlessEqual(r['name'],params['name']) 848 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy']) 849 self.failUnlessAlmostEqual(r['Position_longitude'],params['Position_longitude'],5) 850 self.failUnlessAlmostEqual(r['Position_latitude'],params['Position_latitude'],5) 851 self.failUnlessEqual(r['dim'],params['dim']) 852 self.failUnlessEqual(r['FixType'],params['FixType']) 853 self.failUnlessEqual(r['timestamp'],params['timestamp']) 854 self.failUnlessEqual(r['OffPosition'],params['OffPosition']) 855 self.failUnlessEqual(r['RegionalApp'],params['RegionalApp']) 856 self.failUnlessEqual(r['RAIM'],params['RAIM']) 857 self.failUnlessEqual(r['Spare'],params['Spare'])
858
859 -def addMsgOptions(parser):
860 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 861 help='decode a "AidsToNavReport" AIS message') 862 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 863 help='encode a "AidsToNavReport" AIS message') 864 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 865 ,help='Field parameter value [default: %default]') 866 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 867 ,help='Field parameter value [default: %default]') 868 parser.add_option('--type-field', dest='typeField',default=0,metavar='uint',type='int' 869 ,help='Field parameter value [default: %default]') 870 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string' 871 ,help='Field parameter value [default: %default]') 872 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int' 873 ,help='Field parameter value [default: %default]') 874 parser.add_option('--Position_longitude-field', dest='Position_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 875 ,help='Field parameter value [default: %default]') 876 parser.add_option('--Position_latitude-field', dest='Position_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 877 ,help='Field parameter value [default: %default]') 878 parser.add_option('--dim-field', dest='dimField',default=0,metavar='uint',type='int' 879 ,help='Field parameter value [default: %default]') 880 parser.add_option('--FixType-field', dest='FixTypeField',default=0,metavar='uint',type='int' 881 ,help='Field parameter value [default: %default]') 882 parser.add_option('--timestamp-field', dest='timestampField',metavar='uint',type='int' 883 ,help='Field parameter value [default: %default]') 884 parser.add_option('--OffPosition-field', dest='OffPositionField',metavar='bool',type='int' 885 ,help='Field parameter value [default: %default]') 886 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int' 887 ,help='Field parameter value [default: %default]')
888 889 ############################################################ 890 if __name__=='__main__': 891 892 from optparse import OptionParser 893 parser = OptionParser(usage="%prog [options]", 894 version="%prog "+__version__) 895 896 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 897 help='run the documentation tests') 898 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 899 help='run the unit tests') 900 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 901 help='Make the test output verbose') 902 903 # FIX: remove nmea from binary messages. No way to build the whole packet? 904 # FIX: or build the surrounding msg 8 for a broadcast? 905 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 906 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 907 ,default='nmeapayload' 908 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 909 910 911 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 912 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 913 ,default='std' 914 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 915 916 parser.add_option('-o','--output',dest='outputFileName',default=None, 917 help='Name of the python file to write [default: stdout]') 918 919 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 920 choices=fieldList, 921 help='Which fields to include in the output. Currently only for csv output [default: all]') 922 923 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 924 help='Print the field name for csv') 925 926 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 927 help='Print out an sql create command for the table.') 928 929 dbChoices = ('sqlite','postgres') 930 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 931 ,choices=dbChoices,type='choice' 932 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 933 934 addMsgOptions(parser) 935 936 (options,args) = parser.parse_args() 937 success=True 938 939 if options.doctest: 940 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 941 sys.argv= [sys.argv[0]] 942 if options.verbose: sys.argv.append('-v') 943 import doctest 944 numfail,numtests=doctest.testmod() 945 if numfail==0: print 'ok' 946 else: 947 print 'FAILED' 948 success=False 949 950 if not success: sys.exit('Something Failed') 951 del success # Hide success from epydoc 952 953 if options.unittest: 954 sys.argv = [sys.argv[0]] 955 if options.verbose: sys.argv.append('-v') 956 unittest.main() 957 958 outfile = sys.stdout 959 if None!=options.outputFileName: 960 outfile = file(options.outputFileName,'w') 961 962 963 if options.doEncode: 964 # First make sure all non required options are specified 965 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 966 if None==options.UserIDField: parser.error("missing value for UserIDField") 967 if None==options.typeField: parser.error("missing value for typeField") 968 if None==options.nameField: parser.error("missing value for nameField") 969 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField") 970 if None==options.Position_longitudeField: parser.error("missing value for Position_longitudeField") 971 if None==options.Position_latitudeField: parser.error("missing value for Position_latitudeField") 972 if None==options.dimField: parser.error("missing value for dimField") 973 if None==options.FixTypeField: parser.error("missing value for FixTypeField") 974 if None==options.timestampField: parser.error("missing value for timestampField") 975 if None==options.OffPositionField: parser.error("missing value for OffPositionField") 976 if None==options.RAIMField: parser.error("missing value for RAIMField") 977 msgDict={ 978 'MessageID': '21', 979 'RepeatIndicator': options.RepeatIndicatorField, 980 'UserID': options.UserIDField, 981 'type': options.typeField, 982 'name': options.nameField, 983 'PositionAccuracy': options.PositionAccuracyField, 984 'Position_longitude': options.Position_longitudeField, 985 'Position_latitude': options.Position_latitudeField, 986 'dim': options.dimField, 987 'FixType': options.FixTypeField, 988 'timestamp': options.timestampField, 989 'OffPosition': options.OffPositionField, 990 'RegionalApp': '0', 991 'RAIM': options.RAIMField, 992 'Spare': '0', 993 } 994 995 bits = encode(msgDict) 996 if 'binary'==options.ioType: print str(bits) 997 elif 'nmeapayload'==options.ioType: 998 # FIX: figure out if this might be necessary at compile time 999 print "bitLen",len(bits) 1000 bitLen=len(bits) 1001 if bitLen%6!=0: 1002 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 1003 print "result:",binary.bitvectoais6(bits)[0] 1004 1005 1006 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 1007 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 1008 else: sys.exit('ERROR: unknown ioType. Help!') 1009 1010 1011 if options.sqlCreate: 1012 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 1013 1014 if options.printCsvfieldList: 1015 # Make a csv separated list of fields that will be displayed for csv 1016 if None == options.fieldList: options.fieldList = fieldList 1017 import StringIO 1018 buf = StringIO.StringIO() 1019 for field in options.fieldList: 1020 buf.write(field+',') 1021 result = buf.getvalue() 1022 if result[-1] == ',': print result[:-1] 1023 else: print result 1024 1025 if options.doDecode: 1026 for msg in args: 1027 bv = None 1028 1029 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 1030 # Found nmea 1031 # FIX: do checksum 1032 bv = binary.ais6tobitvec(msg.split(',')[5]) 1033 else: # either binary or nmeapayload... expect mostly nmeapayloads 1034 # assumes that an all 0 and 1 string can not be a nmeapayload 1035 binaryMsg=True 1036 for c in msg: 1037 if c not in ('0','1'): 1038 binaryMsg=False 1039 break 1040 if binaryMsg: 1041 bv = BitVector(bitstring=msg) 1042 else: # nmeapayload 1043 bv = binary.ais6tobitvec(msg) 1044 1045 printFields(decode(bv) 1046 ,out=outfile 1047 ,format=options.outputType 1048 ,fieldList=options.fieldList 1049 ,dbType=options.dbType 1050 ) 1051