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: 2007-12-04 $'.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 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None 718 ,addCoastGuardFields=True 719 ,dbType='postgres' 720 ):
721 ''' 722 Return the SQL CREATE command for this message type 723 @param outfile: file like object to print to. 724 @param fields: which fields to put in the create. Defaults to all. 725 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 726 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 727 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 728 @type addCoastGuardFields: bool 729 @return: sql create string 730 @rtype: str 731 732 @see: sqlCreate 733 ''' 734 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 735 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
736
737 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
738 ''' 739 Return the sqlhelp object to create the table. 740 741 @param fields: which fields to put in the create. Defaults to all. 742 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 743 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 744 @type addCoastGuardFields: bool 745 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 746 @return: An object that can be used to generate a return 747 @rtype: sqlhelp.create 748 ''' 749 if None == fields: fields = fieldList 750 import sqlhelp 751 c = sqlhelp.create('position',dbType=dbType) 752 c.addPrimaryKey() 753 if 'MessageID' in fields: c.addInt ('MessageID') 754 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 755 if 'UserID' in fields: c.addInt ('UserID') 756 if 'NavigationStatus' in fields: c.addInt ('NavigationStatus') 757 if 'ROT' in fields: c.addInt ('ROT') 758 if 'SOG' in fields: c.addDecimal('SOG',4,1) 759 if 'PositionAccuracy' in fields: c.addInt ('PositionAccuracy') 760 if dbType != 'postgres': 761 if 'longitude' in fields: c.addDecimal('longitude',8,5) 762 if dbType != 'postgres': 763 if 'latitude' in fields: c.addDecimal('latitude',8,5) 764 if 'COG' in fields: c.addDecimal('COG',4,1) 765 if 'TrueHeading' in fields: c.addInt ('TrueHeading') 766 if 'TimeStamp' in fields: c.addInt ('TimeStamp') 767 if 'RegionalReserved' in fields: c.addInt ('RegionalReserved') 768 if 'Spare' in fields: c.addInt ('Spare') 769 if 'RAIM' in fields: c.addBool('RAIM') 770 if 'state_syncstate' in fields: c.addInt ('state_syncstate') 771 if 'state_slottimeout' in fields: c.addInt ('state_slottimeout') 772 if 'state_slotoffset' in fields: c.addInt ('state_slotoffset') 773 774 if addCoastGuardFields: 775 # c.addInt('cg_rssi') # Relative signal strength indicator 776 # c.addInt('cg_d') # dBm receive strength 777 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 778 # c.addInt('cg_S') # Slot received in 779 # c.addVarChar('cg_x',10) # Idonno 780 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 781 c.addInt('cg_sec') # UTC seconds since the epoch 782 783 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 784 785 if dbType == 'postgres': 786 #--- EPSG 4326 : WGS 84 787 #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 '); 788 c.addPostGIS('Position','POINT',2,SRID=4326); 789 790 return c
791
792 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
793 ''' 794 Return the SQL INSERT command for this message type 795 @param params: dictionary of values keyed by field name 796 @param outfile: file like object to print to. 797 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 798 @return: sql create string 799 @rtype: str 800 801 @see: sqlCreate 802 ''' 803 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
804 805
806 -def sqlInsert(params,extraParams=None,dbType='postgres'):
807 ''' 808 Give the SQL INSERT statement 809 @param params: dict keyed by field name of values 810 @param extraParams: any extra fields that you have created beyond the normal ais message fields 811 @rtype: sqlhelp.insert 812 @return: insert class instance 813 @todo: allow optional type checking of params? 814 @warning: this will take invalid keys happily and do what??? 815 ''' 816 import sqlhelp 817 i = sqlhelp.insert('position',dbType=dbType) 818 819 if dbType=='postgres': 820 finished = [] 821 for key in params: 822 if key in finished: 823 continue 824 825 if key not in toPgFields and key not in fromPgFields: 826 if type(params[key])==Decimal: i.add(key,float(params[key])) 827 else: i.add(key,params[key]) 828 else: 829 if key in fromPgFields: 830 val = params[key] 831 # Had better be a WKT type like POINT(-88.1 30.321) 832 i.addPostGIS(key,val) 833 finished.append(key) 834 else: 835 # Need to construct the type. 836 pgName = toPgFields[key] 837 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 838 valStr=pgTypes[pgName]+'(' 839 vals = [] 840 for nonPgKey in fromPgFields[pgName]: 841 vals.append(str(params[nonPgKey])) 842 finished.append(nonPgKey) 843 valStr+=' '.join(vals)+')' 844 i.addPostGIS(pgName,valStr) 845 else: 846 for key in params: 847 if type(params[key])==Decimal: i.add(key,float(params[key])) 848 else: i.add(key,params[key]) 849 850 if None != extraParams: 851 for key in extraParams: 852 i.add(key,extraParams[key]) 853 854 return i
855 856 ###################################################################### 857 # LATEX SUPPORT 858 ###################################################################### 859
860 -def latexDefinitionTable(outfile=sys.stdout 861 ):
862 ''' 863 Return the LaTeX definition table for this message type 864 @param outfile: file like object to print to. 865 @type outfile: file obj 866 @return: LaTeX table string via the outfile 867 @rtype: str 868 869 ''' 870 o = outfile 871 872 o.write(''' 873 \\begin{table}%[htb] 874 \\centering 875 \\begin{tabular}{|l|c|l|} 876 \\hline 877 Parameter & Number of bits & Description 878 \\\\ \\hline\\hline 879 MessageID & 6 & AIS message number. Must be 1 \\\\ \hline 880 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 881 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline 882 NavigationStatus & 4 & What is the vessel doing \\\\ \hline 883 ROT & 8 & Rate of turning. Positive right; negative left. BROKEN! \\\\ \hline 884 SOG & 10 & Speed over ground \\\\ \hline 885 PositionAccuracy & 1 & Accuracy of positioning fixes \\\\ \hline 886 longitude & 28 & Location of the vessel East West location \\\\ \hline 887 latitude & 27 & Location of the vessel North South location \\\\ \hline 888 COG & 12 & Course over ground \\\\ \hline 889 TrueHeading & 9 & True heading (relative to true North) \\\\ \hline 890 TimeStamp & 6 & UTC second when the report was generated \\\\ \hline 891 RegionalReserved & 4 & Reserved for definition by a regional authority. \\\\ \hline 892 Spare & 1 & Not used. Should be set to zero. \\\\ \hline 893 RAIM & 1 & Receiver autonomous integrity monitoring flag \\\\ \hline 894 state\_syncstate & 2 & Communications State - SOTDMA Sycronization state \\\\ \hline 895 state\_slottimeout & 3 & Communications State - SOTDMA Frames remaining until a new slot is selected \\\\ \hline 896 state\_slotoffset & 14 & Communications State - SOTDMA In what slot will the next transmission occur. BROKEN\\\\ \\hline \\hline 897 Total bits & 168 & Appears to take 1 slot \\\\ \\hline 898 \\end{tabular} 899 \\caption{AIS message number 3: Scheduled position report} 900 \\label{tab:position} 901 \\end{table} 902 ''')
903 904 ###################################################################### 905 # Text Definition 906 ###################################################################### 907
908 -def textDefinitionTable(outfile=sys.stdout 909 ,delim='\t' 910 ):
911 ''' 912 Return the text definition table for this message type 913 @param outfile: file like object to print to. 914 @type outfile: file obj 915 @return: text table string via the outfile 916 @rtype: str 917 918 ''' 919 o = outfile 920 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description 921 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 1 922 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated 923 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI) 924 NavigationStatus'''+delim+'''4'''+delim+'''What is the vessel doing 925 ROT'''+delim+'''8'''+delim+'''Rate of turning. Positive right; negative left. BROKEN! 926 SOG'''+delim+'''10'''+delim+'''Speed over ground 927 PositionAccuracy'''+delim+'''1'''+delim+'''Accuracy of positioning fixes 928 longitude'''+delim+'''28'''+delim+'''Location of the vessel East West location 929 latitude'''+delim+'''27'''+delim+'''Location of the vessel North South location 930 COG'''+delim+'''12'''+delim+'''Course over ground 931 TrueHeading'''+delim+'''9'''+delim+'''True heading (relative to true North) 932 TimeStamp'''+delim+'''6'''+delim+'''UTC second when the report was generated 933 RegionalReserved'''+delim+'''4'''+delim+'''Reserved for definition by a regional authority. 934 Spare'''+delim+'''1'''+delim+'''Not used. Should be set to zero. 935 RAIM'''+delim+'''1'''+delim+'''Receiver autonomous integrity monitoring flag 936 state_syncstate'''+delim+'''2'''+delim+'''Communications State - SOTDMA Sycronization state 937 state_slottimeout'''+delim+'''3'''+delim+'''Communications State - SOTDMA Frames remaining until a new slot is selected 938 state_slotoffset'''+delim+'''14'''+delim+'''Communications State - SOTDMA In what slot will the next transmission occur. BROKEN 939 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
940 941 942 ###################################################################### 943 # UNIT TESTING 944 ###################################################################### 945 import unittest
946 -def testParams():
947 '''Return a params file base on the testvalue tags. 948 @rtype: dict 949 @return: params based on testvalue tags 950 ''' 951 params = {} 952 params['MessageID'] = 3 953 params['RepeatIndicator'] = 1 954 params['UserID'] = 1193046 955 params['NavigationStatus'] = 3 956 params['ROT'] = -2 957 params['SOG'] = Decimal('101.9') 958 params['PositionAccuracy'] = 1 959 params['longitude'] = Decimal('-122.16328055555556') 960 params['latitude'] = Decimal('37.424458333333334') 961 params['COG'] = Decimal('34.5') 962 params['TrueHeading'] = 41 963 params['TimeStamp'] = 35 964 params['RegionalReserved'] = 0 965 params['Spare'] = 0 966 params['RAIM'] = False 967 params['state_syncstate'] = 2 968 params['state_slottimeout'] = 0 969 params['state_slotoffset'] = 1221 970 971 return params
972
973 -class Testposition(unittest.TestCase):
974 '''Use testvalue tag text from each type to build test case the position message'''
975 - def testEncodeDecode(self):
976 977 params = testParams() 978 bits = encode(params) 979 r = decode(bits) 980 981 # Check that each parameter came through ok. 982 self.failUnlessEqual(r['MessageID'],params['MessageID']) 983 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 984 self.failUnlessEqual(r['UserID'],params['UserID']) 985 self.failUnlessEqual(r['NavigationStatus'],params['NavigationStatus']) 986 self.failUnlessEqual(r['ROT'],params['ROT']) 987 self.failUnlessAlmostEqual(r['SOG'],params['SOG'],1) 988 self.failUnlessEqual(r['PositionAccuracy'],params['PositionAccuracy']) 989 self.failUnlessAlmostEqual(r['longitude'],params['longitude'],5) 990 self.failUnlessAlmostEqual(r['latitude'],params['latitude'],5) 991 self.failUnlessAlmostEqual(r['COG'],params['COG'],1) 992 self.failUnlessEqual(r['TrueHeading'],params['TrueHeading']) 993 self.failUnlessEqual(r['TimeStamp'],params['TimeStamp']) 994 self.failUnlessEqual(r['RegionalReserved'],params['RegionalReserved']) 995 self.failUnlessEqual(r['Spare'],params['Spare']) 996 self.failUnlessEqual(r['RAIM'],params['RAIM']) 997 self.failUnlessEqual(r['state_syncstate'],params['state_syncstate']) 998 self.failUnlessEqual(r['state_slottimeout'],params['state_slottimeout']) 999 self.failUnlessEqual(r['state_slotoffset'],params['state_slotoffset'])
1000
1001 -def addMsgOptions(parser):
1002 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 1003 help='decode a "position" AIS message') 1004 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 1005 help='encode a "position" AIS message') 1006 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 1007 ,help='Field parameter value [default: %default]') 1008 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 1009 ,help='Field parameter value [default: %default]') 1010 parser.add_option('--NavigationStatus-field', dest='NavigationStatusField',default=15,metavar='uint',type='int' 1011 ,help='Field parameter value [default: %default]') 1012 parser.add_option('--ROT-field', dest='ROTField',default=-128,metavar='int',type='int' 1013 ,help='Field parameter value [default: %default]') 1014 parser.add_option('--SOG-field', dest='SOGField',default=Decimal('102.3'),metavar='udecimal',type='string' 1015 ,help='Field parameter value [default: %default]') 1016 parser.add_option('--PositionAccuracy-field', dest='PositionAccuracyField',metavar='uint',type='int' 1017 ,help='Field parameter value [default: %default]') 1018 parser.add_option('--longitude-field', dest='longitudeField',default=Decimal('181'),metavar='decimal',type='string' 1019 ,help='Field parameter value [default: %default]') 1020 parser.add_option('--latitude-field', dest='latitudeField',default=Decimal('91'),metavar='decimal',type='string' 1021 ,help='Field parameter value [default: %default]') 1022 parser.add_option('--COG-field', dest='COGField',default=Decimal('360'),metavar='udecimal',type='string' 1023 ,help='Field parameter value [default: %default]') 1024 parser.add_option('--TrueHeading-field', dest='TrueHeadingField',default=511,metavar='uint',type='int' 1025 ,help='Field parameter value [default: %default]') 1026 parser.add_option('--TimeStamp-field', dest='TimeStampField',default=60,metavar='uint',type='int' 1027 ,help='Field parameter value [default: %default]') 1028 parser.add_option('--RAIM-field', dest='RAIMField',metavar='bool',type='int' 1029 ,help='Field parameter value [default: %default]') 1030 parser.add_option('--state_syncstate-field', dest='state_syncstateField',metavar='uint',type='int' 1031 ,help='Field parameter value [default: %default]') 1032 parser.add_option('--state_slottimeout-field', dest='state_slottimeoutField',metavar='uint',type='int' 1033 ,help='Field parameter value [default: %default]') 1034 parser.add_option('--state_slotoffset-field', dest='state_slotoffsetField',metavar='uint',type='int' 1035 ,help='Field parameter value [default: %default]')
1036 1037 ############################################################ 1038 if __name__=='__main__': 1039 1040 from optparse import OptionParser 1041 parser = OptionParser(usage="%prog [options]", 1042 version="%prog "+__version__) 1043 1044 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 1045 help='run the documentation tests') 1046 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 1047 help='run the unit tests') 1048 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 1049 help='Make the test output verbose') 1050 1051 # FIX: remove nmea from binary messages. No way to build the whole packet? 1052 # FIX: or build the surrounding msg 8 for a broadcast? 1053 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 1054 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 1055 ,default='nmeapayload' 1056 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 1057 1058 1059 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 1060 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 1061 ,default='std' 1062 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 1063 1064 parser.add_option('-o','--output',dest='outputFileName',default=None, 1065 help='Name of the python file to write [default: stdout]') 1066 1067 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 1068 choices=fieldList, 1069 help='Which fields to include in the output. Currently only for csv output [default: all]') 1070 1071 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 1072 help='Print the field name for csv') 1073 1074 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 1075 help='Print out an sql create command for the table.') 1076 1077 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 1078 help='Print a LaTeX table of the type') 1079 1080 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true', 1081 help='Print delimited table of the type (for Word table importing)') 1082 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t' 1083 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)') 1084 1085 1086 dbChoices = ('sqlite','postgres') 1087 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 1088 ,choices=dbChoices,type='choice' 1089 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 1090 1091 addMsgOptions(parser) 1092 1093 (options,args) = parser.parse_args() 1094 success=True 1095 1096 if options.doctest: 1097 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 1098 sys.argv= [sys.argv[0]] 1099 if options.verbose: sys.argv.append('-v') 1100 import doctest 1101 numfail,numtests=doctest.testmod() 1102 if numfail==0: print 'ok' 1103 else: 1104 print 'FAILED' 1105 success=False 1106 1107 if not success: sys.exit('Something Failed') 1108 del success # Hide success from epydoc 1109 1110 if options.unittest: 1111 sys.argv = [sys.argv[0]] 1112 if options.verbose: sys.argv.append('-v') 1113 unittest.main() 1114 1115 outfile = sys.stdout 1116 if None!=options.outputFileName: 1117 outfile = file(options.outputFileName,'w') 1118 1119 1120 if options.doEncode: 1121 # First make sure all non required options are specified 1122 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 1123 if None==options.UserIDField: parser.error("missing value for UserIDField") 1124 if None==options.NavigationStatusField: parser.error("missing value for NavigationStatusField") 1125 if None==options.ROTField: parser.error("missing value for ROTField") 1126 if None==options.SOGField: parser.error("missing value for SOGField") 1127 if None==options.PositionAccuracyField: parser.error("missing value for PositionAccuracyField") 1128 if None==options.longitudeField: parser.error("missing value for longitudeField") 1129 if None==options.latitudeField: parser.error("missing value for latitudeField") 1130 if None==options.COGField: parser.error("missing value for COGField") 1131 if None==options.TrueHeadingField: parser.error("missing value for TrueHeadingField") 1132 if None==options.TimeStampField: parser.error("missing value for TimeStampField") 1133 if None==options.RAIMField: parser.error("missing value for RAIMField") 1134 if None==options.state_syncstateField: parser.error("missing value for state_syncstateField") 1135 if None==options.state_slottimeoutField: parser.error("missing value for state_slottimeoutField") 1136 if None==options.state_slotoffsetField: parser.error("missing value for state_slotoffsetField") 1137 msgDict={ 1138 'MessageID': '3', 1139 'RepeatIndicator': options.RepeatIndicatorField, 1140 'UserID': options.UserIDField, 1141 'NavigationStatus': options.NavigationStatusField, 1142 'ROT': options.ROTField, 1143 'SOG': options.SOGField, 1144 'PositionAccuracy': options.PositionAccuracyField, 1145 'longitude': options.longitudeField, 1146 'latitude': options.latitudeField, 1147 'COG': options.COGField, 1148 'TrueHeading': options.TrueHeadingField, 1149 'TimeStamp': options.TimeStampField, 1150 'RegionalReserved': '0', 1151 'Spare': '0', 1152 'RAIM': options.RAIMField, 1153 'state_syncstate': options.state_syncstateField, 1154 'state_slottimeout': options.state_slottimeoutField, 1155 'state_slotoffset': options.state_slotoffsetField, 1156 } 1157 1158 bits = encode(msgDict) 1159 if 'binary'==options.ioType: print str(bits) 1160 elif 'nmeapayload'==options.ioType: 1161 # FIX: figure out if this might be necessary at compile time 1162 print "bitLen",len(bits) 1163 bitLen=len(bits) 1164 if bitLen%6!=0: 1165 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 1166 print "result:",binary.bitvectoais6(bits)[0] 1167 1168 1169 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 1170 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 1171 else: sys.exit('ERROR: unknown ioType. Help!') 1172 1173 1174 if options.sqlCreate: 1175 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 1176 1177 if options.latexDefinitionTable: 1178 latexDefinitionTable(outfile) 1179 1180 # For conversion to word tables 1181 if options.textDefinitionTable: 1182 textDefinitionTable(outfile,options.delimTextDefinitionTable) 1183 1184 if options.printCsvfieldList: 1185 # Make a csv separated list of fields that will be displayed for csv 1186 if None == options.fieldList: options.fieldList = fieldList 1187 import StringIO 1188 buf = StringIO.StringIO() 1189 for field in options.fieldList: 1190 buf.write(field+',') 1191 result = buf.getvalue() 1192 if result[-1] == ',': print result[:-1] 1193 else: print result 1194 1195 if options.doDecode: 1196 if len(args)==0: args = sys.stdin 1197 for msg in args: 1198 bv = None 1199 1200 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 1201 # Found nmea 1202 # FIX: do checksum 1203 bv = binary.ais6tobitvec(msg.split(',')[5]) 1204 else: # either binary or nmeapayload... expect mostly nmeapayloads 1205 # assumes that an all 0 and 1 string can not be a nmeapayload 1206 binaryMsg=True 1207 for c in msg: 1208 if c not in ('0','1'): 1209 binaryMsg=False 1210 break 1211 if binaryMsg: 1212 bv = BitVector(bitstring=msg) 1213 else: # nmeapayload 1214 bv = binary.ais6tobitvec(msg) 1215 1216 printFields(decode(bv) 1217 ,out=outfile 1218 ,format=options.outputType 1219 ,fieldList=options.fieldList 1220 ,dbType=options.dbType 1221 ) 1222