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-26 $'.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 alltypesmsg 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("alltypesmsg:\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 continue 439 440 if key not in toPgFields and key not in fromPgFields: 441 if type(params[key])==Decimal: i.add(key,float(params[key])) 442 else: i.add(key,params[key]) 443 else: 444 if key in fromPgFields: 445 val = params[key] 446 # Had better be a WKT type like POINT(-88.1 30.321) 447 i.addPostGIS(key,val) 448 finished.append(key) 449 else: 450 # Need to construct the type. 451 pgName = toPgFields[key] 452 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 453 valStr=pgTypes[pgName]+'(' 454 vals = [] 455 for nonPgKey in fromPgFields[pgName]: 456 vals.append(str(params[nonPgKey])) 457 finished.append(nonPgKey) 458 valStr+=' '.join(vals)+')' 459 i.addPostGIS(pgName,valStr) 460 else: 461 for key in params: 462 if type(params[key])==Decimal: i.add(key,float(params[key])) 463 else: i.add(key,params[key]) 464 465 if None != extraParams: 466 for key in extraParams: 467 i.add(key,extraParams[key]) 468 469 return i
470 471 472 ###################################################################### 473 # UNIT TESTING 474 ###################################################################### 475 import unittest
476 -def testParams():
477 '''Return a params file base on the testvalue tags. 478 @rtype: dict 479 @return: params based on testvalue tags 480 ''' 481 params = {} 482 params['dac'] = 366 483 params['reqDecimal'] = Decimal('122') 484 params['unavail_uint'] = 2 485 params['anUInt'] = 1 486 params['anInt'] = -1 487 params['aBool'] = True 488 params['aStr'] = 'ASDF1' 489 params['anUDecimal'] = Decimal('9.5') 490 params['aDecimal'] = Decimal('-9.6') 491 params['aFloat'] = -1234.5678 492 493 return params
494
495 -class Testalltypesmsg(unittest.TestCase):
496 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
497 - def testEncodeDecode(self):
498 499 params = testParams() 500 bits = encode(params) 501 r = decode(bits) 502 503 # Check that each parameter came through ok. 504 self.failUnlessEqual(r['dac'],params['dac']) 505 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],0) 506 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint']) 507 self.failUnlessEqual(r['anUInt'],params['anUInt']) 508 self.failUnlessEqual(r['anInt'],params['anInt']) 509 self.failUnlessEqual(r['aBool'],params['aBool']) 510 self.failUnlessEqual(r['aStr'],params['aStr']) 511 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1) 512 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0) 513 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
514
515 -def addMsgOptions(parser):
516 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 517 help='decode a "alltypesmsg" AIS message') 518 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 519 help='encode a "alltypesmsg" AIS message') 520 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int' 521 ,help='Field parameter value [default: %default]') 522 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int' 523 ,help='Field parameter value [default: %default]') 524 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int' 525 ,help='Field parameter value [default: %default]') 526 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int' 527 ,help='Field parameter value [default: %default]') 528 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string' 529 ,help='Field parameter value [default: %default]') 530 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string' 531 ,help='Field parameter value [default: %default]') 532 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string' 533 ,help='Field parameter value [default: %default]') 534 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float' 535 ,help='Field parameter value [default: %default]')
536 537 ############################################################ 538 if __name__=='__main__': 539 540 from optparse import OptionParser 541 parser = OptionParser(usage="%prog [options]", 542 version="%prog "+__version__) 543 544 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 545 help='run the documentation tests') 546 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 547 help='run the unit tests') 548 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 549 help='Make the test output verbose') 550 551 # FIX: remove nmea from binary messages. No way to build the whole packet? 552 # FIX: or build the surrounding msg 8 for a broadcast? 553 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 554 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 555 ,default='nmeapayload' 556 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 557 558 559 outputChoices = ('std','html','csv','sql' ) 560 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 561 ,default='std' 562 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 563 564 parser.add_option('-o','--output',dest='outputFileName',default=None, 565 help='Name of the python file to write [default: stdout]') 566 567 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 568 choices=fieldList, 569 help='Which fields to include in the output. Currently only for csv output [default: all]') 570 571 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 572 help='Print the field name for csv') 573 574 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 575 help='Print out an sql create command for the table.') 576 577 dbChoices = ('sqlite','postgres') 578 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 579 ,choices=dbChoices,type='choice' 580 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 581 582 addMsgOptions(parser) 583 584 (options,args) = parser.parse_args() 585 success=True 586 587 if options.doctest: 588 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 589 sys.argv= [sys.argv[0]] 590 if options.verbose: sys.argv.append('-v') 591 import doctest 592 numfail,numtests=doctest.testmod() 593 if numfail==0: print 'ok' 594 else: 595 print 'FAILED' 596 success=False 597 598 if not success: sys.exit('Something Failed') 599 del success # Hide success from epydoc 600 601 if options.unittest: 602 sys.argv = [sys.argv[0]] 603 if options.verbose: sys.argv.append('-v') 604 unittest.main() 605 606 outfile = sys.stdout 607 if None!=options.outputFileName: 608 outfile = file(options.outputFileName,'w') 609 610 611 if options.doEncode: 612 # First make sure all non required options are specified 613 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField") 614 if None==options.anUIntField: parser.error("missing value for anUIntField") 615 if None==options.anIntField: parser.error("missing value for anIntField") 616 if None==options.aBoolField: parser.error("missing value for aBoolField") 617 if None==options.aStrField: parser.error("missing value for aStrField") 618 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField") 619 if None==options.aDecimalField: parser.error("missing value for aDecimalField") 620 if None==options.aFloatField: parser.error("missing value for aFloatField") 621 msgDict={ 622 'dac': '366', 623 'reqDecimal': '122', 624 'unavail_uint': options.unavail_uintField, 625 'anUInt': options.anUIntField, 626 'anInt': options.anIntField, 627 'aBool': options.aBoolField, 628 'aStr': options.aStrField, 629 'anUDecimal': options.anUDecimalField, 630 'aDecimal': options.aDecimalField, 631 'aFloat': options.aFloatField, 632 } 633 634 bits = encode(msgDict) 635 if 'binary'==options.ioType: print str(bits) 636 elif 'nmeapayload'==options.ioType: 637 # FIX: figure out if this might be necessary at compile time 638 print "bitLen",len(bits) 639 bitLen=len(bits) 640 if bitLen%6!=0: 641 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 642 print "result:",binary.bitvectoais6(bits)[0] 643 644 645 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 646 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 647 else: sys.exit('ERROR: unknown ioType. Help!') 648 649 650 if options.sqlCreate: 651 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 652 653 if options.printCsvfieldList: 654 # Make a csv separated list of fields that will be displayed for csv 655 if None == options.fieldList: options.fieldList = fieldList 656 import StringIO 657 buf = StringIO.StringIO() 658 for field in options.fieldList: 659 buf.write(field+',') 660 result = buf.getvalue() 661 if result[-1] == ',': print result[:-1] 662 else: print result 663 664 if options.doDecode: 665 for msg in args: 666 bv = None 667 668 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 669 # Found nmea 670 # FIX: do checksum 671 bv = binary.ais6tobitvec(msg.split(',')[5]) 672 else: # either binary or nmeapayload... expect mostly nmeapayloads 673 # assumes that an all 0 and 1 string can not be a nmeapayload 674 binaryMsg=True 675 for c in msg: 676 if c not in ('0','1'): 677 binaryMsg=False 678 break 679 if binaryMsg: 680 bv = BitVector(bitstring=msg) 681 else: # nmeapayload 682 bv = binary.ais6tobitvec(msg) 683 684 printFields(decode(bv) 685 ,out=outfile 686 ,format=options.outputType 687 ,fieldList=options.fieldList 688 ,dbType=options.dbType 689 ) 690