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-11-07 $'.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 # Text Definition 514 ###################################################################### 515
516 -def textDefinitionTable(outfile=sys.stdout 517 ,delim='\t' 518 ):
519 ''' 520 Return the text definition table for this message type 521 @param outfile: file like object to print to. 522 @type outfile: file obj 523 @return: text table string via the outfile 524 @rtype: str 525 526 ''' 527 o = outfile 528 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description 529 dac'''+delim+'''16'''+delim+'''Designated Area Code 530 reqDecimal'''+delim+'''8'''+delim+'''required decimal value... FIX: scale or no? 531 unavail_uint'''+delim+'''2'''+delim+'''Unavailable unsigned integer 532 anUInt'''+delim+'''2'''+delim+'''NO unavailable unsigned integer 533 anInt'''+delim+'''3'''+delim+'''NO unavailable signed integer 534 aBool'''+delim+'''1'''+delim+'''Simple bool 535 aStr'''+delim+'''30'''+delim+'''An ais string of 5 characters 536 anUDecimal'''+delim+'''16'''+delim+'''An unsigned decimal. Allow smaller numbers 537 aDecimal'''+delim+'''16'''+delim+'''A decimal 538 aFloat'''+delim+'''32'''+delim+'''An IEEE floating point number 539 Total bits'''+delim+'''126'''+delim+'''Appears to take 1 slot with 42 pad bits to fill the last slot''')
540 541 542 ###################################################################### 543 # UNIT TESTING 544 ###################################################################### 545 import unittest
546 -def testParams():
547 '''Return a params file base on the testvalue tags. 548 @rtype: dict 549 @return: params based on testvalue tags 550 ''' 551 params = {} 552 params['dac'] = 366 553 params['reqDecimal'] = Decimal('122') 554 params['unavail_uint'] = 2 555 params['anUInt'] = 1 556 params['anInt'] = -1 557 params['aBool'] = True 558 params['aStr'] = 'ASDF1' 559 params['anUDecimal'] = Decimal('9.5') 560 params['aDecimal'] = Decimal('-9.6') 561 params['aFloat'] = -1234.5678 562 563 return params
564
565 -class Testalltypesmsg(unittest.TestCase):
566 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
567 - def testEncodeDecode(self):
568 569 params = testParams() 570 bits = encode(params) 571 r = decode(bits) 572 573 # Check that each parameter came through ok. 574 self.failUnlessEqual(r['dac'],params['dac']) 575 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],0) 576 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint']) 577 self.failUnlessEqual(r['anUInt'],params['anUInt']) 578 self.failUnlessEqual(r['anInt'],params['anInt']) 579 self.failUnlessEqual(r['aBool'],params['aBool']) 580 self.failUnlessEqual(r['aStr'],params['aStr']) 581 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1) 582 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0) 583 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
584
585 -def addMsgOptions(parser):
586 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 587 help='decode a "alltypesmsg" AIS message') 588 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 589 help='encode a "alltypesmsg" AIS message') 590 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int' 591 ,help='Field parameter value [default: %default]') 592 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int' 593 ,help='Field parameter value [default: %default]') 594 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int' 595 ,help='Field parameter value [default: %default]') 596 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int' 597 ,help='Field parameter value [default: %default]') 598 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string' 599 ,help='Field parameter value [default: %default]') 600 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string' 601 ,help='Field parameter value [default: %default]') 602 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string' 603 ,help='Field parameter value [default: %default]') 604 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float' 605 ,help='Field parameter value [default: %default]')
606 607 ############################################################ 608 if __name__=='__main__': 609 610 from optparse import OptionParser 611 parser = OptionParser(usage="%prog [options]", 612 version="%prog "+__version__) 613 614 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 615 help='run the documentation tests') 616 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 617 help='run the unit tests') 618 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 619 help='Make the test output verbose') 620 621 # FIX: remove nmea from binary messages. No way to build the whole packet? 622 # FIX: or build the surrounding msg 8 for a broadcast? 623 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 624 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 625 ,default='nmeapayload' 626 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 627 628 629 outputChoices = ('std','html','csv','sql' ) 630 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 631 ,default='std' 632 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 633 634 parser.add_option('-o','--output',dest='outputFileName',default=None, 635 help='Name of the python file to write [default: stdout]') 636 637 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 638 choices=fieldList, 639 help='Which fields to include in the output. Currently only for csv output [default: all]') 640 641 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 642 help='Print the field name for csv') 643 644 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 645 help='Print out an sql create command for the table.') 646 647 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 648 help='Print a LaTeX table of the type') 649 650 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true', 651 help='Print delimited table of the type (for Word table importing)') 652 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t' 653 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)') 654 655 656 dbChoices = ('sqlite','postgres') 657 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 658 ,choices=dbChoices,type='choice' 659 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 660 661 addMsgOptions(parser) 662 663 (options,args) = parser.parse_args() 664 success=True 665 666 if options.doctest: 667 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 668 sys.argv= [sys.argv[0]] 669 if options.verbose: sys.argv.append('-v') 670 import doctest 671 numfail,numtests=doctest.testmod() 672 if numfail==0: print 'ok' 673 else: 674 print 'FAILED' 675 success=False 676 677 if not success: sys.exit('Something Failed') 678 del success # Hide success from epydoc 679 680 if options.unittest: 681 sys.argv = [sys.argv[0]] 682 if options.verbose: sys.argv.append('-v') 683 unittest.main() 684 685 outfile = sys.stdout 686 if None!=options.outputFileName: 687 outfile = file(options.outputFileName,'w') 688 689 690 if options.doEncode: 691 # First make sure all non required options are specified 692 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField") 693 if None==options.anUIntField: parser.error("missing value for anUIntField") 694 if None==options.anIntField: parser.error("missing value for anIntField") 695 if None==options.aBoolField: parser.error("missing value for aBoolField") 696 if None==options.aStrField: parser.error("missing value for aStrField") 697 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField") 698 if None==options.aDecimalField: parser.error("missing value for aDecimalField") 699 if None==options.aFloatField: parser.error("missing value for aFloatField") 700 msgDict={ 701 'dac': '366', 702 'reqDecimal': '122', 703 'unavail_uint': options.unavail_uintField, 704 'anUInt': options.anUIntField, 705 'anInt': options.anIntField, 706 'aBool': options.aBoolField, 707 'aStr': options.aStrField, 708 'anUDecimal': options.anUDecimalField, 709 'aDecimal': options.aDecimalField, 710 'aFloat': options.aFloatField, 711 } 712 713 bits = encode(msgDict) 714 if 'binary'==options.ioType: print str(bits) 715 elif 'nmeapayload'==options.ioType: 716 # FIX: figure out if this might be necessary at compile time 717 print "bitLen",len(bits) 718 bitLen=len(bits) 719 if bitLen%6!=0: 720 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 721 print "result:",binary.bitvectoais6(bits)[0] 722 723 724 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 725 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 726 else: sys.exit('ERROR: unknown ioType. Help!') 727 728 729 if options.sqlCreate: 730 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 731 732 if options.latexDefinitionTable: 733 latexDefinitionTable(outfile) 734 735 # For conversion to word tables 736 if options.textDefinitionTable: 737 textDefinitionTable(outfile,options.delimTextDefinitionTable) 738 739 if options.printCsvfieldList: 740 # Make a csv separated list of fields that will be displayed for csv 741 if None == options.fieldList: options.fieldList = fieldList 742 import StringIO 743 buf = StringIO.StringIO() 744 for field in options.fieldList: 745 buf.write(field+',') 746 result = buf.getvalue() 747 if result[-1] == ',': print result[:-1] 748 else: print result 749 750 if options.doDecode: 751 if len(args)==0: args = sys.stdin 752 for msg in args: 753 bv = None 754 755 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 756 # Found nmea 757 # FIX: do checksum 758 bv = binary.ais6tobitvec(msg.split(',')[5]) 759 else: # either binary or nmeapayload... expect mostly nmeapayloads 760 # assumes that an all 0 and 1 string can not be a nmeapayload 761 binaryMsg=True 762 for c in msg: 763 if c not in ('0','1'): 764 binaryMsg=False 765 break 766 if binaryMsg: 767 bv = BitVector(bitstring=msg) 768 else: # nmeapayload 769 bv = binary.ais6tobitvec(msg) 770 771 printFields(decode(bv) 772 ,out=outfile 773 ,format=options.outputType 774 ,fieldList=options.fieldList 775 ,dbType=options.dbType 776 ) 777