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

Source Code for Module ais.allaistypes

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