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