Package ais :: Module sls_waterlevel
[hide private]
[frames] | no frames]

Source Code for Module ais.sls_waterlevel

  1  #!/usr/bin/env python 
  2   
  3  __version__ = '$Revision: 4791 $'.split()[1] 
  4  __date__ = '$Date: 2007-02-05 $'.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  ''' 
 34   
 35  import sys 
 36  from decimal import Decimal 
 37  from BitVector import BitVector 
 38   
 39  import binary, aisstring 
 40   
 41  # FIX: check to see if these will be needed 
 42  TrueBV  = BitVector(bitstring="1") 
 43  "Why always rebuild the True bit?  This should speed things up a bunch" 
 44  FalseBV = BitVector(bitstring="0") 
 45  "Why always rebuild the False bit?  This should speed things up a bunch" 
 46   
 47   
 48  fieldList = [ 
 49          'time_month', 
 50          'time_day', 
 51          'time_hour', 
 52          'time_min', 
 53          'stationid', 
 54          'pos_longitude', 
 55          'pos_latitude', 
 56          'type', 
 57          'waterlevel', 
 58          'datum', 
 59          'reserved', 
 60  ] 
 61   
62 -def encode(params, validate=False):
63 '''Create a sls_waterlevel binary message payload to pack into an AIS Msg sls_waterlevel. 64 65 Fields in params: 66 - time_month(uint): Time tag of measurement month 1..12 67 - time_day(uint): Time tag of measurement day of the month 1..31 68 - time_hour(uint): Time tag of measurement UTC hours 0..23 69 - time_min(uint): Time tag of measurement minutes 70 - stationid(aisstr6): Character identifier of the station. Usually a number. 71 - pos_longitude(decimal): Location of measurement East West location 72 - pos_latitude(decimal): Location of measurement North South location 73 - type(uint): How to interpret the water level 74 - waterlevel(int): Water level in centimeters 75 - datum(uint): What reference datum applies to the value 76 - reserved(uint): Reserved bits for future use (field automatically set to "0") 77 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 78 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 79 @rtype: BitVector 80 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 81 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 82 ''' 83 84 bvList = [] 85 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4)) 86 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5)) 87 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5)) 88 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6)) 89 if 'stationid' in params: 90 bvList.append(aisstring.encode(params['stationid'],42)) 91 else: 92 bvList.append(aisstring.encode('@@@@@@@',42)) 93 if 'pos_longitude' in params: 94 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25)) 95 else: 96 bvList.append(binary.bvFromSignedInt(10860000,25)) 97 if 'pos_latitude' in params: 98 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24)) 99 else: 100 bvList.append(binary.bvFromSignedInt(5460000,24)) 101 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),1)) 102 if 'waterlevel' in params: 103 bvList.append(binary.bvFromSignedInt(params['waterlevel'],16)) 104 else: 105 bvList.append(binary.bvFromSignedInt(-32768,16)) 106 if 'datum' in params: 107 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['datum']),2)) 108 else: 109 bvList.append(binary.setBitVectorSize(BitVector(intVal=31),2)) 110 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),14)) 111 112 return binary.joinBV(bvList)
113
114 -def decode(bv, validate=False):
115 '''Unpack a sls_waterlevel message 116 117 Fields in params: 118 - time_month(uint): Time tag of measurement month 1..12 119 - time_day(uint): Time tag of measurement day of the month 1..31 120 - time_hour(uint): Time tag of measurement UTC hours 0..23 121 - time_min(uint): Time tag of measurement minutes 122 - stationid(aisstr6): Character identifier of the station. Usually a number. 123 - pos_longitude(decimal): Location of measurement East West location 124 - pos_latitude(decimal): Location of measurement North South location 125 - type(uint): How to interpret the water level 126 - waterlevel(int): Water level in centimeters 127 - datum(uint): What reference datum applies to the value 128 - reserved(uint): Reserved bits for future use (field automatically set to "0") 129 @type bv: BitVector 130 @param bv: Bits defining a message 131 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 132 @rtype: dict 133 @return: params 134 ''' 135 136 #Would be nice to check the bit count here.. 137 #if validate: 138 # assert (len(bv)==FIX: SOME NUMBER) 139 r = {} 140 r['time_month']=int(bv[0:4]) 141 r['time_day']=int(bv[4:9]) 142 r['time_hour']=int(bv[9:14]) 143 r['time_min']=int(bv[14:20]) 144 r['stationid']=aisstring.decode(bv[20:62]) 145 r['pos_longitude']=Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000') 146 r['pos_latitude']=Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000') 147 r['type']=int(bv[111:112]) 148 r['waterlevel']=binary.signedIntFromBV(bv[112:128]) 149 r['datum']=int(bv[128:130]) 150 r['reserved']=0 151 return r
152
153 -def decodetime_month(bv, validate=False):
154 return int(bv[0:4])
155
156 -def decodetime_day(bv, validate=False):
157 return int(bv[4:9])
158
159 -def decodetime_hour(bv, validate=False):
160 return int(bv[9:14])
161
162 -def decodetime_min(bv, validate=False):
163 return int(bv[14:20])
164
165 -def decodestationid(bv, validate=False):
166 return aisstring.decode(bv[20:62])
167
168 -def decodepos_longitude(bv, validate=False):
169 return Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000')
170
171 -def decodepos_latitude(bv, validate=False):
172 return Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000')
173
174 -def decodetype(bv, validate=False):
175 return int(bv[111:112])
176
177 -def decodewaterlevel(bv, validate=False):
178 return binary.signedIntFromBV(bv[112:128])
179
180 -def decodedatum(bv, validate=False):
181 return int(bv[128:130])
182
183 -def decodereserved(bv, validate=False):
184 return 0
185 186
187 -def printHtml(params, out=sys.stdout):
188 out.write("<h3>sls_waterlevel<h3>\n") 189 out.write("<table border=\"1\">\n") 190 out.write("<tr bgcolor=\"orange\">\n") 191 out.write("<th align=\"left\">Field Name</th>\n") 192 out.write("<th align=\"left\">Type</th>\n") 193 out.write("<th align=\"left\">Value</th>\n") 194 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 195 out.write("<th align=\"left\">Units</th>\n") 196 out.write("\n") 197 out.write("<tr>\n") 198 out.write("<td>time_month</td>\n") 199 out.write("<td>uint</td>\n") 200 if 'time_month' in params: 201 out.write(" <td>"+str(params['time_month'])+"</td>\n") 202 out.write(" <td>"+str(params['time_month'])+"</td>\n") 203 out.write("</tr>\n") 204 out.write("\n") 205 out.write("<tr>\n") 206 out.write("<td>time_day</td>\n") 207 out.write("<td>uint</td>\n") 208 if 'time_day' in params: 209 out.write(" <td>"+str(params['time_day'])+"</td>\n") 210 out.write(" <td>"+str(params['time_day'])+"</td>\n") 211 out.write("</tr>\n") 212 out.write("\n") 213 out.write("<tr>\n") 214 out.write("<td>time_hour</td>\n") 215 out.write("<td>uint</td>\n") 216 if 'time_hour' in params: 217 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 218 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 219 out.write("</tr>\n") 220 out.write("\n") 221 out.write("<tr>\n") 222 out.write("<td>time_min</td>\n") 223 out.write("<td>uint</td>\n") 224 if 'time_min' in params: 225 out.write(" <td>"+str(params['time_min'])+"</td>\n") 226 out.write(" <td>"+str(params['time_min'])+"</td>\n") 227 out.write("</tr>\n") 228 out.write("\n") 229 out.write("<tr>\n") 230 out.write("<td>stationid</td>\n") 231 out.write("<td>aisstr6</td>\n") 232 if 'stationid' in params: 233 out.write(" <td>"+str(params['stationid'])+"</td>\n") 234 out.write(" <td>"+str(params['stationid'])+"</td>\n") 235 out.write("</tr>\n") 236 out.write("\n") 237 out.write("<tr>\n") 238 out.write("<td>pos_longitude</td>\n") 239 out.write("<td>decimal</td>\n") 240 if 'pos_longitude' in params: 241 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 242 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 243 out.write("<td>degrees</td>\n") 244 out.write("</tr>\n") 245 out.write("\n") 246 out.write("<tr>\n") 247 out.write("<td>pos_latitude</td>\n") 248 out.write("<td>decimal</td>\n") 249 if 'pos_latitude' in params: 250 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n") 251 out.write(" <td>"+str(params['pos_latitude'])+"</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>type</td>\n") 257 out.write("<td>uint</td>\n") 258 if 'type' in params: 259 out.write(" <td>"+str(params['type'])+"</td>\n") 260 if str(params['type']) in typeDecodeLut: 261 out.write("<td>"+typeDecodeLut[str(params['type'])]+"</td>") 262 else: 263 out.write("<td><i>Missing LUT entry</i></td>") 264 out.write("</tr>\n") 265 out.write("\n") 266 out.write("<tr>\n") 267 out.write("<td>waterlevel</td>\n") 268 out.write("<td>int</td>\n") 269 if 'waterlevel' in params: 270 out.write(" <td>"+str(params['waterlevel'])+"</td>\n") 271 out.write(" <td>"+str(params['waterlevel'])+"</td>\n") 272 out.write("<td>cm</td>\n") 273 out.write("</tr>\n") 274 out.write("\n") 275 out.write("<tr>\n") 276 out.write("<td>datum</td>\n") 277 out.write("<td>uint</td>\n") 278 if 'datum' in params: 279 out.write(" <td>"+str(params['datum'])+"</td>\n") 280 if str(params['datum']) in datumDecodeLut: 281 out.write("<td>"+datumDecodeLut[str(params['datum'])]+"</td>") 282 else: 283 out.write("<td><i>Missing LUT entry</i></td>") 284 out.write("</tr>\n") 285 out.write("\n") 286 out.write("<tr>\n") 287 out.write("<td>reserved</td>\n") 288 out.write("<td>uint</td>\n") 289 if 'reserved' in params: 290 out.write(" <td>"+str(params['reserved'])+"</td>\n") 291 out.write(" <td>"+str(params['reserved'])+"</td>\n") 292 out.write("</tr>\n") 293 out.write("</table>\n")
294 295
296 -def printKml(params, out=sys.stdout):
297 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer''' 298 out.write("\ <Placemark>\n") 299 out.write("\t <name>"+str(params['stationid'])+"</name>\n") 300 out.write("\t\t<description>\n") 301 import StringIO 302 buf = StringIO.StringIO() 303 printHtml(params,buf) 304 import cgi 305 out.write(cgi.escape(buf.getvalue())) 306 out.write("\t\t</description>\n") 307 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n") 308 out.write("\t\t<Point>\n") 309 out.write("\t\t\t<coordinates>") 310 out.write(str(params['pos_longitude'])) 311 out.write(',') 312 out.write(str(params['pos_latitude'])) 313 out.write(",0</coordinates>\n") 314 out.write("\t\t</Point>\n") 315 out.write("\t</Placemark>\n")
316
317 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
318 '''Print a reserved message to stdout. 319 320 Fields in params: 321 - time_month(uint): Time tag of measurement month 1..12 322 - time_day(uint): Time tag of measurement day of the month 1..31 323 - time_hour(uint): Time tag of measurement UTC hours 0..23 324 - time_min(uint): Time tag of measurement minutes 325 - stationid(aisstr6): Character identifier of the station. Usually a number. 326 - pos_longitude(decimal): Location of measurement East West location 327 - pos_latitude(decimal): Location of measurement North South location 328 - type(uint): How to interpret the water level 329 - waterlevel(int): Water level in centimeters 330 - datum(uint): What reference datum applies to the value 331 - reserved(uint): Reserved bits for future use (field automatically set to "0") 332 @param params: Dictionary of field names/values. 333 @param out: File like object to write to 334 @rtype: stdout 335 @return: text to out 336 ''' 337 338 if 'std'==format: 339 out.write("reserved:\n") 340 if 'time_month' in params: out.write(" time_month: "+str(params['time_month'])+"\n") 341 if 'time_day' in params: out.write(" time_day: "+str(params['time_day'])+"\n") 342 if 'time_hour' in params: out.write(" time_hour: "+str(params['time_hour'])+"\n") 343 if 'time_min' in params: out.write(" time_min: "+str(params['time_min'])+"\n") 344 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n") 345 if 'pos_longitude' in params: out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n") 346 if 'pos_latitude' in params: out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n") 347 if 'type' in params: out.write(" type: "+str(params['type'])+"\n") 348 if 'waterlevel' in params: out.write(" waterlevel: "+str(params['waterlevel'])+"\n") 349 if 'datum' in params: out.write(" datum: "+str(params['datum'])+"\n") 350 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 351 elif 'csv'==format: 352 if None == options.fieldList: 353 options.fieldList = fieldList 354 needComma = False; 355 for field in fieldList: 356 if needComma: out.write(',') 357 needComma = True 358 if field in params: 359 out.write(str(params[field])) 360 # else: leave it empty 361 out.write("\n") 362 elif 'html'==format: 363 printHtml(params,out) 364 elif 'sql'==format: 365 sqlInsertStr(params,out) 366 elif 'kml'==format: 367 printKml(params,out) 368 elif 'kml-full'==format: 369 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") 370 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n") 371 out.write("<Document>\n") 372 out.write(" <name>sls_waterlevel</name>\n") 373 printKml(params,out) 374 out.write("</Document>\n") 375 out.write("</kml>\n") 376 else: 377 print "ERROR: unknown format:",format 378 assert False 379 380 return # Nothing to return
381 382 typeEncodeLut = { 383 'Relative to datum':'0', 384 'Water depth':'1', 385 } #typeEncodeLut 386 387 typeDecodeLut = { 388 '0':'Relative to datum', 389 '1':'Water depth', 390 } # typeEncodeLut 391 392 datumEncodeLut = { 393 'MLLW':'0', 394 'IGLD-85':'1', 395 'Reserved':'2', 396 'Reserved':'3', 397 } #datumEncodeLut 398 399 datumDecodeLut = { 400 '0':'MLLW', 401 '1':'IGLD-85', 402 '2':'Reserved', 403 '3':'Reserved', 404 } # datumEncodeLut 405 406 ###################################################################### 407 # SQL SUPPORT 408 ###################################################################### 409
410 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None):
411 ''' 412 Return the SQL CREATE command for this message type 413 @param outfile: file like object to print to. 414 @param fields: which fields to put in the create. Defaults to all. 415 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 416 @return: sql create string 417 @rtype: str 418 419 @see: sqlCreate 420 ''' 421 outfile.write(str(sqlCreate(fields,extraFields)))
422
423 -def sqlCreate(fields=None, extraFields=None):
424 ''' 425 Return the sqlhelp object to create the table. 426 427 @param fields: which fields to put in the create. Defaults to all. 428 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 429 @return: An object that can be used to generate a return 430 @rtype: sqlhelp.create 431 ''' 432 if None == fields: fields = fieldList 433 import sqlhelp 434 c = sqlhelp.create('sls_waterlevel') 435 if 'time_month' in fields: c.addInt ('time_month') 436 if 'time_day' in fields: c.addInt ('time_day') 437 if 'time_hour' in fields: c.addInt ('time_hour') 438 if 'time_min' in fields: c.addInt ('time_min') 439 if 'stationid' in fields: c.addVarChar(stationid,7) 440 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4) 441 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4) 442 if 'type' in fields: c.addInt ('type') 443 if 'waterlevel' in fields: c.addInt ('waterlevel') 444 if 'datum' in fields: c.addInt ('datum') 445 if 'reserved' in fields: c.addInt ('reserved') 446 447 return c
448
449 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
450 ''' 451 Return the SQL CREATE command for this message type 452 @param params: dictionary of values keyed by field name 453 @param outfile: file like object to print to. 454 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 455 @return: sql create string 456 @rtype: str 457 458 @see: sqlCreate 459 ''' 460 outfile.write(str(sqlInsert(params,extraParams)))
461 462
463 -def sqlInsert(params,extraParams=None):
464 ''' 465 Give the SQL insert statement 466 @param params: dict keyed by field name of values 467 @param extraParams: any extra fields that you have created beyond the normal ais message fields 468 @rtype: sqlhelp.insert 469 @return: insert class instance 470 @todo: allow optional type checking of params? 471 @warning: this will take invalid keys happily and do what??? 472 ''' 473 import sqlhelp 474 i = sqlhelp.insert('sls_waterlevel') 475 for key in params: i.add(key,params[key]) 476 if None != extraParams: 477 for key in extraParams: 478 i.add(key,extraParams[key]) 479 480 return i
481 482 483 ###################################################################### 484 # UNIT TESTING 485 ###################################################################### 486 import unittest
487 -def testParams():
488 '''Return a params file base on the testvalue tags. 489 @rtype: dict 490 @return: params based on testvalue tags 491 ''' 492 params = {} 493 params['time_month'] = 2 494 params['time_day'] = 28 495 params['time_hour'] = 23 496 params['time_min'] = 45 497 params['stationid'] = 'A234567' 498 params['pos_longitude'] = Decimal('-122.16328') 499 params['pos_latitude'] = Decimal('37.42446') 500 params['type'] = 0 501 params['waterlevel'] = -97 502 params['datum'] = 0 503 params['reserved'] = 0 504 505 return params
506
507 -class Testsls_waterlevel(unittest.TestCase):
508 '''Use testvalue tag text from each type to build test case the sls_waterlevel message'''
509 - def testEncodeDecode(self):
510 511 params = testParams() 512 bits = encode(params) 513 r = decode(bits) 514 515 # Check that each parameter came through ok. 516 self.failUnlessEqual(r['time_month'],params['time_month']) 517 self.failUnlessEqual(r['time_day'],params['time_day']) 518 self.failUnlessEqual(r['time_hour'],params['time_hour']) 519 self.failUnlessEqual(r['time_min'],params['time_min']) 520 self.failUnlessEqual(r['stationid'],params['stationid']) 521 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4) 522 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4) 523 self.failUnlessEqual(r['type'],params['type']) 524 self.failUnlessEqual(r['waterlevel'],params['waterlevel']) 525 self.failUnlessEqual(r['datum'],params['datum']) 526 self.failUnlessEqual(r['reserved'],params['reserved'])
527
528 -def addMsgOptions(parser):
529 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 530 help='decode a "sls_waterlevel" AIS message') 531 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 532 help='encode a "sls_waterlevel" AIS message') 533 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int' 534 ,help='Field parameter value [default: %default]') 535 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int' 536 ,help='Field parameter value [default: %default]') 537 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int' 538 ,help='Field parameter value [default: %default]') 539 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int' 540 ,help='Field parameter value [default: %default]') 541 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string' 542 ,help='Field parameter value [default: %default]') 543 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 544 ,help='Field parameter value [default: %default]') 545 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 546 ,help='Field parameter value [default: %default]') 547 parser.add_option('--type-field', dest='typeField',metavar='uint',type='int' 548 ,help='Field parameter value [default: %default]') 549 parser.add_option('--waterlevel-field', dest='waterlevelField',default=-32768,metavar='int',type='int' 550 ,help='Field parameter value [default: %default]') 551 parser.add_option('--datum-field', dest='datumField',default=31,metavar='uint',type='int' 552 ,help='Field parameter value [default: %default]')
553 554 ############################################################ 555 if __name__=='__main__': 556 557 from optparse import OptionParser 558 parser = OptionParser(usage="%prog [options]", 559 version="%prog "+__version__) 560 561 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 562 help='run the documentation tests') 563 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 564 help='run the unit tests') 565 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 566 help='Make the test output verbose') 567 568 # FIX: remove nmea from binary messages. No way to build the whole packet? 569 # FIX: or build the surrounding msg 8 for a broadcast? 570 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 571 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 572 ,default='nmeapayload' 573 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 574 575 576 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 577 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 578 ,default='std' 579 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 580 581 parser.add_option('-o','--output',dest='outputFileName',default=None, 582 help='Name of the python file to write [default: stdout]') 583 584 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 585 choices=fieldList, 586 help='Which fields to include in the output. Currently only for csv output [default: all]') 587 588 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 589 help='Print the field name for csv') 590 591 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 592 help='Print out an sql create command for the table.') 593 594 addMsgOptions(parser) 595 596 (options,args) = parser.parse_args() 597 success=True 598 599 if options.doctest: 600 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 601 sys.argv= [sys.argv[0]] 602 if options.verbose: sys.argv.append('-v') 603 import doctest 604 numfail,numtests=doctest.testmod() 605 if numfail==0: print 'ok' 606 else: 607 print 'FAILED' 608 success=False 609 610 if not success: sys.exit('Something Failed') 611 del success # Hide success from epydoc 612 613 if options.unittest: 614 sys.argv = [sys.argv[0]] 615 if options.verbose: sys.argv.append('-v') 616 unittest.main() 617 618 outfile = sys.stdout 619 if None!=options.outputFileName: 620 outfile = file(options.outputFileName,'w') 621 622 623 if options.doEncode: 624 # First make sure all non required options are specified 625 if None==options.time_monthField: parser.error("missing value for time_monthField") 626 if None==options.time_dayField: parser.error("missing value for time_dayField") 627 if None==options.time_hourField: parser.error("missing value for time_hourField") 628 if None==options.time_minField: parser.error("missing value for time_minField") 629 if None==options.stationidField: parser.error("missing value for stationidField") 630 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField") 631 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField") 632 if None==options.typeField: parser.error("missing value for typeField") 633 if None==options.waterlevelField: parser.error("missing value for waterlevelField") 634 if None==options.datumField: parser.error("missing value for datumField") 635 msgDict={ 636 'time_month': options.time_monthField, 637 'time_day': options.time_dayField, 638 'time_hour': options.time_hourField, 639 'time_min': options.time_minField, 640 'stationid': options.stationidField, 641 'pos_longitude': options.pos_longitudeField, 642 'pos_latitude': options.pos_latitudeField, 643 'type': options.typeField, 644 'waterlevel': options.waterlevelField, 645 'datum': options.datumField, 646 'reserved': '0', 647 } 648 649 bits = encode(msgDict) 650 if 'binary'==options.ioType: print str(bits) 651 elif 'nmeapayload'==options.ioType: 652 # FIX: figure out if this might be necessary at compile time 653 print "bitLen",len(bits) 654 bitLen=len(bits) 655 if bitLen%6!=0: 656 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 657 print "result:",binary.bitvectoais6(bits)[0] 658 659 660 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 661 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 662 else: sys.exit('ERROR: unknown ioType. Help!') 663 664 665 if options.sqlCreate: 666 sqlCreateStr(outfile,options.fieldList) 667 668 if options.printCsvfieldList: 669 # Make a csv separated list of fields that will be displayed for csv 670 if None == options.fieldList: options.fieldList = fieldList 671 import StringIO 672 buf = StringIO.StringIO() 673 for field in options.fieldList: 674 buf.write(field+',') 675 result = buf.getvalue() 676 if result[-1] == ',': print result[:-1] 677 else: print result 678 679 if options.doDecode: 680 for msg in args: 681 bv = None 682 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 683 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 684 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 685 else: sys.exit('ERROR: unknown ioType. Help!') 686 687 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 688