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-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  fieldList = [ 
 49          'MessageID', 
 50          'RepeatIndicator', 
 51          'UserID', 
 52          'Spare', 
 53          'BinaryData', 
 54  ] 
 55   
56 -def encode(params, validate=False):
57 '''Create a bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast. 58 59 Fields in params: 60 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 61 - RepeatIndicator(uint): Indicated how many times a message has been repeated 62 - UserID(uint): Unique ship identification number (MMSI) 63 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 64 - BinaryData(binary): Bits for a binary broadcast message 65 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 66 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 67 @rtype: BitVector 68 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 69 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 70 ''' 71 72 bvList = [] 73 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6)) 74 if 'RepeatIndicator' in params: 75 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 76 else: 77 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 78 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 79 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 80 bvList.append(params['BinaryData']) 81 82 return binary.joinBV(bvList)
83
84 -def decode(bv, validate=False):
85 '''Unpack a bin_broadcast message 86 87 Fields in params: 88 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 89 - RepeatIndicator(uint): Indicated how many times a message has been repeated 90 - UserID(uint): Unique ship identification number (MMSI) 91 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 92 - BinaryData(binary): Bits for a binary broadcast message 93 @type bv: BitVector 94 @param bv: Bits defining a message 95 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 96 @rtype: dict 97 @return: params 98 ''' 99 100 #Would be nice to check the bit count here.. 101 #if validate: 102 # assert (len(bv)==FIX: SOME NUMBER) 103 r = {} 104 r['MessageID']=8 105 r['RepeatIndicator']=int(bv[6:8]) 106 r['UserID']=int(bv[8:38]) 107 r['Spare']=0 108 r['BinaryData']=bv[40:] 109 return r
110
111 -def decodeMessageID(bv, validate=False):
112 return 8
113
114 -def decodeRepeatIndicator(bv, validate=False):
115 return int(bv[6:8])
116
117 -def decodeUserID(bv, validate=False):
118 return int(bv[8:38])
119
120 -def decodeSpare(bv, validate=False):
121 return 0
122
123 -def decodeBinaryData(bv, validate=False):
124 return bv[40:]
125 126
127 -def printHtml(params, out=sys.stdout):
128 out.write("<h3>bin_broadcast<h3>\n") 129 out.write("<table border=\"1\">\n") 130 out.write("<tr bgcolor=\"orange\">\n") 131 out.write("<th align=\"left\">Field Name</th>\n") 132 out.write("<th align=\"left\">Type</th>\n") 133 out.write("<th align=\"left\">Value</th>\n") 134 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 135 out.write("<th align=\"left\">Units</th>\n") 136 out.write("\n") 137 out.write("<tr>\n") 138 out.write("<td>MessageID</td>\n") 139 out.write("<td>uint</td>\n") 140 if 'MessageID' in params: 141 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 142 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 143 out.write("</tr>\n") 144 out.write("\n") 145 out.write("<tr>\n") 146 out.write("<td>RepeatIndicator</td>\n") 147 out.write("<td>uint</td>\n") 148 if 'RepeatIndicator' in params: 149 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 150 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 151 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 152 else: 153 out.write("<td><i>Missing LUT entry</i></td>") 154 out.write("</tr>\n") 155 out.write("\n") 156 out.write("<tr>\n") 157 out.write("<td>UserID</td>\n") 158 out.write("<td>uint</td>\n") 159 if 'UserID' in params: 160 out.write(" <td>"+str(params['UserID'])+"</td>\n") 161 out.write(" <td>"+str(params['UserID'])+"</td>\n") 162 out.write("</tr>\n") 163 out.write("\n") 164 out.write("<tr>\n") 165 out.write("<td>Spare</td>\n") 166 out.write("<td>uint</td>\n") 167 if 'Spare' in params: 168 out.write(" <td>"+str(params['Spare'])+"</td>\n") 169 out.write(" <td>"+str(params['Spare'])+"</td>\n") 170 out.write("</tr>\n") 171 out.write("\n") 172 out.write("<tr>\n") 173 out.write("<td>BinaryData</td>\n") 174 out.write("<td>binary</td>\n") 175 if 'BinaryData' in params: 176 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 177 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 178 out.write("</tr>\n") 179 out.write("</table>\n")
180
181 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
182 '''Print a BinaryData message to stdout. 183 184 Fields in params: 185 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 186 - RepeatIndicator(uint): Indicated how many times a message has been repeated 187 - UserID(uint): Unique ship identification number (MMSI) 188 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 189 - BinaryData(binary): Bits for a binary broadcast message 190 @param params: Dictionary of field names/values. 191 @param out: File like object to write to 192 @rtype: stdout 193 @return: text to out 194 ''' 195 196 if 'std'==format: 197 out.write("BinaryData:\n") 198 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 199 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 200 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 201 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 202 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 203 elif 'csv'==format: 204 if None == options.fieldList: 205 options.fieldList = fieldList 206 needComma = False; 207 for field in fieldList: 208 if needComma: out.write(',') 209 needComma = True 210 if field in params: 211 out.write(str(params[field])) 212 # else: leave it empty 213 out.write("\n") 214 elif 'html'==format: 215 printHtml(params,out) 216 else: 217 print "ERROR: unknown format:",format 218 assert False 219 220 return # Nothing to return
221 222 RepeatIndicatorEncodeLut = { 223 'default':'0', 224 'do not repeat any more':'3', 225 } #RepeatIndicatorEncodeLut 226 227 RepeatIndicatorDecodeLut = { 228 '0':'default', 229 '3':'do not repeat any more', 230 } # RepeatIndicatorEncodeLut 231 232 233 234 ###################################################################### 235 # UNIT TESTING 236 ###################################################################### 237 import unittest
238 -def testParams():
239 '''Return a params file base on the testvalue tags. 240 @rtype: dict 241 @return: params based on testvalue tags 242 ''' 243 params = {} 244 params['MessageID'] = 8 245 params['RepeatIndicator'] = 1 246 params['UserID'] = 1193046 247 params['Spare'] = 0 248 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110') 249 250 return params
251
252 -class Testbin_broadcast(unittest.TestCase):
253 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
254 - def testEncodeDecode(self):
255 256 params = testParams() 257 bits = encode(params) 258 r = decode(bits) 259 260 # Check that each parameter came through ok. 261 self.failUnlessEqual(r['MessageID'],params['MessageID']) 262 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 263 self.failUnlessEqual(r['UserID'],params['UserID']) 264 self.failUnlessEqual(r['Spare'],params['Spare']) 265 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
266
267 -def addMsgOptions(parser):
268 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 269 help='decode a "bin_broadcast" AIS message') 270 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 271 help='encode a "bin_broadcast" AIS message') 272 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 273 ,help='Field parameter value [default: %default]') 274 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 275 ,help='Field parameter value [default: %default]') 276 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 277 ,help='Field parameter value [default: %default]')
278 279 ############################################################ 280 if __name__=='__main__': 281 282 from optparse import OptionParser 283 parser = OptionParser(usage="%prog [options]", 284 version="%prog "+__version__) 285 286 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 287 help='run the documentation tests') 288 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 289 help='run the unit tests') 290 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 291 help='Make the test output verbose') 292 293 # FIX: remove nmea from binary messages. No way to build the whole packet? 294 # FIX: or build the surrounding msg 8 for a broadcast? 295 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 296 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 297 ,default='nmeapayload' 298 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 299 300 301 outputChoices = ('std','html','csv' ) 302 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 303 ,default='std' 304 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 305 306 parser.add_option('-o','--output',dest='outputFileName',default=None, 307 help='Name of the python file to write [default: stdout]') 308 309 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 310 choices=fieldList, 311 help='Which fields to include in the output. Currently only for csv output [default: all]') 312 313 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 314 help='Print the field name for csv') 315 316 addMsgOptions(parser) 317 318 (options,args) = parser.parse_args() 319 success=True 320 321 if options.doctest: 322 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 323 sys.argv= [sys.argv[0]] 324 if options.verbose: sys.argv.append('-v') 325 import doctest 326 numfail,numtests=doctest.testmod() 327 if numfail==0: print 'ok' 328 else: 329 print 'FAILED' 330 success=False 331 332 if not success: sys.exit('Something Failed') 333 del success # Hide success from epydoc 334 335 if options.unittest: 336 sys.argv = [sys.argv[0]] 337 if options.verbose: sys.argv.append('-v') 338 unittest.main() 339 340 outfile = sys.stdout 341 if None!=options.outputFileName: 342 outfile = file(options.outputFileName,'w') 343 344 345 if options.doEncode: 346 # First make sure all non required options are specified 347 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 348 if None==options.UserIDField: parser.error("missing value for UserIDField") 349 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 350 msgDict={ 351 'MessageID': '8', 352 'RepeatIndicator': options.RepeatIndicatorField, 353 'UserID': options.UserIDField, 354 'Spare': '0', 355 'BinaryData': options.BinaryDataField, 356 } 357 358 bits = encode(msgDict) 359 if 'binary'==options.ioType: print str(bits) 360 elif 'nmeapayload'==options.ioType: 361 # FIX: figure out if this might be necessary at compile time 362 print "bitLen",len(bits) 363 bitLen=len(bits) 364 if bitLen%6!=0: 365 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 366 print "result:",binary.bitvectoais6(bits)[0] 367 368 369 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 370 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 371 else: sys.exit('ERROR: unknown ioType. Help!') 372 373 if options.printCsvfieldList: 374 # Make a csv separated list of fields that will be displayed for csv 375 if None == options.fieldList: options.fieldList = fieldList 376 import StringIO 377 buf = StringIO.StringIO() 378 for field in options.fieldList: 379 buf.write(field+',') 380 result = buf.getvalue() 381 if result[-1] == ',': print result[:-1] 382 else: print result 383 384 if options.doDecode: 385 for msg in args: 386 bv = None 387 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 388 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 389 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 390 else: sys.exit('ERROR: unknown ioType. Help!') 391 392 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 393