Package ais :: Package sls :: Module lockschedule
[hide private]
[frames] | no frames]

Source Code for Module ais.sls.lockschedule

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