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

Source Code for Module ais.ais_msg_3

   1  #!/usr/bin/env python 
   2   
   3  __version__ = '$Revision: 4791 $'.split()[1] 
   4  __date__ = '$Date: 2008-01-09 $'.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          'NavigationStatus', 
  54          'ROT', 
  55          'SOG', 
  56          'PositionAccuracy', 
  57          'longitude', 
  58          'latitude', 
  59          'COG', 
  60          'TrueHeading', 
  61          'TimeStamp', 
  62          'RegionalReserved', 
  63          'Spare', 
  64          'RAIM', 
  65          'state_syncstate', 
  66          'state_slottimeout', 
  67          'state_slotoffset', 
  68  ) 
  69   
  70  fieldListPostgres = ( 
  71          'MessageID', 
  72          'RepeatIndicator', 
  73          'UserID', 
  74          'NavigationStatus', 
  75          'ROT', 
  76          'SOG', 
  77          'PositionAccuracy', 
  78          'Position',     # PostGIS data type 
  79          'COG', 
  80          'TrueHeading', 
  81          'TimeStamp', 
  82          'RegionalReserved', 
  83          'Spare', 
  84          'RAIM', 
  85          'state_syncstate', 
  86          'state_slottimeout', 
  87          'state_slotoffset', 
  88  ) 
  89   
  90  toPgFields = { 
  91          'longitude':'Position', 
  92          'latitude':'Position', 
  93  } 
  94  ''' 
  95  Go to the Postgis field names from the straight field name 
  96  ''' 
  97   
  98  fromPgFields = { 
  99          'Position':('longitude','latitude',), 
 100  } 
 101  ''' 
 102  Go from the Postgis field names to the straight field name 
 103  ''' 
 104   
 105  pgTypes = { 
 106          'Position':'POINT', 
 107  } 
 108  ''' 
 109  Lookup table for each postgis field name to get its type. 
 110  ''' 
 111   
112 -def encode(params, validate=False):
113 '''Create a position binary message payload to pack into an AIS Msg position. 114 115 Fields in params: 116 - MessageID(uint): AIS message number. Must be 1 (field automatically set to "3") 117 - RepeatIndicator(uint): Indicated how many times a message has been repeated 118 - UserID(uint): Unique ship identification number (MMSI) 119 - NavigationStatus(uint): What is the vessel doing 120 - ROT(int): RateOfTurn 121 - SOG(udecimal): Speed over ground 122 - PositionAccuracy(uint): Accuracy of positioning fixes 123 - longitude(decimal): Location of the vessel East West location 124 - latitude(decimal): Location of the vessel North South location 125 - COG(udecimal): Course over ground 126 - TrueHeading(uint): True heading (relative to true North) 127 - TimeStamp(uint): UTC second when the report was generated 128 - RegionalReserved(uint): Reserved for definition by a regional authority. (field automatically set to "0") 129 - Spare(uint): Not used. Should be set to zero. (field automatically set to "0") 130 - RAIM(bool): Receiver autonomous integrity monitoring flag 131 - state_syncstate(uint): Communications State - SOTDMA Sycronization state 132 - state_slottimeout(uint): Communications State - SOTDMA Frames remaining until a new slot is selected 133 - state_slotoffset(uint): Communications State - SOTDMA In what slot will the next transmission occur. BROKEN 134 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 135 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 136 @rtype: BitVector 137 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 138 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 139 ''' 140 141 bvList = [] 142 bvList.append(binary.setBitVectorSize(BitVector(intVal=3),6)) 143 if 'RepeatIndicator' in params: 144 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 145 else: 146 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 147 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 148 if 'NavigationStatus' in params: 149 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['NavigationStatus']),4)) 150 else: 151 bvList.append(binary.setBitVectorSize(BitVector(intVal=15),4)) 152 if 'ROT' in params: 153 bvList.append(binary.bvFromSignedInt(params['ROT'],8)) 154 else: 155 bvList.append(binary.bvFromSignedInt(-128,8)) 156 if 'SOG' in params: 157 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['SOG'])*Decimal('10')))),10)) 158 else: 159 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)),10)) 160 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['PositionAccuracy']),1)) 161 if 'longitude' in params: 162 bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28)) 163 else: 164 bvList.append(binary.bvFromSignedInt(108600000,28)) 165 if 'latitude' in params: 166 bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27)) 167 else: 168 bvList.append(binary.bvFromSignedInt(54600000,27)) 169 if 'COG' in params: 170 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['COG'])*Decimal('10')))),12)) 171 else: 172 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(3600)),12)) 173 if 'TrueHeading' in params: 174 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TrueHeading']),9)) 175 else: 176 bvList.append(binary.setBitVectorSize(BitVector(intVal=511),9)) 177 if 'TimeStamp' in params: 178 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TimeStamp']),6)) 179 else: 180 bvList.append(binary.setBitVectorSize(BitVector(intVal=60),6)) 181 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4)) 182 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),1)) 183 if params["RAIM"]: bvList.append(TrueBV) 184 else: bvList.append(FalseBV) 185 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['state_syncstate']),2)) 186 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['state_slottimeout']),3)) 187 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['state_slotoffset']),14)) 188 189 return binary.joinBV(bvList)
190
191 -def decode(bv, validate=False):
192 '''Unpack a position message 193 194 Fields in params: 195 - MessageID(uint): AIS message number. Must be 1 (field automatically set to "3") 196 - RepeatIndicator(uint): Indicated how many times a message has been repeated 197 - UserID(uint): Unique ship identification number (MMSI) 198 - NavigationStatus(uint): What is the vessel doing 199 - ROT(int): RateOfTurn 200 - SOG(udecimal): Speed over ground 201 - PositionAccuracy(uint): Accuracy of positioning fixes 202 - longitude(decimal): Location of the vessel East West location 203 - latitude(decimal): Location of the vessel North South location 204 - COG(udecimal): Course over ground 205 - TrueHeading(uint): True heading (relative to true North) 206 - TimeStamp(uint): UTC second when the report was generated 207 - RegionalReserved(uint): Reserved for definition by a regional authority. (field automatically set to "0") 208 - Spare(uint): Not used. Should be set to zero. (field automatically set to "0") 209 - RAIM(bool): Receiver autonomous integrity monitoring flag 210 - state_syncstate(uint): Communications State - SOTDMA Sycronization state 211 - state_slottimeout(uint): Communications State - SOTDMA Frames remaining until a new slot is selected 212 - state_slotoffset(uint): Communications State - SOTDMA In what slot will the next transmission occur. BROKEN 213 @type bv: BitVector 214 @param bv: Bits defining a message 215 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 216 @rtype: dict 217 @return: params 218 ''' 219 220 #Would be nice to check the bit count here.. 221 #if validate: 222 # assert (len(bv)==FIX: SOME NUMBER) 223 r = {} 224 r['MessageID']=3 225 r['RepeatIndicator']=int(bv[6:8]) 226 r['UserID']=int(bv[8:38]) 227 r['NavigationStatus']=int(bv[38:42]) 228 r['ROT']=binary.signedIntFromBV(bv[42:50]) 229 r['SOG']=Decimal(int(bv[50:60]))/Decimal('10') 230 r['PositionAccuracy']=int(bv[60:61]) 231 r['longitude']=Decimal(binary.signedIntFromBV(bv[61:89]))/Decimal('600000') 232 r['latitude']=Decimal(binary.signedIntFromBV(bv[89:116]))/Decimal('600000') 233 r['COG']=Decimal(int(bv[116:128]))/Decimal('10') 234 r['TrueHeading']=int(bv[128:137]) 235 r['TimeStamp']=int(bv[137:143]) 236 r['RegionalReserved']=0 237 r['Spare']=0 238 r['RAIM']=bool(int(bv[148:149])) 239 r['state_syncstate']=int(bv[149:151]) 240 r['state_slottimeout']=int(bv[151:154]) 241 r['state_slotoffset']=int(bv[154:168]) 242 return r
243
244 -def decodeMessageID(bv, validate=False):
245 return 3
246
247 -def decodeRepeatIndicator(bv, validate=False):
248 return int(bv[6:8])
249
250 -def decodeUserID(bv, validate=False):
251 return int(bv[8:38])
252
253 -def decodeNavigationStatus(bv, validate=False):
254 return int(bv[38:42])
255
256 -def decodeROT(bv, validate=False):
257 return binary.signedIntFromBV(bv[42:50])
258
259 -def decodeSOG(bv, validate=False):
260 return Decimal(int(bv[50:60]))/Decimal('10')
261
262 -def decodePositionAccuracy(bv, validate=False):
263 return int(bv[60:61])
264
265 -def decodelongitude(bv, validate=False):
266 return Decimal(binary.signedIntFromBV(bv[61:89]))/Decimal('600000')
267
268 -def decodelatitude(bv, validate=False):
269 return Decimal(binary.signedIntFromBV(bv[89:116]))/Decimal('600000')
270
271 -def decodeCOG(bv, validate=False):
272 return Decimal(int(bv[116:128]))/Decimal('10')
273
274 -def decodeTrueHeading(bv, validate=False):
275 return int(bv[128:137])
276
277 -def decodeTimeStamp(bv, validate=False):
278 return int(bv[137:143])
279
280 -def decodeRegionalReserved(bv, validate=False):
281 return 0
282
283 -def decodeSpare(bv, validate=False):
284 return 0
285
286 -def decodeRAIM(bv, validate=False):
287 return bool(int(bv[148:149]))
288
289 -def decodestate_syncstate(bv, validate=False):
290 return int(bv[149:151])
291
292 -def decodestate_slottimeout(bv, validate=False):
293 return int(bv[151:154])
294
295 -def decodestate_slotoffset(bv, validate=False):
296 return int(bv[154:168])
297 298
299 -def printHtml(params, out=sys.stdout):
300 out.write("<h3>position</h3>\n") 301 out.write("<table border=\"1\">\n") 302 out.write("<tr bgcolor=\"orange\">\n") 303 out.write("<th align=\"left\">Field Name</th>\n") 304 out.write("<th align=\"left\">Type</th>\n") 305 out.write("<th align=\"left\">Value</th>\n") 306 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 307 out.write("<th align=\"left\">Units</th>\n") 308 out.write("\n") 309 out.write("<tr>\n") 310 out.write("<td>MessageID</td>\n") 311 out.write("<td>uint</td>\n") 312 if 'MessageID' in params: 313 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 314 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 315 out.write("</tr>\n") 316 out.write("\n") 317 out.write("<tr>\n") 318 out.write("<td>RepeatIndicator</td>\n") 319 out.write("<td>uint</td>\n") 320 if 'RepeatIndicator' in params: 321 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 322 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 323 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 324 else: 325 out.write("<td><i>Missing LUT entry</i></td>") 326 out.write("</tr>\n") 327 out.write("\n") 328 out.write("<tr>\n") 329 out.write("<td>UserID</td>\n") 330 out.write("<td>uint</td>\n") 331 if 'UserID' in params: 332 out.write(" <td>"+str(params['UserID'])+"</td>\n") 333 out.write(" <td>"+str(params['UserID'])+"</td>\n") 334 out.write("</tr>\n") 335 out.write("\n") 336 out.write("<tr>\n") 337 out.write("<td>NavigationStatus</td>\n") 338 out.write("<td>uint</td>\n") 339 if 'NavigationStatus' in params: 340 out.write(" <td>"+str(params['NavigationStatus'])+"</td>\n") 341 if str(params['NavigationStatus']) in NavigationStatusDecodeLut: 342 out.write("<td>"+NavigationStatusDecodeLut[str(params['NavigationStatus'])]+"</td>") 343 else: 344 out.write("<td><i>Missing LUT entry</i></td>") 345 out.write("</tr>\n") 346 out.write("\n") 347 out.write("<tr>\n") 348 out.write("<td>ROT</td>\n") 349 out.write("<td>int</td>\n") 350 if 'ROT' in params: 351 out.write(" <td>"+str(params['ROT'])+"</td>\n") 352 out.write(" <td>"+str(params['ROT'])+"</td>\n") 353 out.write("<td>4.733*sqrt(val) degrees/min</td>\n") 354 out.write("</tr>\n") 355 out.write("\n") 356 out.write("<tr>\n") 357 out.write("<td>SOG</td>\n") 358 out.write("<td>udecimal</td>\n") 359 if 'SOG' in params: 360 out.write(" <td>"+str(params['SOG'])+"</td>\n") 361 if str(params['SOG']) in SOGDecodeLut: 362 out.write("<td>"+SOGDecodeLut[str(params['SOG'])]+"</td>") 363 else: 364 out.write("<td><i>Missing LUT entry</i></td>") 365 out.write("<td>knots</td>\n") 366 out.write("</tr>\n") 367 out.write("\n") 368 out.write("<tr>\n") 369 out.write("<td>PositionAccuracy</td>\n") 370 out.write("<td>uint</td>\n") 371 if 'PositionAccuracy' in params: 372 out.write(" <td>"+str(params['PositionAccuracy'])+"</td>\n") 373 if str(params['PositionAccuracy']) in PositionAccuracyDecodeLut: 374 out.write("<td>"+PositionAccuracyDecodeLut[str(params['PositionAccuracy'])]+"</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>longitude</td>\n") 381 out.write("<td>decimal</td>\n") 382 if 'longitude' in params: 383 out.write(" <td>"+str(params['longitude'])+"</td>\n") 384 out.write(" <td>"+str(params['longitude'])+"</td>\n") 385 out.write("<td>degrees</td>\n") 386 out.write("</tr>\n") 387 out.write("\n") 388 out.write("<tr>\n") 389 out.write("<td>latitude</td>\n") 390 out.write("<td>decimal</td>\n") 391 if 'latitude' in params: 392 out.write(" <td>"+str(params['latitude'])+"</td>\n") 393 out.write(" <td>"+str(params['latitude'])+"</td>\n") 394 out.write("<td>degrees</td>\n") 395 out.write("</tr>\n") 396 out.write("\n") 397 out.write("<tr>\n") 398 out.write("<td>COG</td>\n") 399 out.write("<td>udecimal</td>\n") 400 if 'COG' in params: 401 out.write(" <td>"+str(params['COG'])+"</td>\n") 402 out.write(" <td>"+str(params['COG'])+"</td>\n") 403 out.write("<td>degrees</td>\n") 404 out.write("</tr>\n") 405 out.write("\n") 406 out.write("<tr>\n") 407 out.write("<td>TrueHeading</td>\n") 408 out.write("<td>uint</td>\n") 409 if 'TrueHeading' in params: 410 out.write(" <td>"+str(params['TrueHeading'])+"</td>\n") 411 out.write(" <td>"+str(params['TrueHeading'])+"</td>\n") 412 out.write("<td>degrees</td>\n") 413 out.write("</tr>\n") 414 out.write("\n") 415 out.write("<tr>\n") 416 out.write("<td>TimeStamp</td>\n") 417 out.write("<td>uint</td>\n") 418 if 'TimeStamp' in params: 419 out.write(" <td>"+str(params['TimeStamp'])+"</td>\n") 420 if str(params['TimeStamp']) in TimeStampDecodeLut: 421 out.write("<td>"+TimeStampDecodeLut[str(params['TimeStamp'])]+"</td>") 422 else: 423 out.write("<td><i>Missing LUT entry</i></td>") 424 out.write("<td>seconds</td>\n") 425 out.write("</tr>\n") 426 out.write("\n") 427 out.write("<tr>\n") 428 out.write("<td>RegionalReserved</td>\n") 429 out.write("<td>uint</td>\n") 430 if 'RegionalReserved' in params: 431 out.write(" <td>"+str(params['RegionalReserved'])+"</td>\n") 432 out.write(" <td>"+str(params['RegionalReserved'])+"</td>\n") 433 out.write("</tr>\n") 434 out.write("\n") 435 out.write("<tr>\n") 436 out.write("<td>Spare</td>\n") 437 out.write("<td>uint</td>\n") 438 if 'Spare' in params: 439 out.write(" <td>"+str(params['Spare'])+"</td>\n") 440 out.write(" <td>"+str(params['Spare'])+"</td>\n") 441 out.write("</tr>\n") 442 out.write("\n") 443 out.write("<tr>\n") 444 out.write("<td>RAIM</td>\n") 445 out.write("<td>bool</td>\n") 446 if 'RAIM' in params: 447 out.write(" <td>"+str(params['RAIM'])+"</td>\n") 448 if str(params['RAIM']) in RAIMDecodeLut: 449 out.write("<td>"+RAIMDecodeLut[str(params['RAIM'])]+"</td>") 450 else: 451 out.write("<td><i>Missing LUT entry</i></td>") 452 out.write("</tr>\n") 453 out.write("\n") 454 out.write("<tr>\n") 455 out.write("<td>state_syncstate</td>\n") 456 out.write("<td>uint</td>\n") 457 if 'state_syncstate' in params: 458 out.write(" <td>"+str(params['state_syncstate'])+"</td>\n") 459 if str(params['state_syncstate']) in state_syncstateDecodeLut: 460 out.write("<td>"+state_syncstateDecodeLut[str(params['state_syncstate'])]+"</td>") 461 else: 462 out.write("<td><i>Missing LUT entry</i></td>") 463 out.write("</tr>\n") 464 out.write("\n") 465 out.write("<tr>\n") 466 out.write("<td>state_slottimeout</td>\n") 467 out.write("<td>uint</td>\n") 468 if 'state_slottimeout' in params: 469 out.write(" <td>"+str(params['state_slottimeout'])+"</td>\n") 470 if str(params['state_slottimeout']) in state_slottimeoutDecodeLut: 471 out.write("<td>"+state_slottimeoutDecodeLut[str(params['state_slottimeout'])]+"</td>") 472 else: 473 out.write("<td><i>Missing LUT entry</i></td>") 474 out.write("<td>frames</td>\n") 475 out.write("</tr>\n") 476 out.write("\n") 477 out.write("<tr>\n") 478 out.write("<td>state_slotoffset</td>\n") 479 out.write("<td>uint</td>\n") 480 if 'state_slotoffset' in params: 481 out.write(" <td>"+str(params['state_slotoffset'])+"</td>\n") 482 out.write(" <td>"+str(params['state_slotoffset'])+"</td>\n") 483 out.write("</tr>\n") 484 out.write("</table>\n")
485 486
487 -def printKml(params, out=sys.stdout):
488 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer''' 489 out.write("\ <Placemark>\n") 490 out.write("\t <name>"+str(params['UserID'])+"</name>\n") 491 out.write("\t\t<description>\n") 492 import StringIO 493 buf = StringIO.StringIO() 494 printHtml(params,buf) 495 import cgi 496 out.write(cgi.escape(buf.getvalue())) 497 out.write("\t\t</description>\n") 498 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n") 499 out.write("\t\t<Point>\n") 500 out.write("\t\t\t<coordinates>") 501 out.write(str(params['longitude'])) 502 out.write(',') 503 out.write(str(params['latitude'])) 504 out.write(",0</coordinates>\n") 505 out.write("\t\t</Point>\n") 506 out.write("\t</Placemark>\n")
507
508 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
509 '''Print a position message to stdout. 510 511 Fields in params: 512 - MessageID(uint): AIS message number. Must be 1 (field automatically set to "3") 513 - RepeatIndicator(uint): Indicated how many times a message has been repeated 514 - UserID(uint): Unique ship identification number (MMSI) 515 - NavigationStatus(uint): What is the vessel doing 516 - ROT(int): RateOfTurn 517 - SOG(udecimal): Speed over ground 518 - PositionAccuracy(uint): Accuracy of positioning fixes 519 - longitude(decimal): Location of the vessel East West location 520 - latitude(decimal): Location of the vessel North South location 521 - COG(udecimal): Course over ground 522 - TrueHeading(uint): True heading (relative to true North) 523 - TimeStamp(uint): UTC second when the report was generated 524 - RegionalReserved(uint): Reserved for definition by a regional authority. (field automatically set to "0") 525 - Spare(uint): Not used. Should be set to zero. (field automatically set to "0") 526 - RAIM(bool): Receiver autonomous integrity monitoring flag 527 - state_syncstate(uint): Communications State - SOTDMA Sycronization state 528 - state_slottimeout(uint): Communications State - SOTDMA Frames remaining until a new slot is selected 529 - state_slotoffset(uint): Communications State - SOTDMA In what slot will the next transmission occur. BROKEN 530 @param params: Dictionary of field names/values. 531 @param out: File like object to write to 532 @rtype: stdout 533 @return: text to out 534 ''' 535 536 if 'std'==format: 537 out.write("position:\n") 538 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 539 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 540 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 541 if 'NavigationStatus' in params: out.write(" NavigationStatus: "+str(params['NavigationStatus'])+"\n") 542 if 'ROT' in params: out.write(" ROT: "+str(params['ROT'])+"\n") 543 if 'SOG' in params: out.write(" SOG: "+str(params['SOG'])+"\n") 544 if 'PositionAccuracy' in params: out.write(" PositionAccuracy: "+str(params['PositionAccuracy'])+"\n") 545 if 'longitude' in params: out.write(" longitude: "+str(params['longitude'])+"\n") 546 if 'latitude' in params: out.write(" latitude: "+str(params['latitude'])+"\n") 547 if 'COG' in params: out.write(" COG: "+str(params['COG'])+"\n") 548 if 'TrueHeading' in params: out.write(" TrueHeading: "+str(params['TrueHeading'])+"\n") 549 if 'TimeStamp' in params: out.write(" TimeStamp: "+str(params['TimeStamp'])+"\n") 550 if 'RegionalReserved' in params: out.write(" RegionalReserved: "+str(params['RegionalReserved'])+"\n") 551 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 552 if 'RAIM' in params: out.write(" RAIM: "+str(params['RAIM'])+"\n") 553 if 'state_syncstate' in params: out.write(" state_syncstate: "+str(params['state_syncstate'])+"\n") 554 if 'state_slottimeout' in params: out.write(" state_slottimeout: "+str(params['state_slottimeout'])+"\n") 555 if 'state_slotoffset' in params: out.write(" state_slotoffset: "+str(params['state_slotoffset'])+"\n") 556 elif 'csv'==format: 557 if None == options.fieldList: 558 options.fieldList = fieldList 559 needComma = False; 560 for field in fieldList: 561 if needComma: out.write(',') 562 needComma = True 563 if field in params: 564 out.write(str(params[field])) 565 # else: leave it empty 566 out.write("\n") 567 elif 'html'==format: 568 printHtml(params,out) 569 elif 'sql'==format: 570 sqlInsertStr(params,out,dbType=dbType) 571 elif 'kml'==format: 572 printKml(params,out) 573 elif 'kml-full'==format: 574 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") 575 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n") 576 out.write("<Document>\n") 577 out.write(" <name>position</name>\n") 578 printKml(params,out) 579 out.write("</Document>\n") 580 out.write("</kml>\n") 581 else: 582 print "ERROR: unknown format:",format 583 assert False 584 585 return # Nothing to return
586 587 RepeatIndicatorEncodeLut = { 588 'default':'0', 589 'do not repeat any more':'3', 590 } #RepeatIndicatorEncodeLut 591 592 RepeatIndicatorDecodeLut = { 593 '0':'default', 594 '3':'do not repeat any more', 595 } # RepeatIndicatorEncodeLut 596 597 NavigationStatusEncodeLut = { 598 'under way using engine':'0', 599 'at anchor':'1', 600 'not under command':'2', 601 'restricted maneuverability':'3', 602 'constrained by her draught':'4', 603 'moored':'5', 604 'aground':'6', 605 'engaged in fishing':'7', 606 'under way sailing':'8', 607 'reserved for future use (hazmat)':'9', 608 'reserved for future use':'10', 609 'reserved for future use':'11', 610 'reserved for future use':'12', 611 'reserved for future use':'13', 612 'reserved for future use':'14', 613 'not defined = default':'15', 614 } #NavigationStatusEncodeLut 615 616 NavigationStatusDecodeLut = { 617 '0':'under way using engine', 618 '1':'at anchor', 619 '2':'not under command', 620 '3':'restricted maneuverability', 621 '4':'constrained by her draught', 622 '5':'moored', 623 '6':'aground', 624 '7':'engaged in fishing', 625 '8':'under way sailing', 626 '9':'reserved for future use (hazmat)', 627 '10':'reserved for future use', 628 '11':'reserved for future use', 629 '12':'reserved for future use', 630 '13':'reserved for future use', 631 '14':'reserved for future use', 632 '15':'not defined = default', 633 } # NavigationStatusEncodeLut 634 635 SOGEncodeLut = { 636 '102.2 knots or higher':'102.2', 637 } #SOGEncodeLut 638 639 SOGDecodeLut = { 640 '102.2':'102.2 knots or higher', 641 } # SOGEncodeLut 642 643 PositionAccuracyEncodeLut = { 644 'low (greater than 10 m)':'0', 645 'high (less than 10 m)':'1', 646 } #PositionAccuracyEncodeLut 647 648 PositionAccuracyDecodeLut = { 649 '0':'low (greater than 10 m)', 650 '1':'high (less than 10 m)', 651 } # PositionAccuracyEncodeLut 652 653 TimeStampEncodeLut = { 654 'not available/default':'60', 655 'manual input':'61', 656 'dead reckoning':'62', 657 'inoperative':'63', 658 } #TimeStampEncodeLut 659 660 TimeStampDecodeLut = { 661 '60':'not available/default', 662 '61':'manual input', 663 '62':'dead reckoning', 664 '63':'inoperative', 665 } # TimeStampEncodeLut 666 667 RAIMEncodeLut = { 668 'not in use':'False', 669 'in use':'True', 670 } #RAIMEncodeLut 671 672 RAIMDecodeLut = { 673 'False':'not in use', 674 'True':'in use', 675 } # RAIMEncodeLut 676 677 state_syncstateEncodeLut = { 678 'UTC direct':'0', 679 'UTC indirect':'1', 680 'synchronized to a base station':'2', 681 'synchronized to another station':'3', 682 } #state_syncstateEncodeLut 683 684 state_syncstateDecodeLut = { 685 '0':'UTC direct', 686 '1':'UTC indirect', 687 '2':'synchronized to a base station', 688 '3':'synchronized to another station', 689 } # state_syncstateEncodeLut 690 691 state_slottimeoutEncodeLut = { 692 'Last frame in this slot':'0', 693 '1 frames left':'1', 694 '2 frames left':'2', 695 '3 frames left':'3', 696 '4 frames left':'4', 697 '5 frames left':'5', 698 '6 frames left':'6', 699 '7 frames left':'7', 700 } #state_slottimeoutEncodeLut 701 702 state_slottimeoutDecodeLut = { 703 '0':'Last frame in this slot', 704 '1':'1 frames left', 705 '2':'2 frames left', 706 '3':'3 frames left', 707 '4':'4 frames left', 708 '5':'5 frames left', 709 '6':'6 frames left', 710 '7':'7 frames left', 711 } # state_slottimeoutEncodeLut 712 713 ###################################################################### 714 # SQL SUPPORT 715 ###################################################################### 716 717 dbTableName='position' 718 'Database table name' 719
720 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None 721 ,addCoastGuardFields=True 722 ,dbType='postgres' 723 ):
724 ''' 725 Return the SQL CREATE command for this message type 726 @param outfile: file like object to print to. 727 @param fields: which fields to put in the create. Defaults to all. 728 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 729 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 730 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 731 @type addCoastGuardFields: bool 732 @return: sql create string 733 @rtype: str 734 735 @see: sqlCreate 736 ''' 737 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 738 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
739
740 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
741 ''' 742 Return the sqlhelp object to create the table. 743 744 @param fields: which fields to put in the create. Defaults to all. 745 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 746 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 747 @type addCoastGuardFields: bool 748 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 749 @return: An object that can be used to generate a return 750 @rtype: sqlhelp.create 751 ''' 752 if None == fields: fields = fieldList 753 import sqlhelp 754 c = sqlhelp.create('position',dbType=dbType) 755 c.addPrimaryKey() 756 if 'MessageID' in fields: c.addInt ('MessageID') 757 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 758 if 'UserID' in fields: c.addInt ('UserID') 759 if 'NavigationStatus' in fields: c.addInt ('NavigationStatus') 760 if 'ROT' in fields: c.addInt ('ROT') 761 if 'SOG' in fields: c.addDecimal('SOG',4,1) 762 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy') 763 if dbType != 'postgres': 764 if 'longitude' in fields: c.addDecimal('longitude',8,5) 765 if dbType != 'postgres': 766 if 'latitude' in fields: c.addDecimal('latitude',8,5) 767 if 'COG' in fields: c.addDecimal('COG',4,1) 768 if 'TrueHeading' in fields: c.addInt ('TrueHeading') 769 if 'TimeStamp' in fields: c.addInt ('TimeStamp') 770 if 'RegionalReserved' in fields: c.addInt ('RegionalReserved') 771 if 'Spare' in fields: c.addInt ('Spare') 772 if 'RAIM' in fields: c.addBool('RAIM') 773 if 'state_syncstate' in fields: c.addInt ('state_syncstate') 774 if 'state_slottimeout' in fields: c.addInt ('state_slottimeout') 775 if 'state_slotoffset' in fields: c.addInt ('state_slotoffset') 776 777 if addCoastGuardFields: 778 # c.addInt('cg_rssi') # Relative signal strength indicator 779 # c.addInt('cg_d') # dBm receive strength 780 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 781 # c.addInt('cg_S') # Slot received in 782 # c.addVarChar('cg_x',10) # Idonno 783 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 784 c.addInt('cg_sec') # UTC seconds since the epoch 785 786 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 787 788 if dbType == 'postgres': 789 #--- EPSG 4326 : WGS 84 790 #INSERT INTO "spatial_ref_sys" ("srid","auth_name","auth_srid","srtext","proj4text") VALUES (4326,'EPSG',4326,'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]','+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '); 791 c.addPostGIS('Position','POINT',2,SRID=4326); 792 793 return c
794
795 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
796 ''' 797 Return the SQL INSERT command for this message type 798 @param params: dictionary of values keyed by field name 799 @param outfile: file like object to print to. 800 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 801 @return: sql create string 802 @rtype: str 803 804 @see: sqlCreate 805 ''' 806 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
807 808
809 -def sqlInsert(params,extraParams=None,dbType='postgres'):
810 ''' 811 Give the SQL INSERT statement 812 @param params: dict keyed by field name of values 813 @param extraParams: any extra fields that you have created beyond the normal ais message fields 814 @rtype: sqlhelp.insert 815 @return: insert class instance 816 @todo: allow optional type checking of params? 817 @warning: this will take invalid keys happily and do what??? 818 ''' 819 import sqlhelp 820 i = sqlhelp.insert('position',dbType=dbType) 821 822 if dbType=='postgres': 823 finished = [] 824 for key in params: 825 if key in finished: 826 continue 827 828 if key not in toPgFields and key not in fromPgFields: 829 if type(params[key])==Decimal: i.add(key,float(params[key])) 830 else: i.add(key,params[key]) 831 else: 832 if key in fromPgFields: 833 val = params[key] 834 # Had better be a WKT type like POINT(-88.1 30.321) 835 i.addPostGIS(key,val) 836 finished.append(key) 837 else: 838 # Need to construct the type. 839 pgName = toPgFields[key] 840 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 841 valStr=pgTypes[pgName]+'(' 842 vals = [] 843 for nonPgKey in fromPgFields[pgName]: 844 vals.append(str(params[nonPgKey])) 845 finished.append(nonPgKey) 846 valStr+=' '.join(vals)+')' 847 i.addPostGIS(pgName,valStr) 848 else: 849 for key in params: 850 if type(params[key])==Decimal: i.add(key,float(params[key])) 851 else: i.add(key,params[key]) 852 853 if None != extraParams: 854 for key in extraParams: 855 i.add(key,extraParams[key]) 856 857 return i
858 859 ###################################################################### 860 # LATEX SUPPORT 861 ###################################################################### 862
863 -def latexDefinitionTable(outfile=sys.stdout 864 ):
865 ''' 866 Return the LaTeX definition table for this message type 867 @param outfile: file like object to print to. 868 @type outfile: file obj 869 @return: LaTeX table string via the outfile 870 @rtype: str 871 872 ''' 873 o = outfile 874 875 o.write(''' 876 \\begin{table}%[htb] 877 \\centering 878 \\begin{tabular}{|l|c|l|} 879 \\hline 880 Parameter & Number of bits & Description 881 \\\\ \\hline\\hline 882 MessageID & 6 & AIS message number. Must be 1 \\\\ \hline 883 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 884 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline 885 NavigationStatus & 4 & What is the vessel doing \\\\ \hline 886 ROT & 8 & Rate of turning. Positive right; negative left. BROKEN! \\\\ \hline 887 SOG & 10 & Speed over ground \\\\ \hline 888 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline 889 longitude & 28 & Location of the vessel East West location \\\\ \hline 890 latitude & 27 & Location of the vessel North South location \\\\ \hline 891 COG & 12 & Course over ground \\\\ \hline 892 TrueHeading & 9 & True heading (relative to true North) \\\\ \hline 893 TimeStamp & 6 & UTC second when the report was generated \\\\ \hline 894 RegionalReserved & 4 & Reserved for definition by a regional authority. \\\\ \hline 895 Spare & 1 & Not used. Should be set to zero. \\\\ \hline 896 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline 897 state\_syncstate & 2 & Communications State - SOTDMA Sycronization state \\\\ \hline 898 state\_slottimeout & 3 & Communications State - SOTDMA Frames remaining until a new slot is selected \\\\ \hline 899 state\_slotoffset & 14 & Communications State - SOTDMA In what slot will the next transmission occur. BROKEN\\\\ \\hline \\hline 900 Total bits & 168 & Appears to take 1 slot \\\\ \\hline 901 \\end{tabular} 902 \\caption{AIS message number 3: Scheduled position report} 903 \\label{tab:position} 904 \\end{table} 905 ''')
906 907 ###################################################################### 908 # Text Definition 909 ###################################################################### 910
911 -def textDefinitionTable(outfile=sys.stdout 912 ,delim='\t' 913 ):
914 ''' 915 Return the text definition table for this message type 916 @param outfile: file like object to print to. 917 @type outfile: file obj 918 @return: text table string via the outfile 919 @rtype: str 920 921 ''' 922 o = outfile 923 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description 924 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 1 925 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated 926 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI) 927 NavigationStatus'''+delim+'''4'''+delim+'''What is the vessel doing 928 ROT'''+delim+'''8'''+delim+'''Rate of turning. Positive right; negative left. BROKEN! 929 SOG'''+delim+'''10'''+delim+'''Speed over ground 930 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes 931 longitude'''+delim+'''28'''+delim+'''Location of the vessel East West location 932 latitude'''+delim+'''27'''+delim+'''Location of the vessel North South location 933 COG'''+delim+'''12'''+delim+'''Course over ground 934 TrueHeading'''+delim+'''9'''+delim+'''True heading (relative to true North) 935 TimeStamp'''+delim+'''6'''+delim+'''UTC second when the report was generated 936 RegionalReserved'''+delim+'''4'''+delim+'''Reserved for definition by a regional authority. 937 Spare'''+delim+'''1'''+delim+'''Not used. Should be set to zero. 938 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag 939 state_syncstate'''+delim+'''2'''+delim+'''Communications State - SOTDMA Sycronization state 940 state_slottimeout'''+delim+'''3'''+delim+'''Communications State - SOTDMA Frames remaining until a new slot is selected 941 state_slotoffset'''+delim+'''14'''+delim+'''Communications State - SOTDMA In what slot will the next transmission occur. BROKEN 942 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
943 944 945 ###################################################################### 946 # UNIT TESTING 947 ###################################################################### 948 import unittest
949 -def testParams():
950 '''Return a params file base on the testvalue tags. 951 @rtype: dict 952 @return: params based on testvalue tags 953 ''' 954 params = {} 955 params['MessageID'] = 3 956 params['RepeatIndicator'] = 1 957 params['UserID'] = 1193046 958 params['NavigationStatus'] = 3 959 params['ROT'] = -2 960 params['SOG'] = Decimal('101.9') 961 params['PositionAccuracy'] = 1 962 params['longitude'] = Decimal('-122.16328055555556') 963 params['latitude'] = Decimal('37.424458333333334') 964 params['COG'] = Decimal('34.5') 965 params['TrueHeading'] = 41 966 params['TimeStamp'] = 35 967 params['RegionalReserved'] = 0 968 params['Spare'] = 0 969 params['RAIM'] = False 970 params['state_syncstate'] = 2 971 params['state_slottimeout'] = 0 972 params['state_slotoffset'] = 1221 973 974 return params
975
976 -class Testposition(unittest.TestCase):
977 '''Use testvalue tag text from each type to build test case the position message'''
978 - def testEncodeDecode(self):
979 980 params = testParams() 981 bits = encode(params) 982 r = decode(bits) 983 984 # Check that each parameter came through ok. 985 self.failUnlessEqual(r['MessageID'],params['MessageID']) 986 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 987 self.failUnlessEqual(r['UserID'],params['UserID']) 988 self.failUnlessEqual(r['NavigationStatus'],params['NavigationStatus']) 989 self.failUnlessEqual(r['ROT'],params['ROT']) 990 self.failUnlessAlmostEqual(r['SOG'],params['SOG'],1) 991 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy']) 992 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5) 993 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5) 994 self.failUnlessAlmostEqual(r['COG'],params['COG'],1) 995 self.failUnlessEqual(r['TrueHeading'],params['TrueHeading']) 996 self.failUnlessEqual(r['TimeStamp'],params['TimeStamp']) 997 self.failUnlessEqual(r['RegionalReserved'],params['RegionalReserved']) 998 self.failUnlessEqual(r['Spare'],params['Spare']) 999 self.failUnlessEqual(r['RAIM'],params['RAIM']) 1000 self.failUnlessEqual(r['state_syncstate'],params['state_syncstate']) 1001 self.failUnlessEqual(r['state_slottimeout'],params['state_slottimeout']) 1002 self.failUnlessEqual(r['state_slotoffset'],params['state_slotoffset'])
1003
1004 -def addMsgOptions(parser):
1005 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 1006 help='decode a "position" AIS message') 1007 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 1008 help='encode a "position" AIS message') 1009 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 1010 ,help='Field parameter value [default: %default]') 1011 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 1012 ,help='Field parameter value [default: %default]') 1013 parser.add_option('--NavigationStatus-field', dest='NavigationStatusField',default=15,metavar='uint',type='int' 1014 ,help='Field parameter value [default: %default]') 1015 parser.add_option('--ROT-field', dest='ROTField',default=-128,metavar='int',type='int' 1016 ,help='Field parameter value [default: %default]') 1017 parser.add_option('--SOG-field', dest='SOGField',default=Decimal('102.3'),metavar='udecimal',type='string' 1018 ,help='Field parameter value [default: %default]') 1019 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int' 1020 ,help='Field parameter value [default: %default]') 1021 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string' 1022 ,help='Field parameter value [default: %default]') 1023 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string' 1024 ,help='Field parameter value [default: %default]') 1025 parser.add_option('--COG-field', dest='COGField',default=Decimal('360'),metavar='udecimal',type='string' 1026 ,help='Field parameter value [default: %default]') 1027 parser.add_option('--TrueHeading-field', dest='TrueHeadingField',default=511,metavar='uint',type='int' 1028 ,help='Field parameter value [default: %default]') 1029 parser.add_option('--TimeStamp-field', dest='TimeStampField',default=60,metavar='uint',type='int' 1030 ,help='Field parameter value [default: %default]') 1031 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int' 1032 ,help='Field parameter value [default: %default]') 1033 parser.add_option('--state_syncstate-field', dest='state_syncstateField',metavar='uint',type='int' 1034 ,help='Field parameter value [default: %default]') 1035 parser.add_option('--state_slottimeout-field', dest='state_slottimeoutField',metavar='uint',type='int' 1036 ,help='Field parameter value [default: %default]') 1037 parser.add_option('--state_slotoffset-field', dest='state_slotoffsetField',metavar='uint',type='int' 1038 ,help='Field parameter value [default: %default]')
1039 1040 ############################################################ 1041 if __name__=='__main__': 1042 1043 from optparse import OptionParser 1044 parser = OptionParser(usage="%prog [options]", 1045 version="%prog "+__version__) 1046 1047 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 1048 help='run the documentation tests') 1049 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 1050 help='run the unit tests') 1051 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 1052 help='Make the test output verbose') 1053 1054 # FIX: remove nmea from binary messages. No way to build the whole packet? 1055 # FIX: or build the surrounding msg 8 for a broadcast? 1056 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 1057 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 1058 ,default='nmeapayload' 1059 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 1060 1061 1062 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 1063 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 1064 ,default='std' 1065 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 1066 1067 parser.add_option('-o','--output',dest='outputFileName',default=None, 1068 help='Name of the python file to write [default: stdout]') 1069 1070 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 1071 choices=fieldList, 1072 help='Which fields to include in the output. Currently only for csv output [default: all]') 1073 1074 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 1075 help='Print the field name for csv') 1076 1077 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 1078 help='Print out an sql create command for the table.') 1079 1080 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 1081 help='Print a LaTeX table of the type') 1082 1083 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true', 1084 help='Print delimited table of the type (for Word table importing)') 1085 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t' 1086 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)') 1087 1088 1089 dbChoices = ('sqlite','postgres') 1090 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 1091 ,choices=dbChoices,type='choice' 1092 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 1093 1094 addMsgOptions(parser) 1095 1096 (options,args) = parser.parse_args() 1097 success=True 1098 1099 if options.doctest: 1100 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 1101 sys.argv= [sys.argv[0]] 1102 if options.verbose: sys.argv.append('-v') 1103 import doctest 1104 numfail,numtests=doctest.testmod() 1105 if numfail==0: print 'ok' 1106 else: 1107 print 'FAILED' 1108 success=False 1109 1110 if not success: sys.exit('Something Failed') 1111 del success # Hide success from epydoc 1112 1113 if options.unittest: 1114 sys.argv = [sys.argv[0]] 1115 if options.verbose: sys.argv.append('-v') 1116 unittest.main() 1117 1118 outfile = sys.stdout 1119 if None!=options.outputFileName: 1120 outfile = file(options.outputFileName,'w') 1121 1122 1123 if options.doEncode: 1124 # First make sure all non required options are specified 1125 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 1126 if None==options.UserIDField: parser.error("missing value for UserIDField") 1127 if None==options.NavigationStatusField: parser.error("missing value for NavigationStatusField") 1128 if None==options.ROTField: parser.error("missing value for ROTField") 1129 if None==options.SOGField: parser.error("missing value for SOGField") 1130 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField") 1131 if None==options.longitudeField: parser.error("missing value for longitudeField") 1132 if None==options.latitudeField: parser.error("missing value for latitudeField") 1133 if None==options.COGField: parser.error("missing value for COGField") 1134 if None==options.TrueHeadingField: parser.error("missing value for TrueHeadingField") 1135 if None==options.TimeStampField: parser.error("missing value for TimeStampField") 1136 if None==options.RAIMField: parser.error("missing value for RAIMField") 1137 if None==options.state_syncstateField: parser.error("missing value for state_syncstateField") 1138 if None==options.state_slottimeoutField: parser.error("missing value for state_slottimeoutField") 1139 if None==options.state_slotoffsetField: parser.error("missing value for state_slotoffsetField") 1140 msgDict={ 1141 'MessageID': '3', 1142 'RepeatIndicator': options.RepeatIndicatorField, 1143 'UserID': options.UserIDField, 1144 'NavigationStatus': options.NavigationStatusField, 1145 'ROT': options.ROTField, 1146 'SOG': options.SOGField, 1147 'PositionAccuracy': options.PositionAccuracyField, 1148 'longitude': options.longitudeField, 1149 'latitude': options.latitudeField, 1150 'COG': options.COGField, 1151 'TrueHeading': options.TrueHeadingField, 1152 'TimeStamp': options.TimeStampField, 1153 'RegionalReserved': '0', 1154 'Spare': '0', 1155 'RAIM': options.RAIMField, 1156 'state_syncstate': options.state_syncstateField, 1157 'state_slottimeout': options.state_slottimeoutField, 1158 'state_slotoffset': options.state_slotoffsetField, 1159 } 1160 1161 bits = encode(msgDict) 1162 if 'binary'==options.ioType: print str(bits) 1163 elif 'nmeapayload'==options.ioType: 1164 # FIX: figure out if this might be necessary at compile time 1165 print "bitLen",len(bits) 1166 bitLen=len(bits) 1167 if bitLen%6!=0: 1168 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 1169 print "result:",binary.bitvectoais6(bits)[0] 1170 1171 1172 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 1173 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 1174 else: sys.exit('ERROR: unknown ioType. Help!') 1175 1176 1177 if options.sqlCreate: 1178 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 1179 1180 if options.latexDefinitionTable: 1181 latexDefinitionTable(outfile) 1182 1183 # For conversion to word tables 1184 if options.textDefinitionTable: 1185 textDefinitionTable(outfile,options.delimTextDefinitionTable) 1186 1187 if options.printCsvfieldList: 1188 # Make a csv separated list of fields that will be displayed for csv 1189 if None == options.fieldList: options.fieldList = fieldList 1190 import StringIO 1191 buf = StringIO.StringIO() 1192 for field in options.fieldList: 1193 buf.write(field+',') 1194 result = buf.getvalue() 1195 if result[-1] == ',': print result[:-1] 1196 else: print result 1197 1198 if options.doDecode: 1199 if len(args)==0: args = sys.stdin 1200 for msg in args: 1201 bv = None 1202 1203 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 1204 # Found nmea 1205 # FIX: do checksum 1206 bv = binary.ais6tobitvec(msg.split(',')[5]) 1207 else: # either binary or nmeapayload... expect mostly nmeapayloads 1208 # assumes that an all 0 and 1 string can not be a nmeapayload 1209 binaryMsg=True 1210 for c in msg: 1211 if c not in ('0','1'): 1212 binaryMsg=False 1213 break 1214 if binaryMsg: 1215 bv = BitVector(bitstring=msg) 1216 else: # nmeapayload 1217 bv = binary.ais6tobitvec(msg) 1218 1219 printFields(decode(bv) 1220 ,out=outfile 1221 ,format=options.outputType 1222 ,fieldList=options.fieldList 1223 ,dbType=options.dbType 1224 ) 1225