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-05 $'.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
119 -def printHtml(params, out=sys.stdout):
120 out.write("<h3>bin_broadcast<h3>\n") 121 out.write("<table border=\"1\">\n") 122 out.write("<tr bgcolor=\"orange\">\n") 123 out.write("<th align=\"left\">Field Name</th>\n") 124 out.write("<th align=\"left\">Type</th>\n") 125 out.write("<th align=\"left\">Value</th>\n") 126 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 127 out.write("\n") 128 out.write("<tr>\n") 129 out.write("<td>MessageID</td>\n") 130 out.write("<td>uint</td>\n") 131 if 'MessageID' in params: 132 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 133 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 134 out.write("</tr>\n") 135 out.write("\n") 136 out.write("<tr>\n") 137 out.write("<td>RepeatIndicator</td>\n") 138 out.write("<td>uint</td>\n") 139 if 'RepeatIndicator' in params: 140 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 141 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 142 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 143 else: 144 out.write("<td><i>Missing LUT entry</i></td>") 145 out.write("</tr>\n") 146 out.write("\n") 147 out.write("<tr>\n") 148 out.write("<td>UserID</td>\n") 149 out.write("<td>uint</td>\n") 150 if 'UserID' in params: 151 out.write(" <td>"+str(params['UserID'])+"</td>\n") 152 out.write(" <td>"+str(params['UserID'])+"</td>\n") 153 out.write("</tr>\n") 154 out.write("\n") 155 out.write("<tr>\n") 156 out.write("<td>Spare</td>\n") 157 out.write("<td>uint</td>\n") 158 if 'Spare' in params: 159 out.write(" <td>"+str(params['Spare'])+"</td>\n") 160 out.write(" <td>"+str(params['Spare'])+"</td>\n") 161 out.write("</tr>\n") 162 out.write("\n") 163 out.write("<tr>\n") 164 out.write("<td>BinaryData</td>\n") 165 out.write("<td>binary</td>\n") 166 if 'BinaryData' in params: 167 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 168 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 169 out.write("</tr>\n") 170 out.write("</table>\n")
171 -def printFields(params, out=sys.stdout, format='std'):
172 '''Print a BinaryData message to stdout. 173 174 Fields in params: 175 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 176 - RepeatIndicator(uint): Indicated how many times a message has been repeated 177 - UserID(uint): Unique ship identification number (MMSI) 178 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 179 - BinaryData(binary): Bits for a binary broadcast message 180 @param params: Dictionary of field names/values. 181 @param out: File like object to write to 182 @rtype: stdout 183 @return: text to out 184 ''' 185 186 if 'std'==format: 187 out.write("BinaryData:\n") 188 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 189 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 190 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 191 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 192 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 193 elif 'html'==format: 194 printHtml(params,out) 195 else: 196 print "ERROR: unknown format:",format 197 assert False 198 199 return # Nothing to return
200 201 RepeatIndicatorEncodeLut = { 202 'default':'0', 203 'do not repeat any more':'3', 204 } #RepeatIndicatorEncodeLut 205 206 RepeatIndicatorDecodeLut = { 207 '0':'default', 208 '3':'do not repeat any more', 209 } # RepeatIndicatorEncodeLut 210 211 212 213 ###################################################################### 214 # UNIT TESTING 215 ###################################################################### 216 import unittest
217 -def testParams():
218 '''Return a params file base on the testvalue tags. 219 @rtype: dict 220 @return: params based on testvalue tags 221 ''' 222 params = {} 223 params['MessageID'] = 8 224 params['RepeatIndicator'] = 1 225 params['UserID'] = 1193046 226 params['Spare'] = 0 227 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110') 228 229 return params
230
231 -class Testbin_broadcast(unittest.TestCase):
232 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
233 - def testEncodeDecode(self):
234 235 params = testParams() 236 bits = encode(params) 237 r = decode(bits) 238 239 # Check that each parameter came through ok. 240 self.failUnlessEqual(r['MessageID'],params['MessageID']) 241 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 242 self.failUnlessEqual(r['UserID'],params['UserID']) 243 self.failUnlessEqual(r['Spare'],params['Spare']) 244 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
245
246 -def addMsgOptions(parser):
247 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 248 help='decode a "bin_broadcast" AIS message') 249 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 250 help='encode a "bin_broadcast" AIS message') 251 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 252 ,help='Field parameter value [default: %default]') 253 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 254 ,help='Field parameter value [default: %default]') 255 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 256 ,help='Field parameter value [default: %default]')
257 258 ############################################################ 259 if __name__=='__main__': 260 261 from optparse import OptionParser 262 parser = OptionParser(usage="%prog [options]", 263 version="%prog "+__version__) 264 265 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 266 help='run the documentation tests') 267 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 268 help='run the unit tests') 269 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 270 help='Make the test output verbose') 271 272 # FIX: remove nmea from binary messages. No way to build the whole packet? 273 # FIX: or build the surrounding msg 8 for a broadcast? 274 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 275 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 276 ,default='nmeapayload' 277 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 278 279 280 outputChoices = ('std','html','xml' ) 281 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 282 ,default='std' 283 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 284 285 parser.add_option('-o','--output',dest='outputFileName',default=None, 286 help='Name of the python file to write [default: stdout]') 287 288 addMsgOptions(parser) 289 290 (options,args) = parser.parse_args() 291 success=True 292 293 if options.doctest: 294 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 295 sys.argv= [sys.argv[0]] 296 if options.verbose: sys.argv.append('-v') 297 import doctest 298 numfail,numtests=doctest.testmod() 299 if numfail==0: print 'ok' 300 else: 301 print 'FAILED' 302 success=False 303 304 if not success: sys.exit('Something Failed') 305 del success # Hide success from epydoc 306 307 if options.unittest: 308 sys.argv = [sys.argv[0]] 309 if options.verbose: sys.argv.append('-v') 310 unittest.main() 311 312 outfile = sys.stdout 313 if None!=options.outputFileName: 314 outfile = file(options.outputFileName,'w') 315 316 317 if options.doEncode: 318 # First make sure all non required options are specified 319 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 320 if None==options.UserIDField: parser.error("missing value for UserIDField") 321 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 322 msgDict={ 323 'MessageID': '8', 324 'RepeatIndicator': options.RepeatIndicatorField, 325 'UserID': options.UserIDField, 326 'Spare': '0', 327 'BinaryData': options.BinaryDataField, 328 } 329 330 bits = encode(msgDict) 331 if 'binary'==options.ioType: print str(bits) 332 elif 'nmeapayload'==options.ioType: 333 # FIX: figure out if this might be necessary at compile time 334 print "bitLen",len(bits) 335 bitLen=len(bits) 336 if bitLen%6!=0: 337 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 338 print "result:",binary.bitvectoais6(bits)[0] 339 340 341 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 342 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 343 else: sys.exit('ERROR: unknown ioType. Help!') 344 345 if options.doDecode: 346 for msg in args: 347 bv = None 348 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 349 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 350 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 351 else: sys.exit('ERROR: unknown ioType. Help!') 352 353 printFields(decode(bv),out=outfile,format=options.outputType) 354