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-01-04 $'.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 -def encode(params, validate=False):
49 '''Create a sls_waterlevel binary message payload to pack into an AIS Msg sls_waterlevel. 50 51 Fields in params: 52 - time_month(uint): Time tag of measurement month 1..12 53 - time_day(uint): Time tag of measurement day of the month 1..31 54 - time_hour(uint): Time tag of measurement UTC hours 0..23 55 - time_min(uint): Time tag of measurement minutes 56 - stationid(aisstr6): Character identifier of the station. Usually a number. 57 - pos_longitude(decimal): Location of measurement East West location 58 - pos_latitude(decimal): Location of measurement North South location 59 - type(uint): How to interpret the water level 60 - waterlevel(int): Water level in centimeters 61 - datum(uint): What reference datum applies to the value 62 - reserved(uint): Reserved bits for future use (field automatically set to "0") 63 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 64 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 65 @rtype: BitVector 66 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 67 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 68 ''' 69 70 bvList = [] 71 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4)) 72 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5)) 73 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5)) 74 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6)) 75 if 'stationid' in params: 76 bvList.append(aisstring.encode(params['stationid'],42)) 77 else: 78 bvList.append(aisstring.encode('@@@@@@@',42)) 79 if 'pos_longitude' in params: 80 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25)) 81 else: 82 bvList.append(binary.bvFromSignedInt(10860000,25)) 83 if 'pos_latitude' in params: 84 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24)) 85 else: 86 bvList.append(binary.bvFromSignedInt(5460000,24)) 87 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),1)) 88 if 'waterlevel' in params: 89 bvList.append(binary.bvFromSignedInt(params['waterlevel'],16)) 90 else: 91 bvList.append(binary.bvFromSignedInt(-32768,16)) 92 if 'datum' in params: 93 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['datum']),2)) 94 else: 95 bvList.append(binary.setBitVectorSize(BitVector(intVal=31),2)) 96 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),14)) 97 98 return binary.joinBV(bvList)
99
100 -def decode(bv, validate=False):
101 '''Unpack a sls_waterlevel message 102 103 Fields in params: 104 - time_month(uint): Time tag of measurement month 1..12 105 - time_day(uint): Time tag of measurement day of the month 1..31 106 - time_hour(uint): Time tag of measurement UTC hours 0..23 107 - time_min(uint): Time tag of measurement minutes 108 - stationid(aisstr6): Character identifier of the station. Usually a number. 109 - pos_longitude(decimal): Location of measurement East West location 110 - pos_latitude(decimal): Location of measurement North South location 111 - type(uint): How to interpret the water level 112 - waterlevel(int): Water level in centimeters 113 - datum(uint): What reference datum applies to the value 114 - reserved(uint): Reserved bits for future use (field automatically set to "0") 115 @type bv: BitVector 116 @param bv: Bits defining a message 117 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 118 @rtype: dict 119 @return: params 120 ''' 121 122 #Would be nice to check the bit count here.. 123 #if validate: 124 # assert (len(bv)==FIX: SOME NUMBER) 125 r = {} 126 r['time_month']=int(bv[0:4]) 127 r['time_day']=int(bv[4:9]) 128 r['time_hour']=int(bv[9:14]) 129 r['time_min']=int(bv[14:20]) 130 r['stationid']=aisstring.decode(bv[20:62]) 131 r['pos_longitude']=Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000') 132 r['pos_latitude']=Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000') 133 r['type']=int(bv[111:112]) 134 r['waterlevel']=binary.signedIntFromBV(bv[112:128]) 135 r['datum']=int(bv[128:130]) 136 r['reserved']=0 137 return r
138
139 -def decodetime_month(bv, validate=False):
140 return int(bv[0:4])
141
142 -def decodetime_day(bv, validate=False):
143 return int(bv[4:9])
144
145 -def decodetime_hour(bv, validate=False):
146 return int(bv[9:14])
147
148 -def decodetime_min(bv, validate=False):
149 return int(bv[14:20])
150
151 -def decodestationid(bv, validate=False):
152 return aisstring.decode(bv[20:62])
153
154 -def decodepos_longitude(bv, validate=False):
155 return Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000')
156
157 -def decodepos_latitude(bv, validate=False):
158 return Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000')
159
160 -def decodetype(bv, validate=False):
161 return int(bv[111:112])
162
163 -def decodewaterlevel(bv, validate=False):
164 return binary.signedIntFromBV(bv[112:128])
165
166 -def decodedatum(bv, validate=False):
167 return int(bv[128:130])
168
169 -def decodereserved(bv, validate=False):
170 return 0
171
172 -def printFields(params, out=sys.stdout, format='std'):
173 '''Print a sls_waterlevel message to stdout. 174 175 Fields in params: 176 - time_month(uint): Time tag of measurement month 1..12 177 - time_day(uint): Time tag of measurement day of the month 1..31 178 - time_hour(uint): Time tag of measurement UTC hours 0..23 179 - time_min(uint): Time tag of measurement minutes 180 - stationid(aisstr6): Character identifier of the station. Usually a number. 181 - pos_longitude(decimal): Location of measurement East West location 182 - pos_latitude(decimal): Location of measurement North South location 183 - type(uint): How to interpret the water level 184 - waterlevel(int): Water level in centimeters 185 - datum(uint): What reference datum applies to the value 186 - reserved(uint): Reserved bits for future use (field automatically set to "0") 187 @param params: Dictionary of field names/values. 188 @param out: File like object to write to 189 @rtype: stdout 190 @return: text to out 191 ''' 192 193 if 'std'==format: 194 out.write("sls_waterlevel:\n") 195 if 'time_month' in params: out.write(" time_month: "+str(params['time_month'])+"\n") 196 if 'time_day' in params: out.write(" time_day: "+str(params['time_day'])+"\n") 197 if 'time_hour' in params: out.write(" time_hour: "+str(params['time_hour'])+"\n") 198 if 'time_min' in params: out.write(" time_min: "+str(params['time_min'])+"\n") 199 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n") 200 if 'pos_longitude' in params: out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n") 201 if 'pos_latitude' in params: out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n") 202 if 'type' in params: out.write(" type: "+str(params['type'])+"\n") 203 if 'waterlevel' in params: out.write(" waterlevel: "+str(params['waterlevel'])+"\n") 204 if 'datum' in params: out.write(" datum: "+str(params['datum'])+"\n") 205 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 206 elif 'html'==format: 207 out.write("<h3>reserved<h3>\n") 208 out.write("<table border=\"1\">\n") 209 out.write("<tr bgcolor=\"orange\">\n") 210 out.write("<th align=\"left\">Field Name</th>\n") 211 out.write("<th align=\"left\">Type</th>\n") 212 out.write("<th align=\"left\">Value</th>\n") 213 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 214 out.write("\n") 215 out.write("<tr>\n") 216 out.write("<td>time_month</td>\n") 217 out.write("<td>uint</td>\n") 218 if 'time_month' in params: 219 out.write(" <td>"+str(params['time_month'])+"</td>\n") 220 out.write(" <td>"+str(params['time_month'])+"</td>\n") 221 out.write("</tr>\n") 222 out.write("\n") 223 out.write("<tr>\n") 224 out.write("<td>time_day</td>\n") 225 out.write("<td>uint</td>\n") 226 if 'time_day' in params: 227 out.write(" <td>"+str(params['time_day'])+"</td>\n") 228 out.write(" <td>"+str(params['time_day'])+"</td>\n") 229 out.write("</tr>\n") 230 out.write("\n") 231 out.write("<tr>\n") 232 out.write("<td>time_hour</td>\n") 233 out.write("<td>uint</td>\n") 234 if 'time_hour' in params: 235 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 236 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 237 out.write("</tr>\n") 238 out.write("\n") 239 out.write("<tr>\n") 240 out.write("<td>time_min</td>\n") 241 out.write("<td>uint</td>\n") 242 if 'time_min' in params: 243 out.write(" <td>"+str(params['time_min'])+"</td>\n") 244 out.write(" <td>"+str(params['time_min'])+"</td>\n") 245 out.write("</tr>\n") 246 out.write("\n") 247 out.write("<tr>\n") 248 out.write("<td>stationid</td>\n") 249 out.write("<td>aisstr6</td>\n") 250 if 'stationid' in params: 251 out.write(" <td>"+str(params['stationid'])+"</td>\n") 252 out.write(" <td>"+str(params['stationid'])+"</td>\n") 253 out.write("</tr>\n") 254 out.write("\n") 255 out.write("<tr>\n") 256 out.write("<td>pos_longitude</td>\n") 257 out.write("<td>decimal</td>\n") 258 if 'pos_longitude' in params: 259 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 260 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 261 out.write("</tr>\n") 262 out.write("\n") 263 out.write("<tr>\n") 264 out.write("<td>pos_latitude</td>\n") 265 out.write("<td>decimal</td>\n") 266 if 'pos_latitude' in params: 267 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n") 268 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n") 269 out.write("</tr>\n") 270 out.write("\n") 271 out.write("<tr>\n") 272 out.write("<td>type</td>\n") 273 out.write("<td>uint</td>\n") 274 if 'type' in params: 275 out.write(" <td>"+str(params['type'])+"</td>\n") 276 if str(params['type']) in typeDecodeLut: 277 out.write("<td>"+typeDecodeLut[str(params['type'])]+"</td>") 278 else: 279 out.write("<td><i>Missing LUT entry</i></td>") 280 out.write("</tr>\n") 281 out.write("\n") 282 out.write("<tr>\n") 283 out.write("<td>waterlevel</td>\n") 284 out.write("<td>int</td>\n") 285 if 'waterlevel' in params: 286 out.write(" <td>"+str(params['waterlevel'])+"</td>\n") 287 out.write(" <td>"+str(params['waterlevel'])+"</td>\n") 288 out.write("</tr>\n") 289 out.write("\n") 290 out.write("<tr>\n") 291 out.write("<td>datum</td>\n") 292 out.write("<td>uint</td>\n") 293 if 'datum' in params: 294 out.write(" <td>"+str(params['datum'])+"</td>\n") 295 if str(params['datum']) in datumDecodeLut: 296 out.write("<td>"+datumDecodeLut[str(params['datum'])]+"</td>") 297 else: 298 out.write("<td><i>Missing LUT entry</i></td>") 299 out.write("</tr>\n") 300 out.write("\n") 301 out.write("<tr>\n") 302 out.write("<td>reserved</td>\n") 303 out.write("<td>uint</td>\n") 304 if 'reserved' in params: 305 out.write(" <td>"+str(params['reserved'])+"</td>\n") 306 out.write(" <td>"+str(params['reserved'])+"</td>\n") 307 out.write("</tr>\n") 308 out.write("</table>\n") 309 else: 310 print "ERROR: unknown format:",format 311 assert False 312 313 return # Nothing to return
314 315 typeEncodeLut = { 316 'Relative to datum':'0', 317 'Water depth':'1', 318 } #typeEncodeLut 319 320 typeDecodeLut = { 321 '0':'Relative to datum', 322 '1':'Water depth', 323 } # typeEncodeLut 324 325 datumEncodeLut = { 326 'MLLW':'0', 327 'IGLD-85':'1', 328 'Reserved':'2', 329 'Reserved':'3', 330 } #datumEncodeLut 331 332 datumDecodeLut = { 333 '0':'MLLW', 334 '1':'IGLD-85', 335 '2':'Reserved', 336 '3':'Reserved', 337 } # datumEncodeLut 338 339 340 341 ###################################################################### 342 # UNIT TESTING 343 ###################################################################### 344 import unittest
345 -def testParams():
346 '''Return a params file base on the testvalue tags. 347 @rtype: dict 348 @return: params based on testvalue tags 349 ''' 350 params = {} 351 params['time_month'] = 2 352 params['time_day'] = 28 353 params['time_hour'] = 23 354 params['time_min'] = 45 355 params['stationid'] = 'A234567' 356 params['pos_longitude'] = Decimal('-122.16328') 357 params['pos_latitude'] = Decimal('37.42446') 358 params['type'] = 0 359 params['waterlevel'] = -97 360 params['datum'] = 0 361 params['reserved'] = 0 362 363 return params
364
365 -class Testsls_waterlevel(unittest.TestCase):
366 '''Use testvalue tag text from each type to build test case the sls_waterlevel message'''
367 - def testEncodeDecode(self):
368 369 params = testParams() 370 bits = encode(params) 371 r = decode(bits) 372 373 # Check that each parameter came through ok. 374 self.failUnlessEqual(r['time_month'],params['time_month']) 375 self.failUnlessEqual(r['time_day'],params['time_day']) 376 self.failUnlessEqual(r['time_hour'],params['time_hour']) 377 self.failUnlessEqual(r['time_min'],params['time_min']) 378 self.failUnlessEqual(r['stationid'],params['stationid']) 379 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4) 380 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4) 381 self.failUnlessEqual(r['type'],params['type']) 382 self.failUnlessEqual(r['waterlevel'],params['waterlevel']) 383 self.failUnlessEqual(r['datum'],params['datum']) 384 self.failUnlessEqual(r['reserved'],params['reserved'])
385
386 -def addMsgOptions(parser):
387 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 388 help='decode a "sls_waterlevel" AIS message') 389 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 390 help='encode a "sls_waterlevel" AIS message') 391 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int' 392 ,help='Field parameter value [default: %default]') 393 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int' 394 ,help='Field parameter value [default: %default]') 395 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int' 396 ,help='Field parameter value [default: %default]') 397 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int' 398 ,help='Field parameter value [default: %default]') 399 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string' 400 ,help='Field parameter value [default: %default]') 401 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 402 ,help='Field parameter value [default: %default]') 403 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 404 ,help='Field parameter value [default: %default]') 405 parser.add_option('--type-field', dest='typeField',metavar='uint',type='int' 406 ,help='Field parameter value [default: %default]') 407 parser.add_option('--waterlevel-field', dest='waterlevelField',default=-32768,metavar='int',type='int' 408 ,help='Field parameter value [default: %default]') 409 parser.add_option('--datum-field', dest='datumField',default=31,metavar='uint',type='int' 410 ,help='Field parameter value [default: %default]')
411 412 ############################################################ 413 if __name__=='__main__': 414 415 from optparse import OptionParser 416 parser = OptionParser(usage="%prog [options]", 417 version="%prog "+__version__) 418 419 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 420 help='run the documentation tests') 421 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 422 help='run the unit tests') 423 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 424 help='Make the test output verbose') 425 426 # FIX: remove nmea from binary messages. No way to build the whole packet? 427 # FIX: or build the surrounding msg 8 for a broadcast? 428 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 429 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 430 ,default='nmeapayload' 431 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 432 433 outputChoices = ('std','html','xml') 434 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 435 ,default='std' 436 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 437 438 parser.add_option('-o','--output',dest='outputFileName',default=None, 439 help='Name of the python file to write [default: stdout]') 440 441 addMsgOptions(parser) 442 443 (options,args) = parser.parse_args() 444 success=True 445 446 if options.doctest: 447 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 448 sys.argv= [sys.argv[0]] 449 if options.verbose: sys.argv.append('-v') 450 import doctest 451 numfail,numtests=doctest.testmod() 452 if numfail==0: print 'ok' 453 else: 454 print 'FAILED' 455 success=False 456 457 if not success: sys.exit('Something Failed') 458 del success # Hide success from epydoc 459 460 if options.unittest: 461 sys.argv = [sys.argv[0]] 462 if options.verbose: sys.argv.append('-v') 463 unittest.main() 464 465 outfile = sys.stdout 466 if None!=options.outputFileName: 467 outfile = file(options.outputFileName,'w') 468 469 470 if options.doEncode: 471 # First make sure all non required options are specified 472 if None==options.time_monthField: parser.error("missing value for time_monthField") 473 if None==options.time_dayField: parser.error("missing value for time_dayField") 474 if None==options.time_hourField: parser.error("missing value for time_hourField") 475 if None==options.time_minField: parser.error("missing value for time_minField") 476 if None==options.stationidField: parser.error("missing value for stationidField") 477 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField") 478 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField") 479 if None==options.typeField: parser.error("missing value for typeField") 480 if None==options.waterlevelField: parser.error("missing value for waterlevelField") 481 if None==options.datumField: parser.error("missing value for datumField") 482 msgDict={ 483 'time_month': options.time_monthField, 484 'time_day': options.time_dayField, 485 'time_hour': options.time_hourField, 486 'time_min': options.time_minField, 487 'stationid': options.stationidField, 488 'pos_longitude': options.pos_longitudeField, 489 'pos_latitude': options.pos_latitudeField, 490 'type': options.typeField, 491 'waterlevel': options.waterlevelField, 492 'datum': options.datumField, 493 'reserved': '0', 494 } 495 496 bits = encode(msgDict) 497 if 'binary'==options.ioType: print str(bits) 498 elif 'nmeapayload'==options.ioType: 499 # FIX: figure out if this might be necessary at compile time 500 print "bitLen",len(bits) 501 bitLen=len(bits) 502 if bitLen%6!=0: 503 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 504 print "result:",binary.bitvectoais6(bits)[0] 505 506 507 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 508 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 509 else: sys.exit('ERROR: unknown ioType. Help!') 510 511 if options.doDecode: 512 for msg in args: 513 bv = None 514 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 515 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 516 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 517 else: sys.exit('ERROR: unknown ioType. Help!') 518 519 printFields(decode(bv),out=outfile,format=options.outputType) 520