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-03-31 $'.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 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 366 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
367
368 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
369 ''' 370 Return the sqlhelp object to create the table. 371 372 @param fields: which fields to put in the create. Defaults to all. 373 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 374 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 375 @type addCoastGuardFields: bool 376 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 377 @return: An object that can be used to generate a return 378 @rtype: sqlhelp.create 379 ''' 380 if None == fields: fields = fieldList 381 import sqlhelp 382 c = sqlhelp.create('alltypesmsg',dbType=dbType) 383 c.addPrimaryKey() 384 if 'dac' in fields: c.addInt ('dac') 385 if 'reqDecimal' in fields: c.addDecimal('reqDecimal',3,0) 386 if 'unavail_uint' in fields: c.addInt ('unavail_uint') 387 if 'anUInt' in fields: c.addInt ('anUInt') 388 if 'anInt' in fields: c.addInt ('anInt') 389 if 'aBool' in fields: c.addBool('aBool') 390 if 'aStr' in fields: c.addVarChar('aStr',5) 391 if 'anUDecimal' in fields: c.addDecimal('anUDecimal',5,1) 392 if 'aDecimal' in fields: c.addDecimal('aDecimal',4,0) 393 if 'aFloat' in fields: c.addReal('aFloat') 394 395 if addCoastGuardFields: 396 # c.addInt('cg_rssi') # Relative signal strength indicator 397 # c.addInt('cg_d') # dBm receive strength 398 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 399 # c.addInt('cg_S') # Slot received in 400 # c.addVarChar('cg_x',10) # Idonno 401 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 402 c.addInt('cg_sec') # UTC seconds since the epoch 403 404 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 405 406 return c
407
408 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
409 ''' 410 Return the SQL INSERT command for this message type 411 @param params: dictionary of values keyed by field name 412 @param outfile: file like object to print to. 413 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 414 @return: sql create string 415 @rtype: str 416 417 @see: sqlCreate 418 ''' 419 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
420 421
422 -def sqlInsert(params,extraParams=None,dbType='postgres'):
423 ''' 424 Give the SQL INSERT statement 425 @param params: dict keyed by field name of values 426 @param extraParams: any extra fields that you have created beyond the normal ais message fields 427 @rtype: sqlhelp.insert 428 @return: insert class instance 429 @todo: allow optional type checking of params? 430 @warning: this will take invalid keys happily and do what??? 431 ''' 432 import sqlhelp 433 i = sqlhelp.insert('alltypesmsg',dbType=dbType) 434 435 if dbType=='postgres': 436 finished = [] 437 for key in params: 438 if key in finished: 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 # LATEX SUPPORT 474 ###################################################################### 475
476 -def latexDefinitionTable(outfile=sys.stdout 477 ):
478 ''' 479 Return the LaTeX definition table for this message type 480 @param outfile: file like object to print to. 481 @type outfile: file obj 482 @return: LaTeX table string via the outfile 483 @rtype: str 484 485 ''' 486 o = outfile 487 488 o.write(''' 489 \\begin{table}%[htb] 490 \\centering 491 \\begin{tabular}{|l|c|l|} 492 \\hline 493 Parameter & Number of bits & Description 494 \\\\ \\hline\\hline 495 dac & 16 & Designated Area Code \\\\ \hline 496 reqDecimal & 8 & required decimal value... FIX: scale or no? \\\\ \hline 497 unavail\_uint & 2 & Unavailable unsigned integer \\\\ \hline 498 anUInt & 2 & NO unavailable unsigned integer \\\\ \hline 499 anInt & 3 & NO unavailable signed integer \\\\ \hline 500 aBool & 1 & Simple bool \\\\ \hline 501 aStr & 30 & An ais string of 5 characters \\\\ \hline 502 anUDecimal & 16 & An unsigned decimal. Allow smaller numbers \\\\ \hline 503 aDecimal & 16 & A decimal \\\\ \hline 504 aFloat & 32 & An IEEE floating point number\\\\ \\hline \\hline 505 Total bits & 126 & Appears to take 1 slot with 42 pad bits to fill the last slot \\\\ \\hline 506 \\end{tabular} 507 \\caption{AIS message number 8: Message to demonstrate all the ais types. Good for testing} 508 \\label{tab:alltypesmsg} 509 \\end{table} 510 ''')
511 512 513 ###################################################################### 514 # UNIT TESTING 515 ###################################################################### 516 import unittest
517 -def testParams():
518 '''Return a params file base on the testvalue tags. 519 @rtype: dict 520 @return: params based on testvalue tags 521 ''' 522 params = {} 523 params['dac'] = 366 524 params['reqDecimal'] = Decimal('122') 525 params['unavail_uint'] = 2 526 params['anUInt'] = 1 527 params['anInt'] = -1 528 params['aBool'] = True 529 params['aStr'] = 'ASDF1' 530 params['anUDecimal'] = Decimal('9.5') 531 params['aDecimal'] = Decimal('-9.6') 532 params['aFloat'] = -1234.5678 533 534 return params
535
536 -class Testalltypesmsg(unittest.TestCase):
537 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
538 - def testEncodeDecode(self):
539 540 params = testParams() 541 bits = encode(params) 542 r = decode(bits) 543 544 # Check that each parameter came through ok. 545 self.failUnlessEqual(r['dac'],params['dac']) 546 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],0) 547 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint']) 548 self.failUnlessEqual(r['anUInt'],params['anUInt']) 549 self.failUnlessEqual(r['anInt'],params['anInt']) 550 self.failUnlessEqual(r['aBool'],params['aBool']) 551 self.failUnlessEqual(r['aStr'],params['aStr']) 552 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1) 553 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0) 554 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
555
556 -def addMsgOptions(parser):
557 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 558 help='decode a "alltypesmsg" AIS message') 559 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 560 help='encode a "alltypesmsg" AIS message') 561 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int' 562 ,help='Field parameter value [default: %default]') 563 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int' 564 ,help='Field parameter value [default: %default]') 565 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int' 566 ,help='Field parameter value [default: %default]') 567 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int' 568 ,help='Field parameter value [default: %default]') 569 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string' 570 ,help='Field parameter value [default: %default]') 571 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string' 572 ,help='Field parameter value [default: %default]') 573 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string' 574 ,help='Field parameter value [default: %default]') 575 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float' 576 ,help='Field parameter value [default: %default]')
577 578 ############################################################ 579 if __name__=='__main__': 580 581 from optparse import OptionParser 582 parser = OptionParser(usage="%prog [options]", 583 version="%prog "+__version__) 584 585 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 586 help='run the documentation tests') 587 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 588 help='run the unit tests') 589 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 590 help='Make the test output verbose') 591 592 # FIX: remove nmea from binary messages. No way to build the whole packet? 593 # FIX: or build the surrounding msg 8 for a broadcast? 594 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 595 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 596 ,default='nmeapayload' 597 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 598 599 600 outputChoices = ('std','html','csv','sql' ) 601 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 602 ,default='std' 603 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 604 605 parser.add_option('-o','--output',dest='outputFileName',default=None, 606 help='Name of the python file to write [default: stdout]') 607 608 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 609 choices=fieldList, 610 help='Which fields to include in the output. Currently only for csv output [default: all]') 611 612 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 613 help='Print the field name for csv') 614 615 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 616 help='Print out an sql create command for the table.') 617 618 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 619 help='Print a LaTeX table of the type') 620 621 dbChoices = ('sqlite','postgres') 622 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 623 ,choices=dbChoices,type='choice' 624 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 625 626 addMsgOptions(parser) 627 628 (options,args) = parser.parse_args() 629 success=True 630 631 if options.doctest: 632 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 633 sys.argv= [sys.argv[0]] 634 if options.verbose: sys.argv.append('-v') 635 import doctest 636 numfail,numtests=doctest.testmod() 637 if numfail==0: print 'ok' 638 else: 639 print 'FAILED' 640 success=False 641 642 if not success: sys.exit('Something Failed') 643 del success # Hide success from epydoc 644 645 if options.unittest: 646 sys.argv = [sys.argv[0]] 647 if options.verbose: sys.argv.append('-v') 648 unittest.main() 649 650 outfile = sys.stdout 651 if None!=options.outputFileName: 652 outfile = file(options.outputFileName,'w') 653 654 655 if options.doEncode: 656 # First make sure all non required options are specified 657 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField") 658 if None==options.anUIntField: parser.error("missing value for anUIntField") 659 if None==options.anIntField: parser.error("missing value for anIntField") 660 if None==options.aBoolField: parser.error("missing value for aBoolField") 661 if None==options.aStrField: parser.error("missing value for aStrField") 662 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField") 663 if None==options.aDecimalField: parser.error("missing value for aDecimalField") 664 if None==options.aFloatField: parser.error("missing value for aFloatField") 665 msgDict={ 666 'dac': '366', 667 'reqDecimal': '122', 668 'unavail_uint': options.unavail_uintField, 669 'anUInt': options.anUIntField, 670 'anInt': options.anIntField, 671 'aBool': options.aBoolField, 672 'aStr': options.aStrField, 673 'anUDecimal': options.anUDecimalField, 674 'aDecimal': options.aDecimalField, 675 'aFloat': options.aFloatField, 676 } 677 678 bits = encode(msgDict) 679 if 'binary'==options.ioType: print str(bits) 680 elif 'nmeapayload'==options.ioType: 681 # FIX: figure out if this might be necessary at compile time 682 print "bitLen",len(bits) 683 bitLen=len(bits) 684 if bitLen%6!=0: 685 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 686 print "result:",binary.bitvectoais6(bits)[0] 687 688 689 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 690 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 691 else: sys.exit('ERROR: unknown ioType. Help!') 692 693 694 if options.sqlCreate: 695 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 696 697 if options.latexDefinitionTable: 698 latexDefinitionTable(outfile) 699 700 if options.printCsvfieldList: 701 # Make a csv separated list of fields that will be displayed for csv 702 if None == options.fieldList: options.fieldList = fieldList 703 import StringIO 704 buf = StringIO.StringIO() 705 for field in options.fieldList: 706 buf.write(field+',') 707 result = buf.getvalue() 708 if result[-1] == ',': print result[:-1] 709 else: print result 710 711 if options.doDecode: 712 for msg in args: 713 bv = None 714 715 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 716 # Found nmea 717 # FIX: do checksum 718 bv = binary.ais6tobitvec(msg.split(',')[5]) 719 else: # either binary or nmeapayload... expect mostly nmeapayloads 720 # assumes that an all 0 and 1 string can not be a nmeapayload 721 binaryMsg=True 722 for c in msg: 723 if c not in ('0','1'): 724 binaryMsg=False 725 break 726 if binaryMsg: 727 bv = BitVector(bitstring=msg) 728 else: # nmeapayload 729 bv = binary.ais6tobitvec(msg) 730 731 printFields(decode(bv) 732 ,out=outfile 733 ,format=options.outputType 734 ,fieldList=options.fieldList 735 ,dbType=options.dbType 736 ) 737