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-16 $'.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  @todo: FIX: put in a description of the message here with fields and types. 
 34  ''' 
 35   
 36  import sys 
 37  from decimal import Decimal 
 38  from BitVector import BitVector 
 39   
 40  import binary, aisstring 
 41   
 42  # FIX: check to see if these will be needed 
 43  TrueBV  = BitVector(bitstring="1") 
 44  "Why always rebuild the True bit?  This should speed things up a bunch" 
 45  FalseBV = BitVector(bitstring="0") 
 46  "Why always rebuild the False bit?  This should speed things up a bunch" 
 47   
 48   
 49  fieldList = ( 
 50          'MessageID', 
 51          'RepeatIndicator', 
 52          'UserID', 
 53          'Spare', 
 54          'BinaryData', 
 55  ) 
 56   
 57  fieldListPostgres = ( 
 58          'MessageID', 
 59          'RepeatIndicator', 
 60          'UserID', 
 61          'Spare', 
 62          'BinaryData', 
 63  ) 
 64   
 65  toPgFields = { 
 66  } 
 67  ''' 
 68  Go to the Postgis field names from the straight field name 
 69  ''' 
 70   
 71  fromPgFields = { 
 72  } 
 73  ''' 
 74  Go from the Postgis field names to the straight field name 
 75  ''' 
 76   
 77  pgTypes = { 
 78  } 
 79  ''' 
 80  Lookup table for each postgis field name to get its type. 
 81  ''' 
 82   
83 -def encode(params, validate=False):
84 '''Create a bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast. 85 86 Fields in params: 87 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 88 - RepeatIndicator(uint): Indicated how many times a message has been repeated 89 - UserID(uint): Unique ship identification number (MMSI) 90 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 91 - BinaryData(binary): Bits for a binary broadcast message 92 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 93 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 94 @rtype: BitVector 95 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 96 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 97 ''' 98 99 bvList = [] 100 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6)) 101 if 'RepeatIndicator' in params: 102 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 103 else: 104 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 105 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 106 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 107 bvList.append(params['BinaryData']) 108 109 return binary.joinBV(bvList)
110
111 -def decode(bv, validate=False):
112 '''Unpack a bin_broadcast message 113 114 Fields in params: 115 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 116 - RepeatIndicator(uint): Indicated how many times a message has been repeated 117 - UserID(uint): Unique ship identification number (MMSI) 118 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 119 - BinaryData(binary): Bits for a binary broadcast message 120 @type bv: BitVector 121 @param bv: Bits defining a message 122 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 123 @rtype: dict 124 @return: params 125 ''' 126 127 #Would be nice to check the bit count here.. 128 #if validate: 129 # assert (len(bv)==FIX: SOME NUMBER) 130 r = {} 131 r['MessageID']=8 132 r['RepeatIndicator']=int(bv[6:8]) 133 r['UserID']=int(bv[8:38]) 134 r['Spare']=0 135 r['BinaryData']=bv[40:] 136 return r
137
138 -def decodeMessageID(bv, validate=False):
139 return 8
140
141 -def decodeRepeatIndicator(bv, validate=False):
142 return int(bv[6:8])
143
144 -def decodeUserID(bv, validate=False):
145 return int(bv[8:38])
146
147 -def decodeSpare(bv, validate=False):
148 return 0
149
150 -def decodeBinaryData(bv, validate=False):
151 return bv[40:]
152 153
154 -def printHtml(params, out=sys.stdout):
155 out.write("<h3>bin_broadcast<h3>\n") 156 out.write("<table border=\"1\">\n") 157 out.write("<tr bgcolor=\"orange\">\n") 158 out.write("<th align=\"left\">Field Name</th>\n") 159 out.write("<th align=\"left\">Type</th>\n") 160 out.write("<th align=\"left\">Value</th>\n") 161 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 162 out.write("<th align=\"left\">Units</th>\n") 163 out.write("\n") 164 out.write("<tr>\n") 165 out.write("<td>MessageID</td>\n") 166 out.write("<td>uint</td>\n") 167 if 'MessageID' in params: 168 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 169 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 170 out.write("</tr>\n") 171 out.write("\n") 172 out.write("<tr>\n") 173 out.write("<td>RepeatIndicator</td>\n") 174 out.write("<td>uint</td>\n") 175 if 'RepeatIndicator' in params: 176 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 177 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 178 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 179 else: 180 out.write("<td><i>Missing LUT entry</i></td>") 181 out.write("</tr>\n") 182 out.write("\n") 183 out.write("<tr>\n") 184 out.write("<td>UserID</td>\n") 185 out.write("<td>uint</td>\n") 186 if 'UserID' in params: 187 out.write(" <td>"+str(params['UserID'])+"</td>\n") 188 out.write(" <td>"+str(params['UserID'])+"</td>\n") 189 out.write("</tr>\n") 190 out.write("\n") 191 out.write("<tr>\n") 192 out.write("<td>Spare</td>\n") 193 out.write("<td>uint</td>\n") 194 if 'Spare' in params: 195 out.write(" <td>"+str(params['Spare'])+"</td>\n") 196 out.write(" <td>"+str(params['Spare'])+"</td>\n") 197 out.write("</tr>\n") 198 out.write("\n") 199 out.write("<tr>\n") 200 out.write("<td>BinaryData</td>\n") 201 out.write("<td>binary</td>\n") 202 if 'BinaryData' in params: 203 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 204 out.write(" <td>"+str(params['BinaryData'])+"</td>\n") 205 out.write("</tr>\n") 206 out.write("</table>\n")
207
208 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
209 '''Print a BinaryData message to stdout. 210 211 Fields in params: 212 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8") 213 - RepeatIndicator(uint): Indicated how many times a message has been repeated 214 - UserID(uint): Unique ship identification number (MMSI) 215 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0") 216 - BinaryData(binary): Bits for a binary broadcast message 217 @param params: Dictionary of field names/values. 218 @param out: File like object to write to 219 @rtype: stdout 220 @return: text to out 221 ''' 222 223 if 'std'==format: 224 out.write("BinaryData:\n") 225 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 226 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 227 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 228 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 229 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n") 230 elif 'csv'==format: 231 if None == options.fieldList: 232 options.fieldList = fieldList 233 needComma = False; 234 for field in fieldList: 235 if needComma: out.write(',') 236 needComma = True 237 if field in params: 238 out.write(str(params[field])) 239 # else: leave it empty 240 out.write("\n") 241 elif 'html'==format: 242 printHtml(params,out) 243 elif 'sql'==format: 244 sqlInsertStr(params,out,dbType=dbType) 245 else: 246 print "ERROR: unknown format:",format 247 assert False 248 249 return # Nothing to return
250 251 RepeatIndicatorEncodeLut = { 252 'default':'0', 253 'do not repeat any more':'3', 254 } #RepeatIndicatorEncodeLut 255 256 RepeatIndicatorDecodeLut = { 257 '0':'default', 258 '3':'do not repeat any more', 259 } # RepeatIndicatorEncodeLut 260 261 ###################################################################### 262 # SQL SUPPORT 263 ###################################################################### 264
265 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None 266 ,addCoastGuardFields=True 267 ,dbType='postgres' 268 ):
269 ''' 270 Return the SQL CREATE command for this message type 271 @param outfile: file like object to print to. 272 @param fields: which fields to put in the create. Defaults to all. 273 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 274 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 275 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 276 @type addCoastGuardFields: bool 277 @return: sql create string 278 @rtype: str 279 280 @see: sqlCreate 281 ''' 282 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
283
284 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
285 ''' 286 Return the sqlhelp object to create the table. 287 288 @param fields: which fields to put in the create. Defaults to all. 289 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 290 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 291 @type addCoastGuardFields: bool 292 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 293 @return: An object that can be used to generate a return 294 @rtype: sqlhelp.create 295 ''' 296 if None == fields: fields = fieldList 297 import sqlhelp 298 c = sqlhelp.create('bin_broadcast',dbType=dbType) 299 c.addPrimaryKey() 300 if 'MessageID' in fields: c.addInt ('MessageID') 301 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 302 if 'UserID' in fields: c.addInt ('UserID') 303 if 'Spare' in fields: c.addInt ('Spare') 304 if 'BinaryData' in fields: c.addBitVarying('BinaryData',1024) 305 306 if addCoastGuardFields: 307 # c.addInt('cg_rssi') # Relative signal strength indicator 308 # c.addInt('cg_d') # dBm receive strength 309 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 310 # c.addInt('cg_S') # Slot received in 311 # c.addVarChar('cg_x',10) # Idonno 312 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 313 c.addInt('cg_sec') # UTC seconds since the epoch 314 315 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 316 317 return c
318
319 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
320 ''' 321 Return the SQL INSERT command for this message type 322 @param params: dictionary of values keyed by field name 323 @param outfile: file like object to print to. 324 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 325 @return: sql create string 326 @rtype: str 327 328 @see: sqlCreate 329 ''' 330 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
331 332
333 -def sqlInsert(params,extraParams=None,dbType='postgres'):
334 ''' 335 Give the SQL INSERT statement 336 @param params: dict keyed by field name of values 337 @param extraParams: any extra fields that you have created beyond the normal ais message fields 338 @rtype: sqlhelp.insert 339 @return: insert class instance 340 @todo: allow optional type checking of params? 341 @warning: this will take invalid keys happily and do what??? 342 ''' 343 import sqlhelp 344 i = sqlhelp.insert('bin_broadcast',dbType=dbType) 345 346 if dbType=='postgres': 347 finished = [] 348 for key in params: 349 if key in finished: 350 #print 'already did key',key 351 continue 352 353 if key not in toPgFields and key not in fromPgFields: 354 if type(params[key])==Decimal: i.add(key,float(params[key])) 355 else: i.add(key,params[key]) 356 else: 357 if key in fromPgFields: 358 val = params[key] 359 # Had better be a WKT type like POINT(-88.1 30.321) 360 i.addPostGIS(key,val) 361 finished.append(key) 362 else: 363 # Need to construct the type. 364 pgName = toPgFields[key] 365 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 366 valStr=pgTypes[pgName]+'(' 367 vals = [] 368 for nonPgKey in fromPgFields[pgName]: 369 vals.append(str(params[nonPgKey])) 370 finished.append(nonPgKey) 371 valStr+=' '.join(vals)+')' 372 i.addPostGIS(pgName,valStr) 373 else: 374 for key in params: 375 if type(params[key])==Decimal: i.add(key,float(params[key])) 376 else: i.add(key,params[key]) 377 378 if None != extraParams: 379 for key in extraParams: 380 i.add(key,extraParams[key]) 381 382 return i
383 384 385 ###################################################################### 386 # UNIT TESTING 387 ###################################################################### 388 import unittest
389 -def testParams():
390 '''Return a params file base on the testvalue tags. 391 @rtype: dict 392 @return: params based on testvalue tags 393 ''' 394 params = {} 395 params['MessageID'] = 8 396 params['RepeatIndicator'] = 1 397 params['UserID'] = 1193046 398 params['Spare'] = 0 399 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110') 400 401 return params
402
403 -class Testbin_broadcast(unittest.TestCase):
404 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
405 - def testEncodeDecode(self):
406 407 params = testParams() 408 bits = encode(params) 409 r = decode(bits) 410 411 # Check that each parameter came through ok. 412 self.failUnlessEqual(r['MessageID'],params['MessageID']) 413 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 414 self.failUnlessEqual(r['UserID'],params['UserID']) 415 self.failUnlessEqual(r['Spare'],params['Spare']) 416 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
417
418 -def addMsgOptions(parser):
419 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 420 help='decode a "bin_broadcast" AIS message') 421 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 422 help='encode a "bin_broadcast" AIS message') 423 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 424 ,help='Field parameter value [default: %default]') 425 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 426 ,help='Field parameter value [default: %default]') 427 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string' 428 ,help='Field parameter value [default: %default]')
429 430 ############################################################ 431 if __name__=='__main__': 432 433 from optparse import OptionParser 434 parser = OptionParser(usage="%prog [options]", 435 version="%prog "+__version__) 436 437 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 438 help='run the documentation tests') 439 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 440 help='run the unit tests') 441 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 442 help='Make the test output verbose') 443 444 # FIX: remove nmea from binary messages. No way to build the whole packet? 445 # FIX: or build the surrounding msg 8 for a broadcast? 446 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 447 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 448 ,default='nmeapayload' 449 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 450 451 452 outputChoices = ('std','html','csv','sql' ) 453 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 454 ,default='std' 455 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 456 457 parser.add_option('-o','--output',dest='outputFileName',default=None, 458 help='Name of the python file to write [default: stdout]') 459 460 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 461 choices=fieldList, 462 help='Which fields to include in the output. Currently only for csv output [default: all]') 463 464 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 465 help='Print the field name for csv') 466 467 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 468 help='Print out an sql create command for the table.') 469 470 dbChoices = ('sqlite','postgres') 471 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 472 ,choices=dbChoices,type='choice' 473 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 474 475 addMsgOptions(parser) 476 477 (options,args) = parser.parse_args() 478 success=True 479 480 if options.doctest: 481 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 482 sys.argv= [sys.argv[0]] 483 if options.verbose: sys.argv.append('-v') 484 import doctest 485 numfail,numtests=doctest.testmod() 486 if numfail==0: print 'ok' 487 else: 488 print 'FAILED' 489 success=False 490 491 if not success: sys.exit('Something Failed') 492 del success # Hide success from epydoc 493 494 if options.unittest: 495 sys.argv = [sys.argv[0]] 496 if options.verbose: sys.argv.append('-v') 497 unittest.main() 498 499 outfile = sys.stdout 500 if None!=options.outputFileName: 501 outfile = file(options.outputFileName,'w') 502 503 504 if options.doEncode: 505 # First make sure all non required options are specified 506 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 507 if None==options.UserIDField: parser.error("missing value for UserIDField") 508 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField") 509 msgDict={ 510 'MessageID': '8', 511 'RepeatIndicator': options.RepeatIndicatorField, 512 'UserID': options.UserIDField, 513 'Spare': '0', 514 'BinaryData': options.BinaryDataField, 515 } 516 517 bits = encode(msgDict) 518 if 'binary'==options.ioType: print str(bits) 519 elif 'nmeapayload'==options.ioType: 520 # FIX: figure out if this might be necessary at compile time 521 print "bitLen",len(bits) 522 bitLen=len(bits) 523 if bitLen%6!=0: 524 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 525 print "result:",binary.bitvectoais6(bits)[0] 526 527 528 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 529 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 530 else: sys.exit('ERROR: unknown ioType. Help!') 531 532 533 if options.sqlCreate: 534 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 535 536 if options.printCsvfieldList: 537 # Make a csv separated list of fields that will be displayed for csv 538 if None == options.fieldList: options.fieldList = fieldList 539 import StringIO 540 buf = StringIO.StringIO() 541 for field in options.fieldList: 542 buf.write(field+',') 543 result = buf.getvalue() 544 if result[-1] == ',': print result[:-1] 545 else: print result 546 547 if options.doDecode: 548 for msg in args: 549 bv = None 550 551 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 552 # Found nmea 553 # FIX: do checksum 554 bv = binary.ais6tobitvec(msg.split(',')[5]) 555 else: # either binary or nmeapayload... expect mostly nmeapayloads 556 # assumes that an all 0 and 1 string can not be a nmeapayload 557 binaryMsg=True 558 for c in msg: 559 if c not in ('0','1'): 560 binaryMsg=False 561 break 562 if binaryMsg: 563 bv = BitVector(bitstring=msg) 564 else: # nmeapayload 565 bv = binary.ais6tobitvec(msg) 566 567 printFields(decode(bv) 568 ,out=outfile 569 ,format=options.outputType 570 ,fieldList=options.fieldList 571 ,dbType=options.dbType 572 ) 573