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

Source Code for Module ais.sls_header

  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 sls_header binary message payload to pack into an AIS Msg sls_header. 50 51 Fields in params: 52 - dac(uint): Designated Area Code 366 for US 53 - fid(uint): Functional Id (field automatically set to "1") 54 - reserved(uint): say what? (field automatically set to "0") 55 - MessageID(uint): Binary message indentifier 56 - BinaryData(binary): FIX: make this consume the rest! 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=params['dac']),10)) 66 bvList.append(binary.setBitVectorSize(BitVector(intVal=1),6)) 67 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 68 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID']),6)) 69 bvList.append(params['BinaryData']) 70 71 return binary.joinBV(bvList)
72
73 -def decode(bv, validate=False):
74 '''Unpack a sls_header message 75 76 Fields in params: 77 - dac(uint): Designated Area Code 366 for US 78 - fid(uint): Functional Id (field automatically set to "1") 79 - reserved(uint): say what? (field automatically set to "0") 80 - MessageID(uint): Binary message indentifier 81 - BinaryData(binary): FIX: make this consume the rest! 82 @type bv: BitVector 83 @param bv: Bits defining a message 84 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 85 @rtype: dict 86 @return: params 87 ''' 88 89 #Would be nice to check the bit count here.. 90 #if validate: 91 # assert (len(bv)==FIX: SOME NUMBER) 92 r = {} 93 r['dac']=int(bv[0:10]) 94 r['fid']=1 95 r['reserved']=0 96 r['MessageID']=int(bv[18:24]) 97 r['BinaryData']=bv[24:] 98 return r
99
100 -def decodedac(bv, validate=False):
101 return int(bv[0:10])
102
103 -def decodefid(bv, validate=False):
104 return 1
105
106 -def decodereserved(bv, validate=False):
107 return 0
108
109 -def decodeMessageID(bv, validate=False):
110 return int(bv[18:24])
111
112 -def decodeBinaryData(bv, validate=False):
113 return bv[24:]
114 115
116 -def printHtml(params, out=sys.stdout):
117 out.write("<h3>sls_header<h3>\n") 118 out.write("<table border=\"1\">\n") 119 out.write("<tr bgcolor=\"orange\">\n") 120 out.write("<th align=\"left\">Field Name</th>\n") 121 out.write("<th align=\"left\">Type</th>\n") 122 out.write("<th align=\"left\">Value</th>\n") 123 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 124 out.write("<th align=\"left\">Units</th>\n") 125 out.write("\n") 126 out.write("<tr>\n") 127 out.write("<td>dac</td>\n") 128 out.write("<td>uint</td>\n") 129 if 'dac' in params: 130 out.write(" <td>"+str(params['dac'])+"</td>\n") 131 out.write(" <td>"+str(params['dac'])+"</td>\n") 132 out.write("</tr>\n") 133 out.write("\n") 134 out.write("<tr>\n") 135 out.write("<td>fid</td>\n") 136 out.write("<td>uint</td>\n") 137 if 'fid' in params: 138 out.write(" <td>"+str(params['fid'])+"</td>\n") 139 out.write(" <td>"+str(params['fid'])+"</td>\n") 140 out.write("</tr>\n") 141 out.write("\n") 142 out.write("<tr>\n") 143 out.write("<td>reserved</td>\n") 144 out.write("<td>uint</td>\n") 145 if 'reserved' in params: 146 out.write(" <td>"+str(params['reserved'])+"</td>\n") 147 out.write(" <td>"+str(params['reserved'])+"</td>\n") 148 out.write("</tr>\n") 149 out.write("\n") 150 out.write("<tr>\n") 151 out.write("<td>MessageID</td>\n") 152 out.write("<td>uint</td>\n") 153 if 'MessageID' in params: 154 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 155 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 156 out.write("</tr>\n") 157 out.write("\n") 158 out.write("<tr>\n") 159 out.write("<td>BinaryData</td>\n") 160 out.write("<td>binary</td>\n") 161 if 'BinaryData' in params: 162 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 163 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 164 out.write("</tr>\n") 165 out.write("</table>\n")
166 -def printFields(params, out=sys.stdout, format='std'):
167 '''Print a BinaryData message to stdout. 168 169 Fields in params: 170 - dac(uint): Designated Area Code 366 for US 171 - fid(uint): Functional Id (field automatically set to "1") 172 - reserved(uint): say what? (field automatically set to "0") 173 - MessageID(uint): Binary message indentifier 174 - BinaryData(binary): FIX: make this consume the rest! 175 @param params: Dictionary of field names/values. 176 @param out: File like object to write to 177 @rtype: stdout 178 @return: text to out 179 ''' 180 181 if 'std'==format: 182 out.write("BinaryData:\n") 183 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n") 184 if 'fid' in params: out.write(" fid: "+str(params['fid'])+"\n") 185 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 186 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 187 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 188 elif 'html'==format: 189 printHtml(params,out) 190 else: 191 print "ERROR: unknown format:",format 192 assert False 193 194 return # Nothing to return
195 196 197 198 ###################################################################### 199 # UNIT TESTING 200 ###################################################################### 201 import unittest
202 -def testParams():
203 '''Return a params file base on the testvalue tags. 204 @rtype: dict 205 @return: params based on testvalue tags 206 ''' 207 params = {} 208 params['dac'] = 366 209 params['fid'] = 1 210 params['reserved'] = 0 211 params['MessageID'] = 3 212 params['BinaryData'] = BitVector(bitstring='0') 213 214 return params
215
216 -class Testsls_header(unittest.TestCase):
217 '''Use testvalue tag text from each type to build test case the sls_header message'''
218 - def testEncodeDecode(self):
219 220 params = testParams() 221 bits = encode(params) 222 r = decode(bits) 223 224 # Check that each parameter came through ok. 225 self.failUnlessEqual(r['dac'],params['dac']) 226 self.failUnlessEqual(r['fid'],params['fid']) 227 self.failUnlessEqual(r['reserved'],params['reserved']) 228 self.failUnlessEqual(r['MessageID'],params['MessageID']) 229 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
230
231 -def addMsgOptions(parser):
232 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 233 help='decode a "sls_header" AIS message') 234 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 235 help='encode a "sls_header" AIS message') 236 parser.add_option('--dac-field', dest='dacField',metavar='uint',type='int' 237 ,help='Field parameter value [default: %default]') 238 parser.add_option('--MessageID-field', dest='MessageIDField',metavar='uint',type='int' 239 ,help='Field parameter value [default: %default]') 240 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 241 ,help='Field parameter value [default: %default]')
242 243 ############################################################ 244 if __name__=='__main__': 245 246 from optparse import OptionParser 247 parser = OptionParser(usage="%prog [options]", 248 version="%prog "+__version__) 249 250 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 251 help='run the documentation tests') 252 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 253 help='run the unit tests') 254 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 255 help='Make the test output verbose') 256 257 # FIX: remove nmea from binary messages. No way to build the whole packet? 258 # FIX: or build the surrounding msg 8 for a broadcast? 259 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 260 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 261 ,default='nmeapayload' 262 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 263 264 265 outputChoices = ('std','html','xml' ) 266 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 267 ,default='std' 268 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 269 270 parser.add_option('-o','--output',dest='outputFileName',default=None, 271 help='Name of the python file to write [default: stdout]') 272 273 addMsgOptions(parser) 274 275 (options,args) = parser.parse_args() 276 success=True 277 278 if options.doctest: 279 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 280 sys.argv= [sys.argv[0]] 281 if options.verbose: sys.argv.append('-v') 282 import doctest 283 numfail,numtests=doctest.testmod() 284 if numfail==0: print 'ok' 285 else: 286 print 'FAILED' 287 success=False 288 289 if not success: sys.exit('Something Failed') 290 del success # Hide success from epydoc 291 292 if options.unittest: 293 sys.argv = [sys.argv[0]] 294 if options.verbose: sys.argv.append('-v') 295 unittest.main() 296 297 outfile = sys.stdout 298 if None!=options.outputFileName: 299 outfile = file(options.outputFileName,'w') 300 301 302 if options.doEncode: 303 # First make sure all non required options are specified 304 if None==options.dacField: parser.error("missing value for dacField") 305 if None==options.MessageIDField: parser.error("missing value for MessageIDField") 306 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 307 msgDict={ 308 'dac': options.dacField, 309 'fid': '1', 310 'reserved': '0', 311 'MessageID': options.MessageIDField, 312 'BinaryData': options.BinaryDataField, 313 } 314 315 bits = encode(msgDict) 316 if 'binary'==options.ioType: print str(bits) 317 elif 'nmeapayload'==options.ioType: 318 # FIX: figure out if this might be necessary at compile time 319 print "bitLen",len(bits) 320 bitLen=len(bits) 321 if bitLen%6!=0: 322 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 323 print "result:",binary.bitvectoais6(bits)[0] 324 325 326 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 327 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 328 else: sys.exit('ERROR: unknown ioType. Help!') 329 330 if options.doDecode: 331 for msg in args: 332 bv = None 333 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 334 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 335 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 336 else: sys.exit('ERROR: unknown ioType. Help!') 337 338 printFields(decode(bv),out=outfile,format=options.outputType) 339