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

Source Code for Module ais.sls_lockschedule

  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_lockorder binary message payload to pack into an AIS Msg sls_lockorder. 50 51 Fields in params: 52 - vessel(aisstr6): Vessel Name 53 - direction(bool): Up bound/Down bound 54 - ETA_month(uint): Estimated time of arrival month 1..12 55 - ETA_day(uint): Estimated time of arrival day of the month 1..31 56 - ETA_hour(uint): Estimated time of arrival UTC hours 0..23 57 - ETA_min(uint): Estimated time of arrival minutes 58 - reserved(uint): Reserved bits for future use (field automatically set to "0") 59 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 60 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 61 @rtype: BitVector 62 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 63 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 64 ''' 65 66 bvList = [] 67 if 'vessel' in params: 68 bvList.append(aisstring.encode(params['vessel'],90)) 69 else: 70 bvList.append(aisstring.encode('@@@@@@@@@@@@@@@',90)) 71 if params["direction"]: bvList.append(TrueBV) 72 else: bvList.append(FalseBV) 73 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ETA_month']),4)) 74 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ETA_day']),5)) 75 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ETA_hour']),5)) 76 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ETA_min']),6)) 77 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),19)) 78 79 return binary.joinBV(bvList)
80
81 -def decode(bv, validate=False):
82 '''Unpack a sls_lockorder message 83 84 Fields in params: 85 - vessel(aisstr6): Vessel Name 86 - direction(bool): Up bound/Down bound 87 - ETA_month(uint): Estimated time of arrival month 1..12 88 - ETA_day(uint): Estimated time of arrival day of the month 1..31 89 - ETA_hour(uint): Estimated time of arrival UTC hours 0..23 90 - ETA_min(uint): Estimated time of arrival minutes 91 - reserved(uint): Reserved bits for future use (field automatically set to "0") 92 @type bv: BitVector 93 @param bv: Bits defining a message 94 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 95 @rtype: dict 96 @return: params 97 ''' 98 99 #Would be nice to check the bit count here.. 100 #if validate: 101 # assert (len(bv)==FIX: SOME NUMBER) 102 r = {} 103 r['vessel']=aisstring.decode(bv[0:90]) 104 r['direction']=bool(int(bv[90:91])) 105 r['ETA_month']=int(bv[91:95]) 106 r['ETA_day']=int(bv[95:100]) 107 r['ETA_hour']=int(bv[100:105]) 108 r['ETA_min']=int(bv[105:111]) 109 r['reserved']=0 110 return r
111
112 -def decodevessel(bv, validate=False):
113 return aisstring.decode(bv[0:90])
114
115 -def decodedirection(bv, validate=False):
116 return bool(int(bv[90:91]))
117
118 -def decodeETA_month(bv, validate=False):
119 return int(bv[91:95])
120
121 -def decodeETA_day(bv, validate=False):
122 return int(bv[95:100])
123
124 -def decodeETA_hour(bv, validate=False):
125 return int(bv[100:105])
126
127 -def decodeETA_min(bv, validate=False):
128 return int(bv[105:111])
129
130 -def decodereserved(bv, validate=False):
131 return 0
132 133
134 -def printHtml(params, out=sys.stdout):
135 out.write("<h3>sls_lockorder<h3>\n") 136 out.write("<table border=\"1\">\n") 137 out.write("<tr bgcolor=\"orange\">\n") 138 out.write("<th align=\"left\">Field Name</th>\n") 139 out.write("<th align=\"left\">Type</th>\n") 140 out.write("<th align=\"left\">Value</th>\n") 141 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 142 out.write("<th align=\"left\">Units</th>\n") 143 out.write("\n") 144 out.write("<tr>\n") 145 out.write("<td>vessel</td>\n") 146 out.write("<td>aisstr6</td>\n") 147 if 'vessel' in params: 148 out.write(" <td>"+str(params['vessel'])+"</td>\n") 149 out.write(" <td>"+str(params['vessel'])+"</td>\n") 150 out.write("</tr>\n") 151 out.write("\n") 152 out.write("<tr>\n") 153 out.write("<td>direction</td>\n") 154 out.write("<td>bool</td>\n") 155 if 'direction' in params: 156 out.write(" <td>"+str(params['direction'])+"</td>\n") 157 if str(params['direction']) in directionDecodeLut: 158 out.write("<td>"+directionDecodeLut[str(params['direction'])]+"</td>") 159 else: 160 out.write("<td><i>Missing LUT entry</i></td>") 161 out.write("</tr>\n") 162 out.write("\n") 163 out.write("<tr>\n") 164 out.write("<td>ETA_month</td>\n") 165 out.write("<td>uint</td>\n") 166 if 'ETA_month' in params: 167 out.write(" <td>"+str(params['ETA_month'])+"</td>\n") 168 out.write(" <td>"+str(params['ETA_month'])+"</td>\n") 169 out.write("</tr>\n") 170 out.write("\n") 171 out.write("<tr>\n") 172 out.write("<td>ETA_day</td>\n") 173 out.write("<td>uint</td>\n") 174 if 'ETA_day' in params: 175 out.write(" <td>"+str(params['ETA_day'])+"</td>\n") 176 out.write(" <td>"+str(params['ETA_day'])+"</td>\n") 177 out.write("</tr>\n") 178 out.write("\n") 179 out.write("<tr>\n") 180 out.write("<td>ETA_hour</td>\n") 181 out.write("<td>uint</td>\n") 182 if 'ETA_hour' in params: 183 out.write(" <td>"+str(params['ETA_hour'])+"</td>\n") 184 out.write(" <td>"+str(params['ETA_hour'])+"</td>\n") 185 out.write("</tr>\n") 186 out.write("\n") 187 out.write("<tr>\n") 188 out.write("<td>ETA_min</td>\n") 189 out.write("<td>uint</td>\n") 190 if 'ETA_min' in params: 191 out.write(" <td>"+str(params['ETA_min'])+"</td>\n") 192 out.write(" <td>"+str(params['ETA_min'])+"</td>\n") 193 out.write("</tr>\n") 194 out.write("\n") 195 out.write("<tr>\n") 196 out.write("<td>reserved</td>\n") 197 out.write("<td>uint</td>\n") 198 if 'reserved' in params: 199 out.write(" <td>"+str(params['reserved'])+"</td>\n") 200 out.write(" <td>"+str(params['reserved'])+"</td>\n") 201 out.write("</tr>\n") 202 out.write("</table>\n")
203 -def printFields(params, out=sys.stdout, format='std'):
204 '''Print a reserved message to stdout. 205 206 Fields in params: 207 - vessel(aisstr6): Vessel Name 208 - direction(bool): Up bound/Down bound 209 - ETA_month(uint): Estimated time of arrival month 1..12 210 - ETA_day(uint): Estimated time of arrival day of the month 1..31 211 - ETA_hour(uint): Estimated time of arrival UTC hours 0..23 212 - ETA_min(uint): Estimated time of arrival minutes 213 - reserved(uint): Reserved bits for future use (field automatically set to "0") 214 @param params: Dictionary of field names/values. 215 @param out: File like object to write to 216 @rtype: stdout 217 @return: text to out 218 ''' 219 220 if 'std'==format: 221 out.write("reserved:\n") 222 if 'vessel' in params: out.write(" vessel: "+str(params['vessel'])+"\n") 223 if 'direction' in params: out.write(" direction: "+str(params['direction'])+"\n") 224 if 'ETA_month' in params: out.write(" ETA_month: "+str(params['ETA_month'])+"\n") 225 if 'ETA_day' in params: out.write(" ETA_day: "+str(params['ETA_day'])+"\n") 226 if 'ETA_hour' in params: out.write(" ETA_hour: "+str(params['ETA_hour'])+"\n") 227 if 'ETA_min' in params: out.write(" ETA_min: "+str(params['ETA_min'])+"\n") 228 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 229 elif 'html'==format: 230 printHtml(params,out) 231 else: 232 print "ERROR: unknown format:",format 233 assert False 234 235 return # Nothing to return
236 237 directionEncodeLut = { 238 'Down bound':'0', 239 'Up bound':'1', 240 } #directionEncodeLut 241 242 directionDecodeLut = { 243 '0':'Down bound', 244 '1':'Up bound', 245 } # directionEncodeLut 246 247 248 249 ###################################################################### 250 # UNIT TESTING 251 ###################################################################### 252 import unittest
253 -def testParams():
254 '''Return a params file base on the testvalue tags. 255 @rtype: dict 256 @return: params based on testvalue tags 257 ''' 258 params = {} 259 params['vessel'] = 'ICEBERG@@@@@@@@' 260 params['direction'] = True 261 params['ETA_month'] = 2 262 params['ETA_day'] = 28 263 params['ETA_hour'] = 23 264 params['ETA_min'] = 45 265 params['reserved'] = 0 266 267 return params
268
269 -class Testsls_lockorder(unittest.TestCase):
270 '''Use testvalue tag text from each type to build test case the sls_lockorder message'''
271 - def testEncodeDecode(self):
272 273 params = testParams() 274 bits = encode(params) 275 r = decode(bits) 276 277 # Check that each parameter came through ok. 278 self.failUnlessEqual(r['vessel'],params['vessel']) 279 self.failUnlessEqual(r['direction'],params['direction']) 280 self.failUnlessEqual(r['ETA_month'],params['ETA_month']) 281 self.failUnlessEqual(r['ETA_day'],params['ETA_day']) 282 self.failUnlessEqual(r['ETA_hour'],params['ETA_hour']) 283 self.failUnlessEqual(r['ETA_min'],params['ETA_min']) 284 self.failUnlessEqual(r['reserved'],params['reserved'])
285
286 -def addMsgOptions(parser):
287 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 288 help='decode a "sls_lockorder" AIS message') 289 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 290 help='encode a "sls_lockorder" AIS message') 291 parser.add_option('--vessel-field', dest='vesselField',default='@@@@@@@@@@@@@@@',metavar='aisstr6',type='string' 292 ,help='Field parameter value [default: %default]') 293 parser.add_option('--direction-field', dest='directionField',metavar='bool',type='int' 294 ,help='Field parameter value [default: %default]') 295 parser.add_option('--ETA_month-field', dest='ETA_monthField',metavar='uint',type='int' 296 ,help='Field parameter value [default: %default]') 297 parser.add_option('--ETA_day-field', dest='ETA_dayField',metavar='uint',type='int' 298 ,help='Field parameter value [default: %default]') 299 parser.add_option('--ETA_hour-field', dest='ETA_hourField',metavar='uint',type='int' 300 ,help='Field parameter value [default: %default]') 301 parser.add_option('--ETA_min-field', dest='ETA_minField',metavar='uint',type='int' 302 ,help='Field parameter value [default: %default]')
303 304 ############################################################ 305 if __name__=='__main__': 306 307 from optparse import OptionParser 308 parser = OptionParser(usage="%prog [options]", 309 version="%prog "+__version__) 310 311 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 312 help='run the documentation tests') 313 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 314 help='run the unit tests') 315 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 316 help='Make the test output verbose') 317 318 # FIX: remove nmea from binary messages. No way to build the whole packet? 319 # FIX: or build the surrounding msg 8 for a broadcast? 320 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 321 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 322 ,default='nmeapayload' 323 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 324 325 326 outputChoices = ('std','html','xml' ) 327 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 328 ,default='std' 329 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 330 331 parser.add_option('-o','--output',dest='outputFileName',default=None, 332 help='Name of the python file to write [default: stdout]') 333 334 addMsgOptions(parser) 335 336 (options,args) = parser.parse_args() 337 success=True 338 339 if options.doctest: 340 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 341 sys.argv= [sys.argv[0]] 342 if options.verbose: sys.argv.append('-v') 343 import doctest 344 numfail,numtests=doctest.testmod() 345 if numfail==0: print 'ok' 346 else: 347 print 'FAILED' 348 success=False 349 350 if not success: sys.exit('Something Failed') 351 del success # Hide success from epydoc 352 353 if options.unittest: 354 sys.argv = [sys.argv[0]] 355 if options.verbose: sys.argv.append('-v') 356 unittest.main() 357 358 outfile = sys.stdout 359 if None!=options.outputFileName: 360 outfile = file(options.outputFileName,'w') 361 362 363 if options.doEncode: 364 # First make sure all non required options are specified 365 if None==options.vesselField: parser.error("missing value for vesselField") 366 if None==options.directionField: parser.error("missing value for directionField") 367 if None==options.ETA_monthField: parser.error("missing value for ETA_monthField") 368 if None==options.ETA_dayField: parser.error("missing value for ETA_dayField") 369 if None==options.ETA_hourField: parser.error("missing value for ETA_hourField") 370 if None==options.ETA_minField: parser.error("missing value for ETA_minField") 371 msgDict={ 372 'vessel': options.vesselField, 373 'direction': options.directionField, 374 'ETA_month': options.ETA_monthField, 375 'ETA_day': options.ETA_dayField, 376 'ETA_hour': options.ETA_hourField, 377 'ETA_min': options.ETA_minField, 378 'reserved': '0', 379 } 380 381 bits = encode(msgDict) 382 if 'binary'==options.ioType: print str(bits) 383 elif 'nmeapayload'==options.ioType: 384 # FIX: figure out if this might be necessary at compile time 385 print "bitLen",len(bits) 386 bitLen=len(bits) 387 if bitLen%6!=0: 388 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 389 print "result:",binary.bitvectoais6(bits)[0] 390 391 392 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 393 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 394 else: sys.exit('ERROR: unknown ioType. Help!') 395 396 if options.doDecode: 397 for msg in args: 398 bv = None 399 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 400 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 401 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 402 else: sys.exit('ERROR: unknown ioType. Help!') 403 404 printFields(decode(bv),out=outfile,format=options.outputType) 405