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

Source Code for Module ais.ais_msg_8

  1  #!/usr/bin/env python 
  2   
  3  __version__ = '$Revision: 4791 $'.split()[1] 
  4  __date__ = '$Date: 2007-01-02 $'.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 bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast. 50 51 Fields in params: 52 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 53 - RepeatIndicator(uint): Indicated how many times a message has been repeated 54 - UserID(uint): Unique ship identification number (MMSI) 55 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 56 - BinaryData(binary): Bits for a binary broadcast message 57 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 58 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 59 @rtype: BitVector 60 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 61 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 62 ''' 63 64 bvList = [] 65 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6)) 66 if 'RepeatIndicator' in params: 67 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 68 else: 69 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 70 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 71 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 72 bvList.append(params['BinaryData']) 73 74 return binary.joinBV(bvList)
75
76 -def decode(bv, validate=False):
77 '''Unpack a bin_broadcast message 78 79 Fields in params: 80 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 81 - RepeatIndicator(uint): Indicated how many times a message has been repeated 82 - UserID(uint): Unique ship identification number (MMSI) 83 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 84 - BinaryData(binary): Bits for a binary broadcast message 85 @type bv: BitVector 86 @param bv: Bits defining a message 87 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 88 @rtype: dict 89 @return: params 90 ''' 91 92 #Would be nice to check the bit count here.. 93 #if validate: 94 # assert (len(bv)==FIX: SOME NUMBER) 95 r = {} 96 r['MessageID']=8 97 r['RepeatIndicator']=int(bv[6:8]) 98 r['UserID']=int(bv[8:38]) 99 r['Spare']=0 100 r['BinaryData']=bv[40:] 101 return r
102
103 -def decodeMessageID(bv, validate=False):
104 return 8
105
106 -def decodeRepeatIndicator(bv, validate=False):
107 return int(bv[6:8])
108
109 -def decodeUserID(bv, validate=False):
110 return int(bv[8:38])
111
112 -def decodeSpare(bv, validate=False):
113 return 0
114
115 -def decodeBinaryData(bv, validate=False):
116 return bv[40:]
117
118 -def printFields(params, out=sys.stdout, format='std'):
119 '''Print a bin_broadcast message to stdout. 120 121 Fields in params: 122 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 123 - RepeatIndicator(uint): Indicated how many times a message has been repeated 124 - UserID(uint): Unique ship identification number (MMSI) 125 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 126 - BinaryData(binary): Bits for a binary broadcast message 127 @param params: Dictionary of field names/values. 128 @param out: File like object to write to 129 @rtype: stdout 130 @return: text to out 131 ''' 132 133 if 'std'==format: 134 out.write("bin_broadcast:\n") 135 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 136 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 137 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 138 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 139 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 140 141 return # Nothing to return
142 143 144 145 ###################################################################### 146 # UNIT TESTING 147 ###################################################################### 148 import unittest
149 -def testParams():
150 '''Return a params file base on the testvalue tags. 151 @rtype: dict 152 @return: params based on testvalue tags 153 ''' 154 params = {} 155 params['MessageID'] = 8 156 params['RepeatIndicator'] = 1 157 params['UserID'] = 1193046 158 params['Spare'] = 0 159 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110') 160 161 return params
162
163 -class Testbin_broadcast(unittest.TestCase):
164 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
165 - def testEncodeDecode(self):
166 167 params = testParams() 168 bits = encode(params) 169 r = decode(bits) 170 171 # Check that each parameter came through ok. 172 self.failUnlessEqual(r['MessageID'],params['MessageID']) 173 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 174 self.failUnlessEqual(r['UserID'],params['UserID']) 175 self.failUnlessEqual(r['Spare'],params['Spare']) 176 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
177
178 -def addMsgOptions(parser):
179 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 180 help='decode a "bin_broadcast" AIS message') 181 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 182 help='encode a "bin_broadcast" AIS message') 183 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 184 ,help='Field parameter value [default: %default]') 185 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 186 ,help='Field parameter value [default: %default]') 187 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 188 ,help='Field parameter value [default: %default]')
189 190 ############################################################ 191 if __name__=='__main__': 192 193 from optparse import OptionParser 194 parser = OptionParser(usage="%prog [options]", 195 version="%prog "+__version__) 196 197 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 198 help='run the documentation tests') 199 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 200 help='run the unit tests') 201 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 202 help='Make the test output verbose') 203 204 # FIX: remove nmea from binary messages. No way to build the whole packet? 205 # FIX: or build the surrounding msg 8 for a broadcast? 206 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 207 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 208 ,default='nmeapayload' 209 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 210 addMsgOptions(parser) 211 212 (options,args) = parser.parse_args() 213 success=True 214 215 if options.doctest: 216 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 217 sys.argv= [sys.argv[0]] 218 if options.verbose: sys.argv.append('-v') 219 import doctest 220 numfail,numtests=doctest.testmod() 221 if numfail==0: print 'ok' 222 else: 223 print 'FAILED' 224 success=False 225 226 if not success: sys.exit('Something Failed') 227 del success # Hide success from epydoc 228 229 if options.unittest: 230 sys.argv = [sys.argv[0]] 231 if options.verbose: sys.argv.append('-v') 232 unittest.main() 233 234 if options.doEncode: 235 # First make sure all non required options are specified 236 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 237 if None==options.UserIDField: parser.error("missing value for UserIDField") 238 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 239 msgDict={ 240 'MessageID': '8', 241 'RepeatIndicator': options.RepeatIndicatorField, 242 'UserID': options.UserIDField, 243 'Spare': '0', 244 'BinaryData': options.BinaryDataField, 245 } 246 247 bits = encode(msgDict) 248 if 'binary'==options.ioType: print str(bits) 249 elif 'nmeapayload'==options.ioType: 250 # FIX: figure out if this might be necessary at compile time 251 print "bitLen",len(bits) 252 bitLen=len(bits) 253 if bitLen%6!=0: 254 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 255 print "result:",binary.bitvectoais6(bits)[0] 256 257 258 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 259 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 260 else: sys.exit('ERROR: unknown ioType. Help!') 261 262 if options.doDecode: 263 for msg in args: 264 if 'binary'==options.ioType: 265 bv = BitVector(bitstring=msg) 266 printFields(decode(bv)) 267 268 elif 'nmeapayload'==options.ioType: 269 bv = binary.ais6tobitvec(msg) 270 printFields(decode(bv)) 271 272 elif 'nmea'==options.ioType: 273 bv = binary.ais6tobitvec(msg.split(',')[5]) 274 printFields(decode(bv)) 275 else: sys.exit('ERROR: unknown ioType. Help!') 276