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-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          '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 elif 'sql'==format: 217 sqlInsertStr(params,out) 218 else: 219 print "ERROR: unknown format:",format 220 assert False 221 222 return # Nothing to return
223 224 RepeatIndicatorEncodeLut = { 225 'default':'0', 226 'do not repeat any more':'3', 227 } #RepeatIndicatorEncodeLut 228 229 RepeatIndicatorDecodeLut = { 230 '0':'default', 231 '3':'do not repeat any more', 232 } # RepeatIndicatorEncodeLut 233 234 ###################################################################### 235 # SQL SUPPORT 236 ###################################################################### 237
238 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None, addCoastGuardFields=True):
239 ''' 240 Return the SQL CREATE command for this message type 241 @param outfile: file like object to print to. 242 @param fields: which fields to put in the create. Defaults to all. 243 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 244 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 245 @type addCoastGuardFields: bool 246 @return: sql create string 247 @rtype: str 248 249 @see: sqlCreate 250 ''' 251 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields)))
252
253 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True):
254 ''' 255 Return the sqlhelp object to create the table. 256 257 @param fields: which fields to put in the create. Defaults to all. 258 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 259 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 260 @type addCoastGuardFields: bool 261 @return: An object that can be used to generate a return 262 @rtype: sqlhelp.create 263 ''' 264 if None == fields: fields = fieldList 265 import sqlhelp 266 c = sqlhelp.create('bin_broadcast') 267 if 'MessageID' in fields: c.addInt ('MessageID') 268 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 269 if 'UserID' in fields: c.addInt ('UserID') 270 if 'Spare' in fields: c.addInt ('Spare') 271 if 'BinaryData' in fields: c.addBitVarying('BinaryData',1024) 272 273 if addCoastGuardFields: 274 # c.addInt('cg_rssi') # Relative signal strength indicator 275 # c.addInt('cg_d') # dBm receive strength 276 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 277 # c.addInt('cg_S') # Slot received in 278 # c.addVarChar('cg_x',10) # Idonno 279 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 280 c.addInt('cg_timestamp') # UTC seconds since the epoch 281 # FIX: maybe an actually time field? 282 283 return c
284
285 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
286 ''' 287 Return the SQL CREATE command for this message type 288 @param params: dictionary of values keyed by field name 289 @param outfile: file like object to print to. 290 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 291 @return: sql create string 292 @rtype: str 293 294 @see: sqlCreate 295 ''' 296 outfile.write(str(sqlInsert(params,extraParams)))
297 298
299 -def sqlInsert(params,extraParams=None):
300 ''' 301 Give the SQL insert statement 302 @param params: dict keyed by field name of values 303 @param extraParams: any extra fields that you have created beyond the normal ais message fields 304 @rtype: sqlhelp.insert 305 @return: insert class instance 306 @todo: allow optional type checking of params? 307 @warning: this will take invalid keys happily and do what??? 308 ''' 309 import sqlhelp 310 i = sqlhelp.insert('bin_broadcast') 311 for key in params: 312 #i.add(key,params[key]) 313 if type(params[key])==Decimal: i.add(key,float(params[key])) 314 else: i.add(key,params[key]) 315 if None != extraParams: 316 for key in extraParams: 317 i.add(key,extraParams[key]) 318 319 return i
320 321 322 ###################################################################### 323 # UNIT TESTING 324 ###################################################################### 325 import unittest
326 -def testParams():
327 '''Return a params file base on the testvalue tags. 328 @rtype: dict 329 @return: params based on testvalue tags 330 ''' 331 params = {} 332 params['MessageID'] = 8 333 params['RepeatIndicator'] = 1 334 params['UserID'] = 1193046 335 params['Spare'] = 0 336 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110') 337 338 return params
339
340 -class Testbin_broadcast(unittest.TestCase):
341 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
342 - def testEncodeDecode(self):
343 344 params = testParams() 345 bits = encode(params) 346 r = decode(bits) 347 348 # Check that each parameter came through ok. 349 self.failUnlessEqual(r['MessageID'],params['MessageID']) 350 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 351 self.failUnlessEqual(r['UserID'],params['UserID']) 352 self.failUnlessEqual(r['Spare'],params['Spare']) 353 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
354
355 -def addMsgOptions(parser):
356 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 357 help='decode a "bin_broadcast" AIS message') 358 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 359 help='encode a "bin_broadcast" AIS message') 360 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 361 ,help='Field parameter value [default: %default]') 362 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 363 ,help='Field parameter value [default: %default]') 364 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 365 ,help='Field parameter value [default: %default]')
366 367 ############################################################ 368 if __name__=='__main__': 369 370 from optparse import OptionParser 371 parser = OptionParser(usage="%prog [options]", 372 version="%prog "+__version__) 373 374 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 375 help='run the documentation tests') 376 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 377 help='run the unit tests') 378 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 379 help='Make the test output verbose') 380 381 # FIX: remove nmea from binary messages. No way to build the whole packet? 382 # FIX: or build the surrounding msg 8 for a broadcast? 383 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 384 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 385 ,default='nmeapayload' 386 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 387 388 389 outputChoices = ('std','html','csv','sql' ) 390 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 391 ,default='std' 392 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 393 394 parser.add_option('-o','--output',dest='outputFileName',default=None, 395 help='Name of the python file to write [default: stdout]') 396 397 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 398 choices=fieldList, 399 help='Which fields to include in the output. Currently only for csv output [default: all]') 400 401 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 402 help='Print the field name for csv') 403 404 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 405 help='Print out an sql create command for the table.') 406 407 addMsgOptions(parser) 408 409 (options,args) = parser.parse_args() 410 success=True 411 412 if options.doctest: 413 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 414 sys.argv= [sys.argv[0]] 415 if options.verbose: sys.argv.append('-v') 416 import doctest 417 numfail,numtests=doctest.testmod() 418 if numfail==0: print 'ok' 419 else: 420 print 'FAILED' 421 success=False 422 423 if not success: sys.exit('Something Failed') 424 del success # Hide success from epydoc 425 426 if options.unittest: 427 sys.argv = [sys.argv[0]] 428 if options.verbose: sys.argv.append('-v') 429 unittest.main() 430 431 outfile = sys.stdout 432 if None!=options.outputFileName: 433 outfile = file(options.outputFileName,'w') 434 435 436 if options.doEncode: 437 # First make sure all non required options are specified 438 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 439 if None==options.UserIDField: parser.error("missing value for UserIDField") 440 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 441 msgDict={ 442 'MessageID': '8', 443 'RepeatIndicator': options.RepeatIndicatorField, 444 'UserID': options.UserIDField, 445 'Spare': '0', 446 'BinaryData': options.BinaryDataField, 447 } 448 449 bits = encode(msgDict) 450 if 'binary'==options.ioType: print str(bits) 451 elif 'nmeapayload'==options.ioType: 452 # FIX: figure out if this might be necessary at compile time 453 print "bitLen",len(bits) 454 bitLen=len(bits) 455 if bitLen%6!=0: 456 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 457 print "result:",binary.bitvectoais6(bits)[0] 458 459 460 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 461 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 462 else: sys.exit('ERROR: unknown ioType. Help!') 463 464 465 if options.sqlCreate: 466 sqlCreateStr(outfile,options.fieldList) 467 468 if options.printCsvfieldList: 469 # Make a csv separated list of fields that will be displayed for csv 470 if None == options.fieldList: options.fieldList = fieldList 471 import StringIO 472 buf = StringIO.StringIO() 473 for field in options.fieldList: 474 buf.write(field+',') 475 result = buf.getvalue() 476 if result[-1] == ',': print result[:-1] 477 else: print result 478 479 if options.doDecode: 480 for msg in args: 481 bv = None 482 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 483 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 484 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 485 else: sys.exit('ERROR: unknown ioType. Help!') 486 487 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 488