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-03-31 $'.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 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 695 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
696
697 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
698 ''' 699 Return the sqlhelp object to create the table. 700 701 @param fields: which fields to put in the create. Defaults to all. 702 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 703 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 704 @type addCoastGuardFields: bool 705 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 706 @return: An object that can be used to generate a return 707 @rtype: sqlhelp.create 708 ''' 709 if None == fields: fields = fieldList 710 import sqlhelp 711 c = sqlhelp.create('AidsToNavReport',dbType=dbType) 712 c.addPrimaryKey() 713 if 'MessageID' in fields: c.addInt ('MessageID') 714 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 715 if 'UserID' in fields: c.addInt ('UserID') 716 if 'type' in fields: c.addInt ('type') 717 if 'name' in fields: c.addVarChar('name',20) 718 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy') 719 if 'Position_longitude' in fields: c.addDecimal('Position_longitude',8,5) 720 if 'Position_latitude' in fields: c.addDecimal('Position_latitude',8,5) 721 if 'dim' in fields: c.addInt ('dim') 722 if 'FixType' in fields: c.addInt ('FixType') 723 if 'timestamp' in fields: c.addInt ('timestamp') 724 if 'OffPosition' in fields: c.addBool('OffPosition') 725 if 'RegionalApp' in fields: c.addInt ('RegionalApp') 726 if 'RAIM' in fields: c.addBool('RAIM') 727 if 'Spare' in fields: c.addInt ('Spare') 728 729 if addCoastGuardFields: 730 # c.addInt('cg_rssi') # Relative signal strength indicator 731 # c.addInt('cg_d') # dBm receive strength 732 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 733 # c.addInt('cg_S') # Slot received in 734 # c.addVarChar('cg_x',10) # Idonno 735 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 736 c.addInt('cg_sec') # UTC seconds since the epoch 737 738 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 739 740 return c
741
742 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
743 ''' 744 Return the SQL INSERT command for this message type 745 @param params: dictionary of values keyed by field name 746 @param outfile: file like object to print to. 747 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 748 @return: sql create string 749 @rtype: str 750 751 @see: sqlCreate 752 ''' 753 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
754 755
756 -def sqlInsert(params,extraParams=None,dbType='postgres'):
757 ''' 758 Give the SQL INSERT statement 759 @param params: dict keyed by field name of values 760 @param extraParams: any extra fields that you have created beyond the normal ais message fields 761 @rtype: sqlhelp.insert 762 @return: insert class instance 763 @todo: allow optional type checking of params? 764 @warning: this will take invalid keys happily and do what??? 765 ''' 766 import sqlhelp 767 i = sqlhelp.insert('AidsToNavReport',dbType=dbType) 768 769 if dbType=='postgres': 770 finished = [] 771 for key in params: 772 if key in finished: 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 # Had better be a WKT type like POINT(-88.1 30.321) 782 i.addPostGIS(key,val) 783 finished.append(key) 784 else: 785 # Need to construct the type. 786 pgName = toPgFields[key] 787 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 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 # LATEX SUPPORT 808 ###################################################################### 809
810 -def latexDefinitionTable(outfile=sys.stdout 811 ):
812 ''' 813 Return the LaTeX definition table for this message type 814 @param outfile: file like object to print to. 815 @type outfile: file obj 816 @return: LaTeX table string via the outfile 817 @rtype: str 818 819 ''' 820 o = outfile 821 822 o.write(''' 823 \\begin{table}%[htb] 824 \\centering 825 \\begin{tabular}{|l|c|l|} 826 \\hline 827 Parameter & Number of bits & Description 828 \\\\ \\hline\\hline 829 MessageID & 6 & AIS message number. Must be 21 aka 'F' \\\\ \hline 830 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 831 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline 832 type & 5 & IALA type of aid-to-navigation \\\\ \hline 833 name & 120 & Name of the aid-to-navigation \\\\ \hline 834 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline 835 Position\_longitude & 28 & Location of the vessel East West location \\\\ \hline 836 Position\_latitude & 27 & Location of the vessel North South location \\\\ \hline 837 dim & 30 & FIX: break this out. \\\\ \hline 838 FixType & 4 & Type of electronic position fixing device \\\\ \hline 839 timestamp & 6 & UTC second when report was generated \\\\ \hline 840 OffPosition & 1 & True when the AtoN is off station \\\\ \hline 841 RegionalApp & 8 & Should be set to zero \\\\ \hline 842 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline 843 Spare & 3 & Not Used\\\\ \\hline \\hline 844 Total bits & 272 & Appears to take 2 slots with 152 pad bits to fill the last slot \\\\ \\hline 845 \\end{tabular} 846 \\caption{AIS message number 21: Used by a station mounted on an aid-to-navigation} 847 \\label{tab:AidsToNavReport} 848 \\end{table} 849 ''')
850 851 852 ###################################################################### 853 # UNIT TESTING 854 ###################################################################### 855 import unittest
856 -def testParams():
857 '''Return a params file base on the testvalue tags. 858 @rtype: dict 859 @return: params based on testvalue tags 860 ''' 861 params = {} 862 params['MessageID'] = 21 863 params['RepeatIndicator'] = 1 864 params['UserID'] = 1193046 865 params['type'] = 28 866 params['name'] = 'BUNCH OF ROCKS ATON@' 867 params['PositionAccuracy'] = 1 868 params['Position_longitude'] = Decimal('-122.16328055555556') 869 params['Position_latitude'] = Decimal('37.424458333333334') 870 params['dim'] = 0 871 params['FixType'] = 2 872 params['timestamp'] = 62 873 params['OffPosition'] = False 874 params['RegionalApp'] = 0 875 params['RAIM'] = False 876 params['Spare'] = 0 877 878 return params
879
880 -class TestAidsToNavReport(unittest.TestCase):
881 '''Use testvalue tag text from each type to build test case the AidsToNavReport message'''
882 - def testEncodeDecode(self):
883 884 params = testParams() 885 bits = encode(params) 886 r = decode(bits) 887 888 # Check that each parameter came through ok. 889 self.failUnlessEqual(r['MessageID'],params['MessageID']) 890 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 891 self.failUnlessEqual(r['UserID'],params['UserID']) 892 self.failUnlessEqual(r['type'],params['type']) 893 self.failUnlessEqual(r['name'],params['name']) 894 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy']) 895 self.failUnlessAlmostEqual(r['Position_longitude'],params['Position_longitude'],5) 896 self.failUnlessAlmostEqual(r['Position_latitude'],params['Position_latitude'],5) 897 self.failUnlessEqual(r['dim'],params['dim']) 898 self.failUnlessEqual(r['FixType'],params['FixType']) 899 self.failUnlessEqual(r['timestamp'],params['timestamp']) 900 self.failUnlessEqual(r['OffPosition'],params['OffPosition']) 901 self.failUnlessEqual(r['RegionalApp'],params['RegionalApp']) 902 self.failUnlessEqual(r['RAIM'],params['RAIM']) 903 self.failUnlessEqual(r['Spare'],params['Spare'])
904
905 -def addMsgOptions(parser):
906 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 907 help='decode a "AidsToNavReport" AIS message') 908 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 909 help='encode a "AidsToNavReport" AIS message') 910 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 911 ,help='Field parameter value [default: %default]') 912 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 913 ,help='Field parameter value [default: %default]') 914 parser.add_option('--type-field', dest='typeField',default=0,metavar='uint',type='int' 915 ,help='Field parameter value [default: %default]') 916 parser.add_option('--name-field', dest='nameField',default='@@@@@@@@@@@@@@@@@@@@',metavar='aisstr6',type='string' 917 ,help='Field parameter value [default: %default]') 918 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int' 919 ,help='Field parameter value [default: %default]') 920 parser.add_option('--Position_longitude-field', dest='Position_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 921 ,help='Field parameter value [default: %default]') 922 parser.add_option('--Position_latitude-field', dest='Position_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 923 ,help='Field parameter value [default: %default]') 924 parser.add_option('--dim-field', dest='dimField',default=0,metavar='uint',type='int' 925 ,help='Field parameter value [default: %default]') 926 parser.add_option('--FixType-field', dest='FixTypeField',default=0,metavar='uint',type='int' 927 ,help='Field parameter value [default: %default]') 928 parser.add_option('--timestamp-field', dest='timestampField',metavar='uint',type='int' 929 ,help='Field parameter value [default: %default]') 930 parser.add_option('--OffPosition-field', dest='OffPositionField',metavar='bool',type='int' 931 ,help='Field parameter value [default: %default]') 932 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int' 933 ,help='Field parameter value [default: %default]')
934 935 ############################################################ 936 if __name__=='__main__': 937 938 from optparse import OptionParser 939 parser = OptionParser(usage="%prog [options]", 940 version="%prog "+__version__) 941 942 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 943 help='run the documentation tests') 944 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 945 help='run the unit tests') 946 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 947 help='Make the test output verbose') 948 949 # FIX: remove nmea from binary messages. No way to build the whole packet? 950 # FIX: or build the surrounding msg 8 for a broadcast? 951 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 952 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 953 ,default='nmeapayload' 954 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 955 956 957 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 958 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 959 ,default='std' 960 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 961 962 parser.add_option('-o','--output',dest='outputFileName',default=None, 963 help='Name of the python file to write [default: stdout]') 964 965 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 966 choices=fieldList, 967 help='Which fields to include in the output. Currently only for csv output [default: all]') 968 969 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 970 help='Print the field name for csv') 971 972 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 973 help='Print out an sql create command for the table.') 974 975 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 976 help='Print a LaTeX table of the type') 977 978 dbChoices = ('sqlite','postgres') 979 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 980 ,choices=dbChoices,type='choice' 981 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 982 983 addMsgOptions(parser) 984 985 (options,args) = parser.parse_args() 986 success=True 987 988 if options.doctest: 989 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 990 sys.argv= [sys.argv[0]] 991 if options.verbose: sys.argv.append('-v') 992 import doctest 993 numfail,numtests=doctest.testmod() 994 if numfail==0: print 'ok' 995 else: 996 print 'FAILED' 997 success=False 998 999 if not success: sys.exit('Something Failed') 1000 del success # Hide success from epydoc 1001 1002 if options.unittest: 1003 sys.argv = [sys.argv[0]] 1004 if options.verbose: sys.argv.append('-v') 1005 unittest.main() 1006 1007 outfile = sys.stdout 1008 if None!=options.outputFileName: 1009 outfile = file(options.outputFileName,'w') 1010 1011 1012 if options.doEncode: 1013 # First make sure all non required options are specified 1014 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 1015 if None==options.UserIDField: parser.error("missing value for UserIDField") 1016 if None==options.typeField: parser.error("missing value for typeField") 1017 if None==options.nameField: parser.error("missing value for nameField") 1018 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField") 1019 if None==options.Position_longitudeField: parser.error("missing value for Position_longitudeField") 1020 if None==options.Position_latitudeField: parser.error("missing value for Position_latitudeField") 1021 if None==options.dimField: parser.error("missing value for dimField") 1022 if None==options.FixTypeField: parser.error("missing value for FixTypeField") 1023 if None==options.timestampField: parser.error("missing value for timestampField") 1024 if None==options.OffPositionField: parser.error("missing value for OffPositionField") 1025 if None==options.RAIMField: parser.error("missing value for RAIMField") 1026 msgDict={ 1027 'MessageID': '21', 1028 'RepeatIndicator': options.RepeatIndicatorField, 1029 'UserID': options.UserIDField, 1030 'type': options.typeField, 1031 'name': options.nameField, 1032 'PositionAccuracy': options.PositionAccuracyField, 1033 'Position_longitude': options.Position_longitudeField, 1034 'Position_latitude': options.Position_latitudeField, 1035 'dim': options.dimField, 1036 'FixType': options.FixTypeField, 1037 'timestamp': options.timestampField, 1038 'OffPosition': options.OffPositionField, 1039 'RegionalApp': '0', 1040 'RAIM': options.RAIMField, 1041 'Spare': '0', 1042 } 1043 1044 bits = encode(msgDict) 1045 if 'binary'==options.ioType: print str(bits) 1046 elif 'nmeapayload'==options.ioType: 1047 # FIX: figure out if this might be necessary at compile time 1048 print "bitLen",len(bits) 1049 bitLen=len(bits) 1050 if bitLen%6!=0: 1051 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 1052 print "result:",binary.bitvectoais6(bits)[0] 1053 1054 1055 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 1056 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 1057 else: sys.exit('ERROR: unknown ioType. Help!') 1058 1059 1060 if options.sqlCreate: 1061 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 1062 1063 if options.latexDefinitionTable: 1064 latexDefinitionTable(outfile) 1065 1066 if options.printCsvfieldList: 1067 # Make a csv separated list of fields that will be displayed for csv 1068 if None == options.fieldList: options.fieldList = fieldList 1069 import StringIO 1070 buf = StringIO.StringIO() 1071 for field in options.fieldList: 1072 buf.write(field+',') 1073 result = buf.getvalue() 1074 if result[-1] == ',': print result[:-1] 1075 else: print result 1076 1077 if options.doDecode: 1078 for msg in args: 1079 bv = None 1080 1081 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 1082 # Found nmea 1083 # FIX: do checksum 1084 bv = binary.ais6tobitvec(msg.split(',')[5]) 1085 else: # either binary or nmeapayload... expect mostly nmeapayloads 1086 # assumes that an all 0 and 1 string can not be a nmeapayload 1087 binaryMsg=True 1088 for c in msg: 1089 if c not in ('0','1'): 1090 binaryMsg=False 1091 break 1092 if binaryMsg: 1093 bv = BitVector(bitstring=msg) 1094 else: # nmeapayload 1095 bv = binary.ais6tobitvec(msg) 1096 1097 printFields(decode(bv) 1098 ,out=outfile 1099 ,format=options.outputType 1100 ,fieldList=options.fieldList 1101 ,dbType=options.dbType 1102 ) 1103