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: 2006-12-20 $'.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__ myparser 
 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']),5)) 94 else: 95 bvList.append(binary.setBitVectorSize(BitVector(intVal=31),5)) 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:133]) 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:133])
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 out.write(" time_month: "+str(params['time_month'])+"\n") 196 out.write(" time_day: "+str(params['time_day'])+"\n") 197 out.write(" time_hour: "+str(params['time_hour'])+"\n") 198 out.write(" time_min: "+str(params['time_min'])+"\n") 199 out.write(" stationid: "+str(params['stationid'])+"\n") 200 out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n") 201 out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n") 202 out.write(" type: "+str(params['type'])+"\n") 203 out.write(" waterlevel: "+str(params['waterlevel'])+"\n") 204 out.write(" datum: "+str(params['datum'])+"\n") 205 out.write(" reserved: "+str(params['reserved'])+"\n") 206 207 return # Nothing to return
208 209 210 211 ###################################################################### 212 # UNIT TESTING 213 ###################################################################### 214 import unittest
215 -def testParams():
216 '''Return a params file base on the testvalue tags. 217 @rtype: dict 218 @return: params based on testvalue tags 219 ''' 220 params = {} 221 params['time_month'] = 2 222 params['time_day'] = 28 223 params['time_hour'] = 23 224 params['time_min'] = 45 225 params['stationid'] = 'A234567' 226 params['pos_longitude'] = Decimal('-122.16328') 227 params['pos_latitude'] = Decimal('37.42446') 228 params['type'] = 0 229 params['waterlevel'] = -97 230 params['datum'] = 0 231 params['reserved'] = 0 232 233 return params
234
235 -class Testsls_waterlevel(unittest.TestCase):
236 '''Use testvalue tag text from each type to build test case the sls_waterlevel message'''
237 - def testEncodeDecode(self):
238 239 params = testParams() 240 bits = encode(params) 241 r = decode(bits) 242 243 # Check that each parameter came through ok. 244 self.failUnlessEqual(r['time_month'],params['time_month']) 245 self.failUnlessEqual(r['time_day'],params['time_day']) 246 self.failUnlessEqual(r['time_hour'],params['time_hour']) 247 self.failUnlessEqual(r['time_min'],params['time_min']) 248 self.failUnlessEqual(r['stationid'],params['stationid']) 249 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4) 250 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4) 251 self.failUnlessEqual(r['type'],params['type']) 252 self.failUnlessEqual(r['waterlevel'],params['waterlevel']) 253 self.failUnlessEqual(r['datum'],params['datum']) 254 self.failUnlessEqual(r['reserved'],params['reserved'])
255 256 ############################################################ 257 if __name__=='__main__': 258 259 from optparse import OptionParser 260 myparser = OptionParser(usage="%prog [options]", 261 version="%prog "+__version__) 262 263 #sys.exit('EARLY EXIT - FIX: remove') 264 myparser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 265 help='run the documentation tests') 266 myparser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 267 help='run the unit tests') 268 myparser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 269 help='Make the test output verbose') 270 271 272 myparser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 273 help='decode a "sls_waterlevel" AIS message') 274 myparser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 275 help='encode a "sls_waterlevel" AIS message') 276 277 278 # FIX: remove nmea from binary messages. No way to build the whole packet? 279 # FIX: or build the surrounding msg 8 for a broadcast? 280 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 281 myparser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 282 ,default='nmeapayload' 283 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 284 285 myparser.add_option('--time_month-field', dest='time_monthField' 286 ,help='Field parameter value [default: %default]' 287 ,metavar='uint' 288 ,type='int' 289 ) 290 myparser.add_option('--time_day-field', dest='time_dayField' 291 ,help='Field parameter value [default: %default]' 292 ,metavar='uint' 293 ,type='int' 294 ) 295 myparser.add_option('--time_hour-field', dest='time_hourField' 296 ,help='Field parameter value [default: %default]' 297 ,metavar='uint' 298 ,type='int' 299 ) 300 myparser.add_option('--time_min-field', dest='time_minField' 301 ,help='Field parameter value [default: %default]' 302 ,metavar='uint' 303 ,type='int' 304 ) 305 myparser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@' 306 ,help='Field parameter value [default: %default]' 307 ,metavar='aisstr6' 308 ,type='string' 309 ) 310 myparser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181') 311 ,help='Field parameter value [default: %default]' 312 ,metavar='decimal' 313 ,type='string' 314 ) 315 myparser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91') 316 ,help='Field parameter value [default: %default]' 317 ,metavar='decimal' 318 ,type='string' 319 ) 320 myparser.add_option('--type-field', dest='typeField' 321 ,help='Field parameter value [default: %default]' 322 ,metavar='uint' 323 ,type='int' 324 ) 325 myparser.add_option('--waterlevel-field', dest='waterlevelField',default=-32768 326 ,help='Field parameter value [default: %default]' 327 ,metavar='int' 328 ,type='int' 329 ) 330 myparser.add_option('--datum-field', dest='datumField',default=31 331 ,help='Field parameter value [default: %default]' 332 ,metavar='uint' 333 ,type='int' 334 ) 335 336 (options,args) = myparser.parse_args() 337 success=True 338 339 if options.doctest: 340 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 341 sys.argv= [sys.argv[0]] 342 if options.verbose: sys.argv.append('-v') 343 import doctest 344 numfail,numtests=doctest.testmod() 345 if numfail==0: print 'ok' 346 else: 347 print 'FAILED' 348 success=False 349 350 if not success: 351 sys.exit('Something Failed') 352 353 del success # Hide success from epydoc 354 355 if options.unittest: 356 sys.argv = [sys.argv[0]] 357 if options.verbose: sys.argv.append('-v') 358 unittest.main() 359 360 if options.doEncode: 361 # First make sure all non required options are specified 362 if None==options.time_monthField: myparser.error("missing value for time_monthField") 363 if None==options.time_dayField: myparser.error("missing value for time_dayField") 364 if None==options.time_hourField: myparser.error("missing value for time_hourField") 365 if None==options.time_minField: myparser.error("missing value for time_minField") 366 if None==options.stationidField: myparser.error("missing value for stationidField") 367 if None==options.pos_longitudeField: myparser.error("missing value for pos_longitudeField") 368 if None==options.pos_latitudeField: myparser.error("missing value for pos_latitudeField") 369 if None==options.typeField: myparser.error("missing value for typeField") 370 if None==options.waterlevelField: myparser.error("missing value for waterlevelField") 371 if None==options.datumField: myparser.error("missing value for datumField") 372 msgDict={ 373 'time_month': options.time_monthField, 374 'time_day': options.time_dayField, 375 'time_hour': options.time_hourField, 376 'time_min': options.time_minField, 377 'stationid': options.stationidField, 378 'pos_longitude': options.pos_longitudeField, 379 'pos_latitude': options.pos_latitudeField, 380 'type': options.typeField, 381 'waterlevel': options.waterlevelField, 382 'datum': options.datumField, 383 'reserved': '0', 384 } 385 bits = encode(msgDict) 386 if 'binary'==options.ioType: print str(bits) 387 elif 'nmeapayload'==options.ioType: 388 print "bitLen",len(bits) 389 bitLen=len(bits) 390 if bitLen%6!=0: 391 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 392 print "result:",binary.bitvectoais6(bits)[0] 393 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 394 else: sys.exit('ERROR: unknown ioType. Help!') 395 396 if options.doDecode: 397 for msg in args: 398 if 'binary'==options.ioType: 399 bv = BitVector(bitstring=msg) 400 printFields(decode(bv)) 401 elif 'nmeapayload'==options.ioType: 402 bv = binary.ais6tobitvec(msg) 403 printFields(decode(bv)) 404 elif 'nmea'==options.ioType: 405 bv = binary.ais6tobitvec(msg.split(',')[5]) 406 printFields(decode(bv)) 407 else: sys.exit('ERROR: unknown ioType. Help!') 408