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

Source Code for Module ais.allaistypes

  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 alltypesmsg binary message payload to pack into an AIS Msg alltypesmsg. 50 51 Fields in params: 52 - dac(uint): Designated Area Code (field automatically set to "366") 53 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122") 54 - unavail_uint(uint): Unavailable unsigned integer 55 - anUInt(uint): NO unavailable unsigned integer 56 - anInt(int): NO unavailable signed integer 57 - aBool(bool): Simple bool 58 - aStr(aisstr6): An ais string of 5 characters 59 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers 60 - aDecimal(decimal): A decimal 61 - aFloat(float): An IEEE floating point number 62 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 63 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 64 @rtype: BitVector 65 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 66 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 67 ''' 68 69 bvList = [] 70 bvList.append(binary.setBitVectorSize(BitVector(intVal=366),16)) 71 bvList.append(binary.bvFromSignedInt(122,8)) 72 if 'unavail_uint' in params: 73 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['unavail_uint']),2)) 74 else: 75 bvList.append(binary.setBitVectorSize(BitVector(intVal=3),2)) 76 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['anUInt']),2)) 77 bvList.append(binary.bvFromSignedInt(params['anInt'],3)) 78 if params["aBool"]: bvList.append(TrueBV) 79 else: bvList.append(FalseBV) 80 bvList.append(aisstring.encode(params['aStr'],30)) 81 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['anUDecimal'])*Decimal('10')))),16)) 82 bvList.append(binary.bvFromSignedInt(int(Decimal(params['aDecimal'])*Decimal('10')),16)) 83 bvList.append(binary.float2bitvec(params['aFloat'])) 84 85 return binary.joinBV(bvList)
86
87 -def decode(bv, validate=False):
88 '''Unpack a alltypesmsg message 89 90 Fields in params: 91 - dac(uint): Designated Area Code (field automatically set to "366") 92 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122") 93 - unavail_uint(uint): Unavailable unsigned integer 94 - anUInt(uint): NO unavailable unsigned integer 95 - anInt(int): NO unavailable signed integer 96 - aBool(bool): Simple bool 97 - aStr(aisstr6): An ais string of 5 characters 98 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers 99 - aDecimal(decimal): A decimal 100 - aFloat(float): An IEEE floating point number 101 @type bv: BitVector 102 @param bv: Bits defining a message 103 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 104 @rtype: dict 105 @return: params 106 ''' 107 108 #Would be nice to check the bit count here.. 109 #if validate: 110 # assert (len(bv)==FIX: SOME NUMBER) 111 r = {} 112 r['dac']=366 113 r['reqDecimal']=122/Decimal('1') 114 r['unavail_uint']=int(bv[24:26]) 115 r['anUInt']=int(bv[26:28]) 116 r['anInt']=binary.signedIntFromBV(bv[28:31]) 117 r['aBool']=bool(int(bv[31:32])) 118 r['aStr']=aisstring.decode(bv[32:62]) 119 r['anUDecimal']=Decimal(int(bv[62:78]))/Decimal('10') 120 r['aDecimal']=Decimal(binary.signedIntFromBV(bv[78:94]))/Decimal('10') 121 r['aFloat']=binary.bitvec2float(bv[94:126]) 122 return r
123
124 -def decodedac(bv, validate=False):
125 return 366
126
127 -def decodereqDecimal(bv, validate=False):
128 return 122/Decimal('1')
129
130 -def decodeunavail_uint(bv, validate=False):
131 return int(bv[24:26])
132
133 -def decodeanUInt(bv, validate=False):
134 return int(bv[26:28])
135
136 -def decodeanInt(bv, validate=False):
137 return binary.signedIntFromBV(bv[28:31])
138
139 -def decodeaBool(bv, validate=False):
140 return bool(int(bv[31:32]))
141
142 -def decodeaStr(bv, validate=False):
143 return aisstring.decode(bv[32:62])
144
145 -def decodeanUDecimal(bv, validate=False):
146 return Decimal(int(bv[62:78]))/Decimal('10')
147
148 -def decodeaDecimal(bv, validate=False):
149 return Decimal(binary.signedIntFromBV(bv[78:94]))/Decimal('10')
150
151 -def decodeaFloat(bv, validate=False):
152 return binary.bitvec2float(bv[94:126])
153
154 -def printFields(params, out=sys.stdout, format='std'):
155 '''Print a alltypesmsg message to stdout. 156 157 Fields in params: 158 - dac(uint): Designated Area Code (field automatically set to "366") 159 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122") 160 - unavail_uint(uint): Unavailable unsigned integer 161 - anUInt(uint): NO unavailable unsigned integer 162 - anInt(int): NO unavailable signed integer 163 - aBool(bool): Simple bool 164 - aStr(aisstr6): An ais string of 5 characters 165 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers 166 - aDecimal(decimal): A decimal 167 - aFloat(float): An IEEE floating point number 168 @param params: Dictionary of field names/values. 169 @param out: File like object to write to 170 @rtype: stdout 171 @return: text to out 172 ''' 173 174 if 'std'==format: 175 out.write("alltypesmsg:\n") 176 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n") 177 if 'reqDecimal' in params: out.write(" reqDecimal: "+str(params['reqDecimal'])+"\n") 178 if 'unavail_uint' in params: out.write(" unavail_uint: "+str(params['unavail_uint'])+"\n") 179 if 'anUInt' in params: out.write(" anUInt: "+str(params['anUInt'])+"\n") 180 if 'anInt' in params: out.write(" anInt: "+str(params['anInt'])+"\n") 181 if 'aBool' in params: out.write(" aBool: "+str(params['aBool'])+"\n") 182 if 'aStr' in params: out.write(" aStr: "+str(params['aStr'])+"\n") 183 if 'anUDecimal' in params: out.write(" anUDecimal: "+str(params['anUDecimal'])+"\n") 184 if 'aDecimal' in params: out.write(" aDecimal: "+str(params['aDecimal'])+"\n") 185 if 'aFloat' in params: out.write(" aFloat: "+str(params['aFloat'])+"\n") 186 elif 'html'==format: 187 out.write("<h3>aFloat<h3>\n") 188 out.write("<table border=\"1\">\n") 189 out.write("<tr bgcolor=\"orange\">\n") 190 out.write("<th align=\"left\">Field Name</th>\n") 191 out.write("<th align=\"left\">Type</th>\n") 192 out.write("<th align=\"left\">Value</th>\n") 193 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 194 out.write("\n") 195 out.write("<tr>\n") 196 out.write("<td>dac</td>\n") 197 out.write("<td>uint</td>\n") 198 if 'dac' in params: 199 out.write(" <td>"+str(params['dac'])+"</td>\n") 200 out.write(" <td>"+str(params['dac'])+"</td>\n") 201 out.write("</tr>\n") 202 out.write("\n") 203 out.write("<tr>\n") 204 out.write("<td>reqDecimal</td>\n") 205 out.write("<td>decimal</td>\n") 206 if 'reqDecimal' in params: 207 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n") 208 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n") 209 out.write("</tr>\n") 210 out.write("\n") 211 out.write("<tr>\n") 212 out.write("<td>unavail_uint</td>\n") 213 out.write("<td>uint</td>\n") 214 if 'unavail_uint' in params: 215 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n") 216 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n") 217 out.write("</tr>\n") 218 out.write("\n") 219 out.write("<tr>\n") 220 out.write("<td>anUInt</td>\n") 221 out.write("<td>uint</td>\n") 222 if 'anUInt' in params: 223 out.write(" <td>"+str(params['anUInt'])+"</td>\n") 224 out.write(" <td>"+str(params['anUInt'])+"</td>\n") 225 out.write("</tr>\n") 226 out.write("\n") 227 out.write("<tr>\n") 228 out.write("<td>anInt</td>\n") 229 out.write("<td>int</td>\n") 230 if 'anInt' in params: 231 out.write(" <td>"+str(params['anInt'])+"</td>\n") 232 out.write(" <td>"+str(params['anInt'])+"</td>\n") 233 out.write("</tr>\n") 234 out.write("\n") 235 out.write("<tr>\n") 236 out.write("<td>aBool</td>\n") 237 out.write("<td>bool</td>\n") 238 if 'aBool' in params: 239 out.write(" <td>"+str(params['aBool'])+"</td>\n") 240 out.write(" <td>"+str(params['aBool'])+"</td>\n") 241 out.write("</tr>\n") 242 out.write("\n") 243 out.write("<tr>\n") 244 out.write("<td>aStr</td>\n") 245 out.write("<td>aisstr6</td>\n") 246 if 'aStr' in params: 247 out.write(" <td>"+str(params['aStr'])+"</td>\n") 248 out.write(" <td>"+str(params['aStr'])+"</td>\n") 249 out.write("</tr>\n") 250 out.write("\n") 251 out.write("<tr>\n") 252 out.write("<td>anUDecimal</td>\n") 253 out.write("<td>udecimal</td>\n") 254 if 'anUDecimal' in params: 255 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n") 256 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n") 257 out.write("</tr>\n") 258 out.write("\n") 259 out.write("<tr>\n") 260 out.write("<td>aDecimal</td>\n") 261 out.write("<td>decimal</td>\n") 262 if 'aDecimal' in params: 263 out.write(" <td>"+str(params['aDecimal'])+"</td>\n") 264 out.write(" <td>"+str(params['aDecimal'])+"</td>\n") 265 out.write("</tr>\n") 266 out.write("\n") 267 out.write("<tr>\n") 268 out.write("<td>aFloat</td>\n") 269 out.write("<td>float</td>\n") 270 if 'aFloat' in params: 271 out.write(" <td>"+str(params['aFloat'])+"</td>\n") 272 out.write(" <td>"+str(params['aFloat'])+"</td>\n") 273 out.write("</tr>\n") 274 out.write("</table>\n") 275 else: 276 print "ERROR: unknown format:",format 277 assert False 278 279 return # Nothing to return
280 281 282 283 ###################################################################### 284 # UNIT TESTING 285 ###################################################################### 286 import unittest
287 -def testParams():
288 '''Return a params file base on the testvalue tags. 289 @rtype: dict 290 @return: params based on testvalue tags 291 ''' 292 params = {} 293 params['dac'] = 366 294 params['reqDecimal'] = Decimal('122') 295 params['unavail_uint'] = 2 296 params['anUInt'] = 1 297 params['anInt'] = -1 298 params['aBool'] = True 299 params['aStr'] = 'ASDF1' 300 params['anUDecimal'] = Decimal('9.5') 301 params['aDecimal'] = Decimal('-9.6') 302 params['aFloat'] = -1234.5678 303 304 return params
305
306 -class Testalltypesmsg(unittest.TestCase):
307 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
308 - def testEncodeDecode(self):
309 310 params = testParams() 311 bits = encode(params) 312 r = decode(bits) 313 314 # Check that each parameter came through ok. 315 self.failUnlessEqual(r['dac'],params['dac']) 316 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],3) 317 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint']) 318 self.failUnlessEqual(r['anUInt'],params['anUInt']) 319 self.failUnlessEqual(r['anInt'],params['anInt']) 320 self.failUnlessEqual(r['aBool'],params['aBool']) 321 self.failUnlessEqual(r['aStr'],params['aStr']) 322 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1) 323 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0) 324 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
325
326 -def addMsgOptions(parser):
327 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 328 help='decode a "alltypesmsg" AIS message') 329 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 330 help='encode a "alltypesmsg" AIS message') 331 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int' 332 ,help='Field parameter value [default: %default]') 333 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int' 334 ,help='Field parameter value [default: %default]') 335 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int' 336 ,help='Field parameter value [default: %default]') 337 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int' 338 ,help='Field parameter value [default: %default]') 339 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string' 340 ,help='Field parameter value [default: %default]') 341 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string' 342 ,help='Field parameter value [default: %default]') 343 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string' 344 ,help='Field parameter value [default: %default]') 345 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float' 346 ,help='Field parameter value [default: %default]')
347 348 ############################################################ 349 if __name__=='__main__': 350 351 from optparse import OptionParser 352 parser = OptionParser(usage="%prog [options]", 353 version="%prog "+__version__) 354 355 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 356 help='run the documentation tests') 357 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 358 help='run the unit tests') 359 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 360 help='Make the test output verbose') 361 362 # FIX: remove nmea from binary messages. No way to build the whole packet? 363 # FIX: or build the surrounding msg 8 for a broadcast? 364 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 365 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 366 ,default='nmeapayload' 367 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 368 369 outputChoices = ('std','html','xml') 370 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 371 ,default='std' 372 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 373 374 parser.add_option('-o','--output',dest='outputFileName',default=None, 375 help='Name of the python file to write [default: stdout]') 376 377 addMsgOptions(parser) 378 379 (options,args) = parser.parse_args() 380 success=True 381 382 if options.doctest: 383 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 384 sys.argv= [sys.argv[0]] 385 if options.verbose: sys.argv.append('-v') 386 import doctest 387 numfail,numtests=doctest.testmod() 388 if numfail==0: print 'ok' 389 else: 390 print 'FAILED' 391 success=False 392 393 if not success: sys.exit('Something Failed') 394 del success # Hide success from epydoc 395 396 if options.unittest: 397 sys.argv = [sys.argv[0]] 398 if options.verbose: sys.argv.append('-v') 399 unittest.main() 400 401 outfile = sys.stdout 402 if None!=options.outputFileName: 403 outfile = file(options.outputFileName,'w') 404 405 406 if options.doEncode: 407 # First make sure all non required options are specified 408 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField") 409 if None==options.anUIntField: parser.error("missing value for anUIntField") 410 if None==options.anIntField: parser.error("missing value for anIntField") 411 if None==options.aBoolField: parser.error("missing value for aBoolField") 412 if None==options.aStrField: parser.error("missing value for aStrField") 413 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField") 414 if None==options.aDecimalField: parser.error("missing value for aDecimalField") 415 if None==options.aFloatField: parser.error("missing value for aFloatField") 416 msgDict={ 417 'dac': '366', 418 'reqDecimal': '122', 419 'unavail_uint': options.unavail_uintField, 420 'anUInt': options.anUIntField, 421 'anInt': options.anIntField, 422 'aBool': options.aBoolField, 423 'aStr': options.aStrField, 424 'anUDecimal': options.anUDecimalField, 425 'aDecimal': options.aDecimalField, 426 'aFloat': options.aFloatField, 427 } 428 429 bits = encode(msgDict) 430 if 'binary'==options.ioType: print str(bits) 431 elif 'nmeapayload'==options.ioType: 432 # FIX: figure out if this might be necessary at compile time 433 print "bitLen",len(bits) 434 bitLen=len(bits) 435 if bitLen%6!=0: 436 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 437 print "result:",binary.bitvectoais6(bits)[0] 438 439 440 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 441 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 442 else: sys.exit('ERROR: unknown ioType. Help!') 443 444 if options.doDecode: 445 for msg in args: 446 bv = None 447 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 448 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 449 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 450 else: sys.exit('ERROR: unknown ioType. Help!') 451 452 printFields(decode(bv),out=outfile,format=options.outputType) 453