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

Source Code for Module ais.sls_waterflow

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