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

Source Code for Module ais.ais_msg_12

  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          'SeqNum', 
 54          'DestinationID', 
 55          'RetransmitFlag', 
 56          'Spare', 
 57  ) 
 58   
 59  fieldListPostgres = ( 
 60          'MessageID', 
 61          'RepeatIndicator', 
 62          'UserID', 
 63          'SeqNum', 
 64          'DestinationID', 
 65          'RetransmitFlag', 
 66          'Spare', 
 67  ) 
 68   
 69  toPgFields = { 
 70  } 
 71  ''' 
 72  Go to the Postgis field names from the straight field name 
 73  ''' 
 74   
 75  fromPgFields = { 
 76  } 
 77  ''' 
 78  Go from the Postgis field names to the straight field name 
 79  ''' 
 80   
 81  pgTypes = { 
 82  } 
 83  ''' 
 84  Lookup table for each postgis field name to get its type. 
 85  ''' 
 86   
87 -def encode(params, validate=False):
88 '''Create a asrm binary message payload to pack into an AIS Msg asrm. 89 90 Fields in params: 91 - MessageID(uint): AIS message number. Must be 6 (field automatically set to "6") 92 - RepeatIndicator(uint): Indicated how many times a message has been repeated 93 - UserID(uint): Unique ship identification number (MMSI). Also known as the Source ID 94 - SeqNum(uint): Sequence number as described in 5.3.1. Assigned to each station 95 - DestinationID(uint): Unique ship identification number (MMSI). 96 - RetransmitFlag(bool): Should the message be restransmitted? 97 - Spare(uint): Must be 0 (field automatically set to "0") 98 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 99 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 100 @rtype: BitVector 101 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 102 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 103 ''' 104 105 bvList = [] 106 bvList.append(binary.setBitVectorSize(BitVector(intVal=6),6)) 107 if 'RepeatIndicator' in params: 108 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 109 else: 110 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 111 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 112 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['SeqNum']),2)) 113 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['DestinationID']),30)) 114 if params["RetransmitFlag"]: bvList.append(TrueBV) 115 else: bvList.append(FalseBV) 116 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),1)) 117 118 return binary.joinBV(bvList)
119
120 -def decode(bv, validate=False):
121 '''Unpack a asrm message 122 123 Fields in params: 124 - MessageID(uint): AIS message number. Must be 6 (field automatically set to "6") 125 - RepeatIndicator(uint): Indicated how many times a message has been repeated 126 - UserID(uint): Unique ship identification number (MMSI). Also known as the Source ID 127 - SeqNum(uint): Sequence number as described in 5.3.1. Assigned to each station 128 - DestinationID(uint): Unique ship identification number (MMSI). 129 - RetransmitFlag(bool): Should the message be restransmitted? 130 - Spare(uint): Must be 0 (field automatically set to "0") 131 @type bv: BitVector 132 @param bv: Bits defining a message 133 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 134 @rtype: dict 135 @return: params 136 ''' 137 138 #Would be nice to check the bit count here.. 139 #if validate: 140 # assert (len(bv)==FIX: SOME NUMBER) 141 r = {} 142 r['MessageID']=6 143 r['RepeatIndicator']=int(bv[6:8]) 144 r['UserID']=int(bv[8:38]) 145 r['SeqNum']=int(bv[38:40]) 146 r['DestinationID']=int(bv[40:70]) 147 r['RetransmitFlag']=bool(int(bv[70:71])) 148 r['Spare']=0 149 return r
150
151 -def decodeMessageID(bv, validate=False):
152 return 6
153
154 -def decodeRepeatIndicator(bv, validate=False):
155 return int(bv[6:8])
156
157 -def decodeUserID(bv, validate=False):
158 return int(bv[8:38])
159
160 -def decodeSeqNum(bv, validate=False):
161 return int(bv[38:40])
162
163 -def decodeDestinationID(bv, validate=False):
164 return int(bv[40:70])
165
166 -def decodeRetransmitFlag(bv, validate=False):
167 return bool(int(bv[70:71]))
168
169 -def decodeSpare(bv, validate=False):
170 return 0
171 172
173 -def printHtml(params, out=sys.stdout):
174 out.write("<h3>asrm</h3>\n") 175 out.write("<table border=\"1\">\n") 176 out.write("<tr bgcolor=\"orange\">\n") 177 out.write("<th align=\"left\">Field Name</th>\n") 178 out.write("<th align=\"left\">Type</th>\n") 179 out.write("<th align=\"left\">Value</th>\n") 180 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 181 out.write("<th align=\"left\">Units</th>\n") 182 out.write("\n") 183 out.write("<tr>\n") 184 out.write("<td>MessageID</td>\n") 185 out.write("<td>uint</td>\n") 186 if 'MessageID' in params: 187 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 188 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 189 out.write("</tr>\n") 190 out.write("\n") 191 out.write("<tr>\n") 192 out.write("<td>RepeatIndicator</td>\n") 193 out.write("<td>uint</td>\n") 194 if 'RepeatIndicator' in params: 195 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 196 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 197 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 198 else: 199 out.write("<td><i>Missing LUT entry</i></td>") 200 out.write("</tr>\n") 201 out.write("\n") 202 out.write("<tr>\n") 203 out.write("<td>UserID</td>\n") 204 out.write("<td>uint</td>\n") 205 if 'UserID' in params: 206 out.write(" <td>"+str(params['UserID'])+"</td>\n") 207 out.write(" <td>"+str(params['UserID'])+"</td>\n") 208 out.write("</tr>\n") 209 out.write("\n") 210 out.write("<tr>\n") 211 out.write("<td>SeqNum</td>\n") 212 out.write("<td>uint</td>\n") 213 if 'SeqNum' in params: 214 out.write(" <td>"+str(params['SeqNum'])+"</td>\n") 215 out.write(" <td>"+str(params['SeqNum'])+"</td>\n") 216 out.write("</tr>\n") 217 out.write("\n") 218 out.write("<tr>\n") 219 out.write("<td>DestinationID</td>\n") 220 out.write("<td>uint</td>\n") 221 if 'DestinationID' in params: 222 out.write(" <td>"+str(params['DestinationID'])+"</td>\n") 223 out.write(" <td>"+str(params['DestinationID'])+"</td>\n") 224 out.write("</tr>\n") 225 out.write("\n") 226 out.write("<tr>\n") 227 out.write("<td>RetransmitFlag</td>\n") 228 out.write("<td>bool</td>\n") 229 if 'RetransmitFlag' in params: 230 out.write(" <td>"+str(params['RetransmitFlag'])+"</td>\n") 231 out.write(" <td>"+str(params['RetransmitFlag'])+"</td>\n") 232 out.write("</tr>\n") 233 out.write("\n") 234 out.write("<tr>\n") 235 out.write("<td>Spare</td>\n") 236 out.write("<td>uint</td>\n") 237 if 'Spare' in params: 238 out.write(" <td>"+str(params['Spare'])+"</td>\n") 239 out.write(" <td>"+str(params['Spare'])+"</td>\n") 240 out.write("</tr>\n") 241 out.write("</table>\n")
242
243 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
244 '''Print a asrm message to stdout. 245 246 Fields in params: 247 - MessageID(uint): AIS message number. Must be 6 (field automatically set to "6") 248 - RepeatIndicator(uint): Indicated how many times a message has been repeated 249 - UserID(uint): Unique ship identification number (MMSI). Also known as the Source ID 250 - SeqNum(uint): Sequence number as described in 5.3.1. Assigned to each station 251 - DestinationID(uint): Unique ship identification number (MMSI). 252 - RetransmitFlag(bool): Should the message be restransmitted? 253 - Spare(uint): Must be 0 (field automatically set to "0") 254 @param params: Dictionary of field names/values. 255 @param out: File like object to write to 256 @rtype: stdout 257 @return: text to out 258 ''' 259 260 if 'std'==format: 261 out.write("asrm:\n") 262 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 263 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 264 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 265 if 'SeqNum' in params: out.write(" SeqNum: "+str(params['SeqNum'])+"\n") 266 if 'DestinationID' in params: out.write(" DestinationID: "+str(params['DestinationID'])+"\n") 267 if 'RetransmitFlag' in params: out.write(" RetransmitFlag: "+str(params['RetransmitFlag'])+"\n") 268 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 269 elif 'csv'==format: 270 if None == options.fieldList: 271 options.fieldList = fieldList 272 needComma = False; 273 for field in fieldList: 274 if needComma: out.write(',') 275 needComma = True 276 if field in params: 277 out.write(str(params[field])) 278 # else: leave it empty 279 out.write("\n") 280 elif 'html'==format: 281 printHtml(params,out) 282 elif 'sql'==format: 283 sqlInsertStr(params,out,dbType=dbType) 284 else: 285 print "ERROR: unknown format:",format 286 assert False 287 288 return # Nothing to return
289 290 RepeatIndicatorEncodeLut = { 291 'default':'0', 292 'do not repeat any more':'3', 293 } #RepeatIndicatorEncodeLut 294 295 RepeatIndicatorDecodeLut = { 296 '0':'default', 297 '3':'do not repeat any more', 298 } # RepeatIndicatorEncodeLut 299 300 ###################################################################### 301 # SQL SUPPORT 302 ###################################################################### 303 304 dbTableName='asrm' 305 'Database table name' 306
307 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None 308 ,addCoastGuardFields=True 309 ,dbType='postgres' 310 ):
311 ''' 312 Return the SQL CREATE command for this message type 313 @param outfile: file like object to print to. 314 @param fields: which fields to put in the create. Defaults to all. 315 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 316 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 317 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 318 @type addCoastGuardFields: bool 319 @return: sql create string 320 @rtype: str 321 322 @see: sqlCreate 323 ''' 324 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 325 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
326
327 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
328 ''' 329 Return the sqlhelp object to create the table. 330 331 @param fields: which fields to put in the create. Defaults to all. 332 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 333 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 334 @type addCoastGuardFields: bool 335 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 336 @return: An object that can be used to generate a return 337 @rtype: sqlhelp.create 338 ''' 339 if None == fields: fields = fieldList 340 import sqlhelp 341 c = sqlhelp.create('asrm',dbType=dbType) 342 c.addPrimaryKey() 343 if 'MessageID' in fields: c.addInt ('MessageID') 344 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 345 if 'UserID' in fields: c.addInt ('UserID') 346 if 'SeqNum' in fields: c.addInt ('SeqNum') 347 if 'DestinationID' in fields: c.addInt ('DestinationID') 348 if 'RetransmitFlag' in fields: c.addBool('RetransmitFlag') 349 if 'Spare' in fields: c.addInt ('Spare') 350 351 if addCoastGuardFields: 352 # c.addInt('cg_rssi') # Relative signal strength indicator 353 # c.addInt('cg_d') # dBm receive strength 354 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 355 # c.addInt('cg_S') # Slot received in 356 # c.addVarChar('cg_x',10) # Idonno 357 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 358 c.addInt('cg_sec') # UTC seconds since the epoch 359 360 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 361 362 return c
363
364 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
365 ''' 366 Return the SQL INSERT command for this message type 367 @param params: dictionary of values keyed by field name 368 @param outfile: file like object to print to. 369 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 370 @return: sql create string 371 @rtype: str 372 373 @see: sqlCreate 374 ''' 375 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
376 377
378 -def sqlInsert(params,extraParams=None,dbType='postgres'):
379 ''' 380 Give the SQL INSERT statement 381 @param params: dict keyed by field name of values 382 @param extraParams: any extra fields that you have created beyond the normal ais message fields 383 @rtype: sqlhelp.insert 384 @return: insert class instance 385 @todo: allow optional type checking of params? 386 @warning: this will take invalid keys happily and do what??? 387 ''' 388 import sqlhelp 389 i = sqlhelp.insert('asrm',dbType=dbType) 390 391 if dbType=='postgres': 392 finished = [] 393 for key in params: 394 if key in finished: 395 continue 396 397 if key not in toPgFields and key not in fromPgFields: 398 if type(params[key])==Decimal: i.add(key,float(params[key])) 399 else: i.add(key,params[key]) 400 else: 401 if key in fromPgFields: 402 val = params[key] 403 # Had better be a WKT type like POINT(-88.1 30.321) 404 i.addPostGIS(key,val) 405 finished.append(key) 406 else: 407 # Need to construct the type. 408 pgName = toPgFields[key] 409 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 410 valStr=pgTypes[pgName]+'(' 411 vals = [] 412 for nonPgKey in fromPgFields[pgName]: 413 vals.append(str(params[nonPgKey])) 414 finished.append(nonPgKey) 415 valStr+=' '.join(vals)+')' 416 i.addPostGIS(pgName,valStr) 417 else: 418 for key in params: 419 if type(params[key])==Decimal: i.add(key,float(params[key])) 420 else: i.add(key,params[key]) 421 422 if None != extraParams: 423 for key in extraParams: 424 i.add(key,extraParams[key]) 425 426 return i
427 428 ###################################################################### 429 # LATEX SUPPORT 430 ###################################################################### 431
432 -def latexDefinitionTable(outfile=sys.stdout 433 ):
434 ''' 435 Return the LaTeX definition table for this message type 436 @param outfile: file like object to print to. 437 @type outfile: file obj 438 @return: LaTeX table string via the outfile 439 @rtype: str 440 441 ''' 442 o = outfile 443 444 o.write(''' 445 \\begin{table}%[htb] 446 \\centering 447 \\begin{tabular}{|l|c|l|} 448 \\hline 449 Parameter & Number of bits & Description 450 \\\\ \\hline\\hline 451 MessageID & 6 & AIS message number. Must be 6 \\\\ \hline 452 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 453 UserID & 30 & Unique ship identification number (MMSI). Also known as the Source ID \\\\ \hline 454 SeqNum & 2 & Sequence number as described in 5.3.1. Assigned to each station \\\\ \hline 455 DestinationID & 30 & Unique ship identification number (MMSI). \\\\ \hline 456 RetransmitFlag & 1 & Should the message be restransmitted? \\\\ \hline 457 Spare & 1 & Must be 0\\\\ \\hline \\hline 458 Total bits & 72 & Appears to take 1 slot with 96 pad bits to fill the last slot \\\\ \\hline 459 \\end{tabular} 460 \\caption{AIS message number 8: Addressed safety related message. FIX: need to handle the -1 string length at the end} 461 \\label{tab:asrm} 462 \\end{table} 463 ''')
464 465 ###################################################################### 466 # Text Definition 467 ###################################################################### 468
469 -def textDefinitionTable(outfile=sys.stdout 470 ,delim='\t' 471 ):
472 ''' 473 Return the text definition table for this message type 474 @param outfile: file like object to print to. 475 @type outfile: file obj 476 @return: text table string via the outfile 477 @rtype: str 478 479 ''' 480 o = outfile 481 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description 482 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 6 483 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated 484 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI). Also known as the Source ID 485 SeqNum'''+delim+'''2'''+delim+'''Sequence number as described in 5.3.1. Assigned to each station 486 DestinationID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI). 487 RetransmitFlag'''+delim+'''1'''+delim+'''Should the message be restransmitted? 488 Spare'''+delim+'''1'''+delim+'''Must be 0 489 Total bits'''+delim+'''72'''+delim+'''Appears to take 1 slot with 96 pad bits to fill the last slot''')
490 491 492 ###################################################################### 493 # UNIT TESTING 494 ###################################################################### 495 import unittest
496 -def testParams():
497 '''Return a params file base on the testvalue tags. 498 @rtype: dict 499 @return: params based on testvalue tags 500 ''' 501 params = {} 502 params['MessageID'] = 6 503 params['RepeatIndicator'] = 1 504 params['UserID'] = 1193046 505 params['SeqNum'] = 3 506 params['DestinationID'] = 1193047 507 params['RetransmitFlag'] = True 508 params['Spare'] = 0 509 510 return params
511
512 -class Testasrm(unittest.TestCase):
513 '''Use testvalue tag text from each type to build test case the asrm message'''
514 - def testEncodeDecode(self):
515 516 params = testParams() 517 bits = encode(params) 518 r = decode(bits) 519 520 # Check that each parameter came through ok. 521 self.failUnlessEqual(r['MessageID'],params['MessageID']) 522 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 523 self.failUnlessEqual(r['UserID'],params['UserID']) 524 self.failUnlessEqual(r['SeqNum'],params['SeqNum']) 525 self.failUnlessEqual(r['DestinationID'],params['DestinationID']) 526 self.failUnlessEqual(r['RetransmitFlag'],params['RetransmitFlag']) 527 self.failUnlessEqual(r['Spare'],params['Spare'])
528
529 -def addMsgOptions(parser):
530 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 531 help='decode a "asrm" AIS message') 532 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 533 help='encode a "asrm" AIS message') 534 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 535 ,help='Field parameter value [default: %default]') 536 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 537 ,help='Field parameter value [default: %default]') 538 parser.add_option('--SeqNum-field', dest='SeqNumField',metavar='uint',type='int' 539 ,help='Field parameter value [default: %default]') 540 parser.add_option('--DestinationID-field', dest='DestinationIDField',metavar='uint',type='int' 541 ,help='Field parameter value [default: %default]') 542 parser.add_option('--RetransmitFlag-field', dest='RetransmitFlagField',metavar='bool',type='int' 543 ,help='Field parameter value [default: %default]')
544 545 ############################################################ 546 if __name__=='__main__': 547 548 from optparse import OptionParser 549 parser = OptionParser(usage="%prog [options]", 550 version="%prog "+__version__) 551 552 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 553 help='run the documentation tests') 554 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 555 help='run the unit tests') 556 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 557 help='Make the test output verbose') 558 559 # FIX: remove nmea from binary messages. No way to build the whole packet? 560 # FIX: or build the surrounding msg 8 for a broadcast? 561 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 562 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 563 ,default='nmeapayload' 564 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 565 566 567 outputChoices = ('std','html','csv','sql' ) 568 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 569 ,default='std' 570 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 571 572 parser.add_option('-o','--output',dest='outputFileName',default=None, 573 help='Name of the python file to write [default: stdout]') 574 575 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 576 choices=fieldList, 577 help='Which fields to include in the output. Currently only for csv output [default: all]') 578 579 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 580 help='Print the field name for csv') 581 582 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 583 help='Print out an sql create command for the table.') 584 585 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 586 help='Print a LaTeX table of the type') 587 588 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true', 589 help='Print delimited table of the type (for Word table importing)') 590 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t' 591 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)') 592 593 594 dbChoices = ('sqlite','postgres') 595 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 596 ,choices=dbChoices,type='choice' 597 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 598 599 addMsgOptions(parser) 600 601 (options,args) = parser.parse_args() 602 success=True 603 604 if options.doctest: 605 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 606 sys.argv= [sys.argv[0]] 607 if options.verbose: sys.argv.append('-v') 608 import doctest 609 numfail,numtests=doctest.testmod() 610 if numfail==0: print 'ok' 611 else: 612 print 'FAILED' 613 success=False 614 615 if not success: sys.exit('Something Failed') 616 del success # Hide success from epydoc 617 618 if options.unittest: 619 sys.argv = [sys.argv[0]] 620 if options.verbose: sys.argv.append('-v') 621 unittest.main() 622 623 outfile = sys.stdout 624 if None!=options.outputFileName: 625 outfile = file(options.outputFileName,'w') 626 627 628 if options.doEncode: 629 # First make sure all non required options are specified 630 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 631 if None==options.UserIDField: parser.error("missing value for UserIDField") 632 if None==options.SeqNumField: parser.error("missing value for SeqNumField") 633 if None==options.DestinationIDField: parser.error("missing value for DestinationIDField") 634 if None==options.RetransmitFlagField: parser.error("missing value for RetransmitFlagField") 635 msgDict={ 636 'MessageID': '6', 637 'RepeatIndicator': options.RepeatIndicatorField, 638 'UserID': options.UserIDField, 639 'SeqNum': options.SeqNumField, 640 'DestinationID': options.DestinationIDField, 641 'RetransmitFlag': options.RetransmitFlagField, 642 'Spare': '0', 643 } 644 645 bits = encode(msgDict) 646 if 'binary'==options.ioType: print str(bits) 647 elif 'nmeapayload'==options.ioType: 648 # FIX: figure out if this might be necessary at compile time 649 print "bitLen",len(bits) 650 bitLen=len(bits) 651 if bitLen%6!=0: 652 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 653 print "result:",binary.bitvectoais6(bits)[0] 654 655 656 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 657 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 658 else: sys.exit('ERROR: unknown ioType. Help!') 659 660 661 if options.sqlCreate: 662 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 663 664 if options.latexDefinitionTable: 665 latexDefinitionTable(outfile) 666 667 # For conversion to word tables 668 if options.textDefinitionTable: 669 textDefinitionTable(outfile,options.delimTextDefinitionTable) 670 671 if options.printCsvfieldList: 672 # Make a csv separated list of fields that will be displayed for csv 673 if None == options.fieldList: options.fieldList = fieldList 674 import StringIO 675 buf = StringIO.StringIO() 676 for field in options.fieldList: 677 buf.write(field+',') 678 result = buf.getvalue() 679 if result[-1] == ',': print result[:-1] 680 else: print result 681 682 if options.doDecode: 683 if len(args)==0: args = sys.stdin 684 for msg in args: 685 bv = None 686 687 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 688 # Found nmea 689 # FIX: do checksum 690 bv = binary.ais6tobitvec(msg.split(',')[5]) 691 else: # either binary or nmeapayload... expect mostly nmeapayloads 692 # assumes that an all 0 and 1 string can not be a nmeapayload 693 binaryMsg=True 694 for c in msg: 695 if c not in ('0','1'): 696 binaryMsg=False 697 break 698 if binaryMsg: 699 bv = BitVector(bitstring=msg) 700 else: # nmeapayload 701 bv = binary.ais6tobitvec(msg) 702 703 printFields(decode(bv) 704 ,out=outfile 705 ,format=options.outputType 706 ,fieldList=options.fieldList 707 ,dbType=options.dbType 708 ) 709