Module prototype
[hide private]
[frames] | no frames]

Source Code for Module prototype

  1  #!/usr/bin/env python 
  2   
  3  __version__ = '$Revision: 5061 $'.split()[1] 
  4  __date__ = '$Date: 2006-11-29 17:34:11 -0500 (Wed, 29 Nov 2006) $'.split()[1] 
  5  __author__ = 'xmlbinmsg' 
  6   
  7  __doc__=''' 
  8   
  9  Autogenerated python functions to serialize/deserialize binary messages. 
 10   
 11  Generated by: ./xmlbinmsg.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  import aisstring 
 39   
 40  import binary 
 41  #def waterlevelEncode(*aDict, **params): 
42 -def encode(params, validate=False, **moreParams):
43 '''Serializer for the waterlevel binary message 44 45 Keywords and types: 46 47 - dac: uint 48 - unavail_uint: uint 49 - uint: uint 50 FIX: generate CORRECT doctest string that does all the defaults 51 52 The default message: 53 54 >>> print encode() 55 1011011101100 56 57 @param aDict: for passing in a dictionary of keyword and values. 58 @param params: keyword dictionary or if a dict is passed, it will use that dict 59 @return: bitvector 60 @note: only use one of aDict or params 61 @bug: FIX: have moreParams add to and override params 62 ''' 63 64 bvList = [] 65 66 67 ### FIELD: dac (type=uint) REQUIRED CONSTANT FIELD 68 bvList.append(binary.setBitVectorSize(BitVector(intVal=366),16)) 69 70 ### FIELD: unavail_uint (type=uint) 71 if 'unavail_uint' in params: bvList.append(binary.setBitVectorSize(BitVector(intVal=params['unavail_uint']),2)) 72 else: bvList.append(binary.setBitVectorSize(BitVector(intVal=3),2)) 73 74 ### FIELD: anUInt (type=uint) 75 #if 'anUInt' in params: 76 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['anUInt']),2)) 77 #else: bvList.append(BitVector(size=2)) 78 79 ### FIELD: anInt (type=int) 80 #if 'int' in params: 81 bvList.append(binary.bvFromSignedInt(int(params['anInt']),4)) 82 #else: assert False # FIX: throw exception when not given 83 84 ### FIELD: aBool (type=bool) 85 if params['aBool']: bvList.append(BitVector(bitstring="1")) 86 else: bvList.append(BitVector(bitstring="0")) 87 88 if validate and len(params['aStr']) != 5: raise ValueError 89 bvList.append(aisstring.encode(params['aStr'],5*6)) 90 91 # 16 bits 92 # scaleValue = 10 93 #tmpVal = int(params['anUDecimal']/Decimal('.1')) 94 #print 'an unsigned decimal tmpVal: ', params['anUDecimal'], '->',tmpVal 95 #bvList.append(binary.setBitVectorSize(BitVector(intVal=tmpVal),16)) 96 #del tmpVal 97 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(params['anUDecimal']/Decimal('.1'))),16)) 98 99 #tmpVal = int(params['aDecimal']/Decimal('10')) 100 #print 'a decimal tmpVal: ', params['aDecimal'], '->',tmpVal 101 #bvList.append(binary.bvFromSignedInt(tmpVal,16)) 102 bvList.append(binary.bvFromSignedInt(int(params['aDecimal']/Decimal('10')),16)) 103 104 # FIELD: aFloat (type=float) 105 bvList.append(binary.float2bitvec(params['aFloat'])) 106 107 return binary.joinBV(bvList)
108 109 110 ###################################################################### 111
112 -def decode(bv,validate=False):
113 '''Deserialize a binary water levelmessage 114 115 @param bv: bitvector containing the message portion of the assembled transmission 116 @param validate: set to true to check parsed values. If false, constant fields will not be parsed. 117 @return: dictory of fields and values 118 ''' 119 120 r={} # Results 121 r['dac'] = 366 # Constand value 122 if int(bv[0:16]) != 366: raise ValueError 123 124 print 'unavail: ',bv[16:16+2],int(bv[16:16+2]) 125 r['unavail_uint'] = int(bv[16:16+2]) 126 # FIX: what to do if this is set to the unavailable value? Prob another dict value of a bool with _available 127 128 r['anUInt'] = int(bv[18:18+2]) 129 r['anInt'] = binary.signedIntFromBV(bv[20:20+4]) 130 print 'bool:',bv[24:] 131 r['aBool'] = bool(int(bv[24])) 132 133 r['aStr'] = aisstring.decode(bv[25:25+5*6]) 134 135 r['anUDecimal'] = int(bv[55:55+16])*Decimal('.1') 136 r['aDecimal'] = binary.signedIntFromBV(bv[55+16:55+32])*Decimal('10') 137 138 base = 55+32 139 r['aFloat'] = binary.bitvec2float(bv[base:base+32]) 140 base += 32 141 142 return r
143 144 ###################################################################### 145 # UNIT TESTING 146 ###################################################################### 147 import unittest 148
149 -class TestEncode(unittest.TestCase):
150 '''Unit testing of the Template class. 151 Make lots of testFoo methods to exercise the class. 152 '''
153 - def testEncodeAllPresent(self):
154 '''Just encode 155 ''' 156 params = {} 157 params['unavail_uint']=1 158 params['anUInt']=2 159 params['anInt']=-3 160 params['aBool']=True 161 params['anUDecimal']=Decimal('4.5') 162 params['aDecimal']=-70000 163 params['aStr']='12345' 164 params['aFloat'] = -234.56 165 print params 166 bv = encode(params) 167 print bv 168 print 'decoding...' 169 r = decode (bv,validate=True) 170 print 'dict of decoded values:', r 171 self.failUnless(r['dac']==366) 172 self.failUnless(r['unavail_uint']==1) 173 self.failUnless(r['anUInt']==2) 174 self.failUnless(r['anInt']==-3) 175 self.failUnless(r['aBool']==True) 176 self.failUnless(r['anUDecimal']==Decimal('4.5')) 177 self.failUnless(r['aDecimal']==Decimal('-70000')) 178 print 'retrieved aFloat:',r['aFloat'] 179 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],2)
180 181 #bv = binary.setBitVectorSize(BitVector(intVal=366),16) 182 #decode (bv,validate=True) 183 #bv = BitVector(bitstring="01") 184 #decode (bv,validate=True) 185 #self.failUnless(1==1) 186 187 188 ############################################################ 189 if __name__=='__main__': 190 # print encode() 191 from optparse import OptionParser 192 myparser = OptionParser(usage="%prog [options]", 193 version="%prog "+__version__) 194 195 #sys.exit('EARLY EXIT - FIX: remove') 196 myparser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 197 help='run the documentation tests') 198 myparser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 199 help='run the unit tests') 200 myparser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 201 help='Make the test output verbose') 202 203 (options,args) = myparser.parse_args() 204 success=True 205 206 if options.doctest: 207 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 208 sys.argv= [sys.argv[0]] 209 if options.verbose: sys.argv.append('-v') 210 import doctest 211 numfail,numtests=doctest.testmod() 212 if numfail==0: print 'ok' 213 else: 214 print 'FAILED' 215 success=False 216 217 if not success: 218 sys.exit('Something Failed') 219 220 del success # Hide success from epydoc 221 222 223 if options.unittest: 224 sys.argv = [sys.argv[0]] 225 if options.verbose: sys.argv.append('-v') 226 227 unittest.main() 228