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-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 -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
155 -def printHtml(params, out=sys.stdout):
156 out.write("<h3>alltypesmsg<h3>\n") 157 out.write("<table border=\"1\">\n") 158 out.write("<tr bgcolor=\"orange\">\n") 159 out.write("<th align=\"left\">Field Name</th>\n") 160 out.write("<th align=\"left\">Type</th>\n") 161 out.write("<th align=\"left\">Value</th>\n") 162 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 163 out.write("<th align=\"left\">Units</th>\n") 164 out.write("\n") 165 out.write("<tr>\n") 166 out.write("<td>dac</td>\n") 167 out.write("<td>uint</td>\n") 168 if 'dac' in params: 169 out.write(" <td>"+str(params['dac'])+"</td>\n") 170 out.write(" <td>"+str(params['dac'])+"</td>\n") 171 out.write("</tr>\n") 172 out.write("\n") 173 out.write("<tr>\n") 174 out.write("<td>reqDecimal</td>\n") 175 out.write("<td>decimal</td>\n") 176 if 'reqDecimal' in params: 177 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n") 178 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n") 179 out.write("</tr>\n") 180 out.write("\n") 181 out.write("<tr>\n") 182 out.write("<td>unavail_uint</td>\n") 183 out.write("<td>uint</td>\n") 184 if 'unavail_uint' in params: 185 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n") 186 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n") 187 out.write("</tr>\n") 188 out.write("\n") 189 out.write("<tr>\n") 190 out.write("<td>anUInt</td>\n") 191 out.write("<td>uint</td>\n") 192 if 'anUInt' in params: 193 out.write(" <td>"+str(params['anUInt'])+"</td>\n") 194 out.write(" <td>"+str(params['anUInt'])+"</td>\n") 195 out.write("</tr>\n") 196 out.write("\n") 197 out.write("<tr>\n") 198 out.write("<td>anInt</td>\n") 199 out.write("<td>int</td>\n") 200 if 'anInt' in params: 201 out.write(" <td>"+str(params['anInt'])+"</td>\n") 202 out.write(" <td>"+str(params['anInt'])+"</td>\n") 203 out.write("</tr>\n") 204 out.write("\n") 205 out.write("<tr>\n") 206 out.write("<td>aBool</td>\n") 207 out.write("<td>bool</td>\n") 208 if 'aBool' in params: 209 out.write(" <td>"+str(params['aBool'])+"</td>\n") 210 out.write(" <td>"+str(params['aBool'])+"</td>\n") 211 out.write("</tr>\n") 212 out.write("\n") 213 out.write("<tr>\n") 214 out.write("<td>aStr</td>\n") 215 out.write("<td>aisstr6</td>\n") 216 if 'aStr' in params: 217 out.write(" <td>"+str(params['aStr'])+"</td>\n") 218 out.write(" <td>"+str(params['aStr'])+"</td>\n") 219 out.write("</tr>\n") 220 out.write("\n") 221 out.write("<tr>\n") 222 out.write("<td>anUDecimal</td>\n") 223 out.write("<td>udecimal</td>\n") 224 if 'anUDecimal' in params: 225 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n") 226 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n") 227 out.write("</tr>\n") 228 out.write("\n") 229 out.write("<tr>\n") 230 out.write("<td>aDecimal</td>\n") 231 out.write("<td>decimal</td>\n") 232 if 'aDecimal' in params: 233 out.write(" <td>"+str(params['aDecimal'])+"</td>\n") 234 out.write(" <td>"+str(params['aDecimal'])+"</td>\n") 235 out.write("</tr>\n") 236 out.write("\n") 237 out.write("<tr>\n") 238 out.write("<td>aFloat</td>\n") 239 out.write("<td>float</td>\n") 240 if 'aFloat' in params: 241 out.write(" <td>"+str(params['aFloat'])+"</td>\n") 242 out.write(" <td>"+str(params['aFloat'])+"</td>\n") 243 out.write("</tr>\n") 244 out.write("</table>\n")
245 -def printFields(params, out=sys.stdout, format='std'):
246 '''Print a aFloat message to stdout. 247 248 Fields in params: 249 - dac(uint): Designated Area Code (field automatically set to "366") 250 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122") 251 - unavail_uint(uint): Unavailable unsigned integer 252 - anUInt(uint): NO unavailable unsigned integer 253 - anInt(int): NO unavailable signed integer 254 - aBool(bool): Simple bool 255 - aStr(aisstr6): An ais string of 5 characters 256 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers 257 - aDecimal(decimal): A decimal 258 - aFloat(float): An IEEE floating point number 259 @param params: Dictionary of field names/values. 260 @param out: File like object to write to 261 @rtype: stdout 262 @return: text to out 263 ''' 264 265 if 'std'==format: 266 out.write("aFloat:\n") 267 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n") 268 if 'reqDecimal' in params: out.write(" reqDecimal: "+str(params['reqDecimal'])+"\n") 269 if 'unavail_uint' in params: out.write(" unavail_uint: "+str(params['unavail_uint'])+"\n") 270 if 'anUInt' in params: out.write(" anUInt: "+str(params['anUInt'])+"\n") 271 if 'anInt' in params: out.write(" anInt: "+str(params['anInt'])+"\n") 272 if 'aBool' in params: out.write(" aBool: "+str(params['aBool'])+"\n") 273 if 'aStr' in params: out.write(" aStr: "+str(params['aStr'])+"\n") 274 if 'anUDecimal' in params: out.write(" anUDecimal: "+str(params['anUDecimal'])+"\n") 275 if 'aDecimal' in params: out.write(" aDecimal: "+str(params['aDecimal'])+"\n") 276 if 'aFloat' in params: out.write(" aFloat: "+str(params['aFloat'])+"\n") 277 elif 'html'==format: 278 printHtml(params,out) 279 else: 280 print "ERROR: unknown format:",format 281 assert False 282 283 return # Nothing to return
284 285 286 287 ###################################################################### 288 # UNIT TESTING 289 ###################################################################### 290 import unittest
291 -def testParams():
292 '''Return a params file base on the testvalue tags. 293 @rtype: dict 294 @return: params based on testvalue tags 295 ''' 296 params = {} 297 params['dac'] = 366 298 params['reqDecimal'] = Decimal('122') 299 params['unavail_uint'] = 2 300 params['anUInt'] = 1 301 params['anInt'] = -1 302 params['aBool'] = True 303 params['aStr'] = 'ASDF1' 304 params['anUDecimal'] = Decimal('9.5') 305 params['aDecimal'] = Decimal('-9.6') 306 params['aFloat'] = -1234.5678 307 308 return params
309
310 -class Testalltypesmsg(unittest.TestCase):
311 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
312 - def testEncodeDecode(self):
313 314 params = testParams() 315 bits = encode(params) 316 r = decode(bits) 317 318 # Check that each parameter came through ok. 319 self.failUnlessEqual(r['dac'],params['dac']) 320 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],3) 321 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint']) 322 self.failUnlessEqual(r['anUInt'],params['anUInt']) 323 self.failUnlessEqual(r['anInt'],params['anInt']) 324 self.failUnlessEqual(r['aBool'],params['aBool']) 325 self.failUnlessEqual(r['aStr'],params['aStr']) 326 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1) 327 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0) 328 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
329
330 -def addMsgOptions(parser):
331 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 332 help='decode a "alltypesmsg" AIS message') 333 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 334 help='encode a "alltypesmsg" AIS message') 335 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int' 336 ,help='Field parameter value [default: %default]') 337 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int' 338 ,help='Field parameter value [default: %default]') 339 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int' 340 ,help='Field parameter value [default: %default]') 341 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int' 342 ,help='Field parameter value [default: %default]') 343 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string' 344 ,help='Field parameter value [default: %default]') 345 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string' 346 ,help='Field parameter value [default: %default]') 347 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string' 348 ,help='Field parameter value [default: %default]') 349 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float' 350 ,help='Field parameter value [default: %default]')
351 352 ############################################################ 353 if __name__=='__main__': 354 355 from optparse import OptionParser 356 parser = OptionParser(usage="%prog [options]", 357 version="%prog "+__version__) 358 359 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 360 help='run the documentation tests') 361 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 362 help='run the unit tests') 363 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 364 help='Make the test output verbose') 365 366 # FIX: remove nmea from binary messages. No way to build the whole packet? 367 # FIX: or build the surrounding msg 8 for a broadcast? 368 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 369 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 370 ,default='nmeapayload' 371 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 372 373 374 outputChoices = ('std','html','xml' ) 375 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 376 ,default='std' 377 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 378 379 parser.add_option('-o','--output',dest='outputFileName',default=None, 380 help='Name of the python file to write [default: stdout]') 381 382 addMsgOptions(parser) 383 384 (options,args) = parser.parse_args() 385 success=True 386 387 if options.doctest: 388 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 389 sys.argv= [sys.argv[0]] 390 if options.verbose: sys.argv.append('-v') 391 import doctest 392 numfail,numtests=doctest.testmod() 393 if numfail==0: print 'ok' 394 else: 395 print 'FAILED' 396 success=False 397 398 if not success: sys.exit('Something Failed') 399 del success # Hide success from epydoc 400 401 if options.unittest: 402 sys.argv = [sys.argv[0]] 403 if options.verbose: sys.argv.append('-v') 404 unittest.main() 405 406 outfile = sys.stdout 407 if None!=options.outputFileName: 408 outfile = file(options.outputFileName,'w') 409 410 411 if options.doEncode: 412 # First make sure all non required options are specified 413 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField") 414 if None==options.anUIntField: parser.error("missing value for anUIntField") 415 if None==options.anIntField: parser.error("missing value for anIntField") 416 if None==options.aBoolField: parser.error("missing value for aBoolField") 417 if None==options.aStrField: parser.error("missing value for aStrField") 418 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField") 419 if None==options.aDecimalField: parser.error("missing value for aDecimalField") 420 if None==options.aFloatField: parser.error("missing value for aFloatField") 421 msgDict={ 422 'dac': '366', 423 'reqDecimal': '122', 424 'unavail_uint': options.unavail_uintField, 425 'anUInt': options.anUIntField, 426 'anInt': options.anIntField, 427 'aBool': options.aBoolField, 428 'aStr': options.aStrField, 429 'anUDecimal': options.anUDecimalField, 430 'aDecimal': options.aDecimalField, 431 'aFloat': options.aFloatField, 432 } 433 434 bits = encode(msgDict) 435 if 'binary'==options.ioType: print str(bits) 436 elif 'nmeapayload'==options.ioType: 437 # FIX: figure out if this might be necessary at compile time 438 print "bitLen",len(bits) 439 bitLen=len(bits) 440 if bitLen%6!=0: 441 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 442 print "result:",binary.bitvectoais6(bits)[0] 443 444 445 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 446 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 447 else: sys.exit('ERROR: unknown ioType. Help!') 448 449 if options.doDecode: 450 for msg in args: 451 bv = None 452 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 453 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 454 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 455 else: sys.exit('ERROR: unknown ioType. Help!') 456 457 printFields(decode(bv),out=outfile,format=options.outputType) 458