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

Source Code for Module ais.sls.lockorder

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