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-02-08 $'.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          'dac', 
 50          'fid', 
 51          'reserved', 
 52          'MessageID', 
 53          'BinaryData', 
 54  ] 
 55   
56 -def encode(params, validate=False):
57 '''Create a sls_header binary message payload to pack into an AIS Msg sls_header. 58 59 Fields in params: 60 - dac(uint): Designated Area Code 366 for US 61 - fid(uint): Functional Id (field automatically set to "1") 62 - reserved(uint): say what? (field automatically set to "0") 63 - MessageID(uint): Binary message indentifier 64 - BinaryData(binary): FIX: make this consume the rest! 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=params['dac']),10)) 74 bvList.append(binary.setBitVectorSize(BitVector(intVal=1),6)) 75 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 76 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID']),6)) 77 bvList.append(params['BinaryData']) 78 79 return binary.joinBV(bvList)
80
81 -def decode(bv, validate=False):
82 '''Unpack a sls_header message 83 84 Fields in params: 85 - dac(uint): Designated Area Code 366 for US 86 - fid(uint): Functional Id (field automatically set to "1") 87 - reserved(uint): say what? (field automatically set to "0") 88 - MessageID(uint): Binary message indentifier 89 - BinaryData(binary): FIX: make this consume the rest! 90 @type bv: BitVector 91 @param bv: Bits defining a message 92 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 93 @rtype: dict 94 @return: params 95 ''' 96 97 #Would be nice to check the bit count here.. 98 #if validate: 99 # assert (len(bv)==FIX: SOME NUMBER) 100 r = {} 101 r['dac']=int(bv[0:10]) 102 r['fid']=1 103 r['reserved']=0 104 r['MessageID']=int(bv[18:24]) 105 r['BinaryData']=bv[24:] 106 return r
107
108 -def decodedac(bv, validate=False):
109 return int(bv[0:10])
110
111 -def decodefid(bv, validate=False):
112 return 1
113
114 -def decodereserved(bv, validate=False):
115 return 0
116
117 -def decodeMessageID(bv, validate=False):
118 return int(bv[18:24])
119
120 -def decodeBinaryData(bv, validate=False):
121 return bv[24:]
122 123
124 -def printHtml(params, out=sys.stdout):
125 out.write("<h3>sls_header<h3>\n") 126 out.write("<table border=\"1\">\n") 127 out.write("<tr bgcolor=\"orange\">\n") 128 out.write("<th align=\"left\">Field Name</th>\n") 129 out.write("<th align=\"left\">Type</th>\n") 130 out.write("<th align=\"left\">Value</th>\n") 131 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 132 out.write("<th align=\"left\">Units</th>\n") 133 out.write("\n") 134 out.write("<tr>\n") 135 out.write("<td>dac</td>\n") 136 out.write("<td>uint</td>\n") 137 if 'dac' in params: 138 out.write(" <td>"+str(params['dac'])+"</td>\n") 139 out.write(" <td>"+str(params['dac'])+"</td>\n") 140 out.write("</tr>\n") 141 out.write("\n") 142 out.write("<tr>\n") 143 out.write("<td>fid</td>\n") 144 out.write("<td>uint</td>\n") 145 if 'fid' in params: 146 out.write(" <td>"+str(params['fid'])+"</td>\n") 147 out.write(" <td>"+str(params['fid'])+"</td>\n") 148 out.write("</tr>\n") 149 out.write("\n") 150 out.write("<tr>\n") 151 out.write("<td>reserved</td>\n") 152 out.write("<td>uint</td>\n") 153 if 'reserved' in params: 154 out.write(" <td>"+str(params['reserved'])+"</td>\n") 155 out.write(" <td>"+str(params['reserved'])+"</td>\n") 156 out.write("</tr>\n") 157 out.write("\n") 158 out.write("<tr>\n") 159 out.write("<td>MessageID</td>\n") 160 out.write("<td>uint</td>\n") 161 if 'MessageID' in params: 162 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 163 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 164 out.write("</tr>\n") 165 out.write("\n") 166 out.write("<tr>\n") 167 out.write("<td>BinaryData</td>\n") 168 out.write("<td>binary</td>\n") 169 if 'BinaryData' in params: 170 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 171 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 172 out.write("</tr>\n") 173 out.write("</table>\n")
174
175 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
176 '''Print a BinaryData message to stdout. 177 178 Fields in params: 179 - dac(uint): Designated Area Code 366 for US 180 - fid(uint): Functional Id (field automatically set to "1") 181 - reserved(uint): say what? (field automatically set to "0") 182 - MessageID(uint): Binary message indentifier 183 - BinaryData(binary): FIX: make this consume the rest! 184 @param params: Dictionary of field names/values. 185 @param out: File like object to write to 186 @rtype: stdout 187 @return: text to out 188 ''' 189 190 if 'std'==format: 191 out.write("BinaryData:\n") 192 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n") 193 if 'fid' in params: out.write(" fid: "+str(params['fid'])+"\n") 194 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 195 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 196 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 197 elif 'csv'==format: 198 if None == options.fieldList: 199 options.fieldList = fieldList 200 needComma = False; 201 for field in fieldList: 202 if needComma: out.write(',') 203 needComma = True 204 if field in params: 205 out.write(str(params[field])) 206 # else: leave it empty 207 out.write("\n") 208 elif 'html'==format: 209 printHtml(params,out) 210 elif 'sql'==format: 211 sqlInsertStr(params,out) 212 else: 213 print "ERROR: unknown format:",format 214 assert False 215 216 return # Nothing to return
217 218 ###################################################################### 219 # SQL SUPPORT 220 ###################################################################### 221
222 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None, addCoastGuardFields=True):
223 ''' 224 Return the SQL CREATE command for this message type 225 @param outfile: file like object to print to. 226 @param fields: which fields to put in the create. Defaults to all. 227 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 228 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 229 @type addCoastGuardFields: bool 230 @return: sql create string 231 @rtype: str 232 233 @see: sqlCreate 234 ''' 235 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields)))
236
237 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True):
238 ''' 239 Return the sqlhelp object to create the table. 240 241 @param fields: which fields to put in the create. Defaults to all. 242 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 243 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 244 @type addCoastGuardFields: bool 245 @return: An object that can be used to generate a return 246 @rtype: sqlhelp.create 247 ''' 248 if None == fields: fields = fieldList 249 import sqlhelp 250 c = sqlhelp.create('sls_header') 251 if 'dac' in fields: c.addInt ('dac') 252 if 'fid' in fields: c.addInt ('fid') 253 if 'reserved' in fields: c.addInt ('reserved') 254 if 'MessageID' in fields: c.addInt ('MessageID') 255 if 'BinaryData' in fields: c.addBitVarying('BinaryData',1024) 256 257 if addCoastGuardFields: 258 # c.addInt('cg_rssi') # Relative signal strength indicator 259 # c.addInt('cg_d') # dBm receive strength 260 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 261 # c.addInt('cg_S') # Slot received in 262 # c.addVarChar('cg_x',10) # Idonno 263 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 264 c.addInt('cg_timestamp') # UTC seconds since the epoch 265 # FIX: maybe an actually time field? 266 267 return c
268
269 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
270 ''' 271 Return the SQL CREATE command for this message type 272 @param params: dictionary of values keyed by field name 273 @param outfile: file like object to print to. 274 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 275 @return: sql create string 276 @rtype: str 277 278 @see: sqlCreate 279 ''' 280 outfile.write(str(sqlInsert(params,extraParams)))
281 282
283 -def sqlInsert(params,extraParams=None):
284 ''' 285 Give the SQL insert statement 286 @param params: dict keyed by field name of values 287 @param extraParams: any extra fields that you have created beyond the normal ais message fields 288 @rtype: sqlhelp.insert 289 @return: insert class instance 290 @todo: allow optional type checking of params? 291 @warning: this will take invalid keys happily and do what??? 292 ''' 293 import sqlhelp 294 i = sqlhelp.insert('sls_header') 295 for key in params: 296 #i.add(key,params[key]) 297 if type(params[key])==Decimal: i.add(key,float(params[key])) 298 else: i.add(key,params[key]) 299 if None != extraParams: 300 for key in extraParams: 301 i.add(key,extraParams[key]) 302 303 return i
304 305 306 ###################################################################### 307 # UNIT TESTING 308 ###################################################################### 309 import unittest
310 -def testParams():
311 '''Return a params file base on the testvalue tags. 312 @rtype: dict 313 @return: params based on testvalue tags 314 ''' 315 params = {} 316 params['dac'] = 366 317 params['fid'] = 1 318 params['reserved'] = 0 319 params['MessageID'] = 3 320 params['BinaryData'] = BitVector(bitstring='0') 321 322 return params
323
324 -class Testsls_header(unittest.TestCase):
325 '''Use testvalue tag text from each type to build test case the sls_header message'''
326 - def testEncodeDecode(self):
327 328 params = testParams() 329 bits = encode(params) 330 r = decode(bits) 331 332 # Check that each parameter came through ok. 333 self.failUnlessEqual(r['dac'],params['dac']) 334 self.failUnlessEqual(r['fid'],params['fid']) 335 self.failUnlessEqual(r['reserved'],params['reserved']) 336 self.failUnlessEqual(r['MessageID'],params['MessageID']) 337 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
338
339 -def addMsgOptions(parser):
340 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 341 help='decode a "sls_header" AIS message') 342 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 343 help='encode a "sls_header" AIS message') 344 parser.add_option('--dac-field', dest='dacField',metavar='uint',type='int' 345 ,help='Field parameter value [default: %default]') 346 parser.add_option('--MessageID-field', dest='MessageIDField',metavar='uint',type='int' 347 ,help='Field parameter value [default: %default]') 348 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 349 ,help='Field parameter value [default: %default]')
350 351 ############################################################ 352 if __name__=='__main__': 353 354 from optparse import OptionParser 355 parser = OptionParser(usage="%prog [options]", 356 version="%prog "+__version__) 357 358 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 359 help='run the documentation tests') 360 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 361 help='run the unit tests') 362 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 363 help='Make the test output verbose') 364 365 # FIX: remove nmea from binary messages. No way to build the whole packet? 366 # FIX: or build the surrounding msg 8 for a broadcast? 367 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 368 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 369 ,default='nmeapayload' 370 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 371 372 373 outputChoices = ('std','html','csv','sql' ) 374 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 375 ,default='std' 376 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 377 378 parser.add_option('-o','--output',dest='outputFileName',default=None, 379 help='Name of the python file to write [default: stdout]') 380 381 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 382 choices=fieldList, 383 help='Which fields to include in the output. Currently only for csv output [default: all]') 384 385 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 386 help='Print the field name for csv') 387 388 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 389 help='Print out an sql create command for the table.') 390 391 addMsgOptions(parser) 392 393 (options,args) = parser.parse_args() 394 success=True 395 396 if options.doctest: 397 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 398 sys.argv= [sys.argv[0]] 399 if options.verbose: sys.argv.append('-v') 400 import doctest 401 numfail,numtests=doctest.testmod() 402 if numfail==0: print 'ok' 403 else: 404 print 'FAILED' 405 success=False 406 407 if not success: sys.exit('Something Failed') 408 del success # Hide success from epydoc 409 410 if options.unittest: 411 sys.argv = [sys.argv[0]] 412 if options.verbose: sys.argv.append('-v') 413 unittest.main() 414 415 outfile = sys.stdout 416 if None!=options.outputFileName: 417 outfile = file(options.outputFileName,'w') 418 419 420 if options.doEncode: 421 # First make sure all non required options are specified 422 if None==options.dacField: parser.error("missing value for dacField") 423 if None==options.MessageIDField: parser.error("missing value for MessageIDField") 424 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 425 msgDict={ 426 'dac': options.dacField, 427 'fid': '1', 428 'reserved': '0', 429 'MessageID': options.MessageIDField, 430 'BinaryData': options.BinaryDataField, 431 } 432 433 bits = encode(msgDict) 434 if 'binary'==options.ioType: print str(bits) 435 elif 'nmeapayload'==options.ioType: 436 # FIX: figure out if this might be necessary at compile time 437 print "bitLen",len(bits) 438 bitLen=len(bits) 439 if bitLen%6!=0: 440 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 441 print "result:",binary.bitvectoais6(bits)[0] 442 443 444 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 445 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 446 else: sys.exit('ERROR: unknown ioType. Help!') 447 448 449 if options.sqlCreate: 450 sqlCreateStr(outfile,options.fieldList) 451 452 if options.printCsvfieldList: 453 # Make a csv separated list of fields that will be displayed for csv 454 if None == options.fieldList: options.fieldList = fieldList 455 import StringIO 456 buf = StringIO.StringIO() 457 for field in options.fieldList: 458 buf.write(field+',') 459 result = buf.getvalue() 460 if result[-1] == ',': print result[:-1] 461 else: print result 462 463 if options.doDecode: 464 for msg in args: 465 bv = None 466 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 467 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 468 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 469 else: sys.exit('ERROR: unknown ioType. Help!') 470 471 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 472