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

Source Code for Module ais.ais_msg_14

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