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

Source Code for Module ais.sls_wind

  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          'time_month', 
 50          'time_day', 
 51          'time_hour', 
 52          'time_min', 
 53          'stationid', 
 54          'pos_longitude', 
 55          'pos_latitude', 
 56          'speed', 
 57          'gust', 
 58          'direction', 
 59          'reserved', 
 60  ] 
 61   
62 -def encode(params, validate=False):
63 '''Create a sls_wind binary message payload to pack into an AIS Msg sls_wind. 64 65 Fields in params: 66 - time_month(uint): Time tag of measurement month 1..12 67 - time_day(uint): Time tag of measurement day of the month 1..31 68 - time_hour(uint): Time tag of measurement UTC hours 0..23 69 - time_min(uint): Time tag of measurement minutes 70 - stationid(aisstr6): Character identifier of the station 71 - pos_longitude(decimal): Location of measurement East West location 72 - pos_latitude(decimal): Location of measurement North South location 73 - speed(udecimal): Average wind speed 74 - gust(udecimal): Wind gust 75 - direction(uint): Wind direction 76 - reserved(uint): Reserved bits for future use (field automatically set to "0") 77 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 78 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 79 @rtype: BitVector 80 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 81 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 82 ''' 83 84 bvList = [] 85 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4)) 86 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5)) 87 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5)) 88 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6)) 89 if 'stationid' in params: 90 bvList.append(aisstring.encode(params['stationid'],42)) 91 else: 92 bvList.append(aisstring.encode('@@@@@@@',42)) 93 if 'pos_longitude' in params: 94 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25)) 95 else: 96 bvList.append(binary.bvFromSignedInt(10860000,25)) 97 if 'pos_latitude' in params: 98 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24)) 99 else: 100 bvList.append(binary.bvFromSignedInt(5460000,24)) 101 if 'speed' in params: 102 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['speed'])*Decimal('10')))),10)) 103 else: 104 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)),10)) 105 if 'gust' in params: 106 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['gust'])*Decimal('10')))),10)) 107 else: 108 bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)),10)) 109 if 'direction' in params: 110 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['direction']),9)) 111 else: 112 bvList.append(binary.setBitVectorSize(BitVector(intVal=511),9)) 113 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4)) 114 115 return binary.joinBV(bvList)
116
117 -def decode(bv, validate=False):
118 '''Unpack a sls_wind message 119 120 Fields in params: 121 - time_month(uint): Time tag of measurement month 1..12 122 - time_day(uint): Time tag of measurement day of the month 1..31 123 - time_hour(uint): Time tag of measurement UTC hours 0..23 124 - time_min(uint): Time tag of measurement minutes 125 - stationid(aisstr6): Character identifier of the station 126 - pos_longitude(decimal): Location of measurement East West location 127 - pos_latitude(decimal): Location of measurement North South location 128 - speed(udecimal): Average wind speed 129 - gust(udecimal): Wind gust 130 - direction(uint): Wind direction 131 - reserved(uint): Reserved bits for future use (field automatically set to "0") 132 @type bv: BitVector 133 @param bv: Bits defining a message 134 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 135 @rtype: dict 136 @return: params 137 ''' 138 139 #Would be nice to check the bit count here.. 140 #if validate: 141 # assert (len(bv)==FIX: SOME NUMBER) 142 r = {} 143 r['time_month']=int(bv[0:4]) 144 r['time_day']=int(bv[4:9]) 145 r['time_hour']=int(bv[9:14]) 146 r['time_min']=int(bv[14:20]) 147 r['stationid']=aisstring.decode(bv[20:62]) 148 r['pos_longitude']=Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000') 149 r['pos_latitude']=Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000') 150 r['speed']=Decimal(int(bv[111:121]))/Decimal('10') 151 r['gust']=Decimal(int(bv[121:131]))/Decimal('10') 152 r['direction']=int(bv[131:140]) 153 r['reserved']=0 154 return r
155
156 -def decodetime_month(bv, validate=False):
157 return int(bv[0:4])
158
159 -def decodetime_day(bv, validate=False):
160 return int(bv[4:9])
161
162 -def decodetime_hour(bv, validate=False):
163 return int(bv[9:14])
164
165 -def decodetime_min(bv, validate=False):
166 return int(bv[14:20])
167
168 -def decodestationid(bv, validate=False):
169 return aisstring.decode(bv[20:62])
170
171 -def decodepos_longitude(bv, validate=False):
172 return Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000')
173
174 -def decodepos_latitude(bv, validate=False):
175 return Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000')
176
177 -def decodespeed(bv, validate=False):
178 return Decimal(int(bv[111:121]))/Decimal('10')
179
180 -def decodegust(bv, validate=False):
181 return Decimal(int(bv[121:131]))/Decimal('10')
182
183 -def decodedirection(bv, validate=False):
184 return int(bv[131:140])
185
186 -def decodereserved(bv, validate=False):
187 return 0
188 189
190 -def printHtml(params, out=sys.stdout):
191 out.write("<h3>sls_wind<h3>\n") 192 out.write("<table border=\"1\">\n") 193 out.write("<tr bgcolor=\"orange\">\n") 194 out.write("<th align=\"left\">Field Name</th>\n") 195 out.write("<th align=\"left\">Type</th>\n") 196 out.write("<th align=\"left\">Value</th>\n") 197 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 198 out.write("<th align=\"left\">Units</th>\n") 199 out.write("\n") 200 out.write("<tr>\n") 201 out.write("<td>time_month</td>\n") 202 out.write("<td>uint</td>\n") 203 if 'time_month' in params: 204 out.write(" <td>"+str(params['time_month'])+"</td>\n") 205 out.write(" <td>"+str(params['time_month'])+"</td>\n") 206 out.write("</tr>\n") 207 out.write("\n") 208 out.write("<tr>\n") 209 out.write("<td>time_day</td>\n") 210 out.write("<td>uint</td>\n") 211 if 'time_day' in params: 212 out.write(" <td>"+str(params['time_day'])+"</td>\n") 213 out.write(" <td>"+str(params['time_day'])+"</td>\n") 214 out.write("</tr>\n") 215 out.write("\n") 216 out.write("<tr>\n") 217 out.write("<td>time_hour</td>\n") 218 out.write("<td>uint</td>\n") 219 if 'time_hour' in params: 220 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 221 out.write(" <td>"+str(params['time_hour'])+"</td>\n") 222 out.write("</tr>\n") 223 out.write("\n") 224 out.write("<tr>\n") 225 out.write("<td>time_min</td>\n") 226 out.write("<td>uint</td>\n") 227 if 'time_min' in params: 228 out.write(" <td>"+str(params['time_min'])+"</td>\n") 229 out.write(" <td>"+str(params['time_min'])+"</td>\n") 230 out.write("</tr>\n") 231 out.write("\n") 232 out.write("<tr>\n") 233 out.write("<td>stationid</td>\n") 234 out.write("<td>aisstr6</td>\n") 235 if 'stationid' in params: 236 out.write(" <td>"+str(params['stationid'])+"</td>\n") 237 out.write(" <td>"+str(params['stationid'])+"</td>\n") 238 out.write("</tr>\n") 239 out.write("\n") 240 out.write("<tr>\n") 241 out.write("<td>pos_longitude</td>\n") 242 out.write("<td>decimal</td>\n") 243 if 'pos_longitude' in params: 244 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 245 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n") 246 out.write("<td>degrees</td>\n") 247 out.write("</tr>\n") 248 out.write("\n") 249 out.write("<tr>\n") 250 out.write("<td>pos_latitude</td>\n") 251 out.write("<td>decimal</td>\n") 252 if 'pos_latitude' in params: 253 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n") 254 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n") 255 out.write("<td>degrees</td>\n") 256 out.write("</tr>\n") 257 out.write("\n") 258 out.write("<tr>\n") 259 out.write("<td>speed</td>\n") 260 out.write("<td>udecimal</td>\n") 261 if 'speed' in params: 262 out.write(" <td>"+str(params['speed'])+"</td>\n") 263 if str(params['speed']) in speedDecodeLut: 264 out.write("<td>"+speedDecodeLut[str(params['speed'])]+"</td>") 265 else: 266 out.write("<td><i>Missing LUT entry</i></td>") 267 out.write("<td>kts</td>\n") 268 out.write("</tr>\n") 269 out.write("\n") 270 out.write("<tr>\n") 271 out.write("<td>gust</td>\n") 272 out.write("<td>udecimal</td>\n") 273 if 'gust' in params: 274 out.write(" <td>"+str(params['gust'])+"</td>\n") 275 if str(params['gust']) in gustDecodeLut: 276 out.write("<td>"+gustDecodeLut[str(params['gust'])]+"</td>") 277 else: 278 out.write("<td><i>Missing LUT entry</i></td>") 279 out.write("<td>kts</td>\n") 280 out.write("</tr>\n") 281 out.write("\n") 282 out.write("<tr>\n") 283 out.write("<td>direction</td>\n") 284 out.write("<td>uint</td>\n") 285 if 'direction' in params: 286 out.write(" <td>"+str(params['direction'])+"</td>\n") 287 out.write(" <td>"+str(params['direction'])+"</td>\n") 288 out.write("<td>degrees</td>\n") 289 out.write("</tr>\n") 290 out.write("\n") 291 out.write("<tr>\n") 292 out.write("<td>reserved</td>\n") 293 out.write("<td>uint</td>\n") 294 if 'reserved' in params: 295 out.write(" <td>"+str(params['reserved'])+"</td>\n") 296 out.write(" <td>"+str(params['reserved'])+"</td>\n") 297 out.write("</tr>\n") 298 out.write("</table>\n")
299 300
301 -def printKml(params, out=sys.stdout):
302 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer''' 303 out.write("\ <Placemark>\n") 304 out.write("\t <name>"+str(params['stationid'])+"</name>\n") 305 out.write("\t\t<description>\n") 306 import StringIO 307 buf = StringIO.StringIO() 308 printHtml(params,buf) 309 import cgi 310 out.write(cgi.escape(buf.getvalue())) 311 out.write("\t\t</description>\n") 312 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n") 313 out.write("\t\t<Point>\n") 314 out.write("\t\t\t<coordinates>") 315 out.write(str(params['pos_longitude'])) 316 out.write(',') 317 out.write(str(params['pos_latitude'])) 318 out.write(",0</coordinates>\n") 319 out.write("\t\t</Point>\n") 320 out.write("\t</Placemark>\n")
321
322 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
323 '''Print a reserved message to stdout. 324 325 Fields in params: 326 - time_month(uint): Time tag of measurement month 1..12 327 - time_day(uint): Time tag of measurement day of the month 1..31 328 - time_hour(uint): Time tag of measurement UTC hours 0..23 329 - time_min(uint): Time tag of measurement minutes 330 - stationid(aisstr6): Character identifier of the station 331 - pos_longitude(decimal): Location of measurement East West location 332 - pos_latitude(decimal): Location of measurement North South location 333 - speed(udecimal): Average wind speed 334 - gust(udecimal): Wind gust 335 - direction(uint): Wind direction 336 - reserved(uint): Reserved bits for future use (field automatically set to "0") 337 @param params: Dictionary of field names/values. 338 @param out: File like object to write to 339 @rtype: stdout 340 @return: text to out 341 ''' 342 343 if 'std'==format: 344 out.write("reserved:\n") 345 if 'time_month' in params: out.write(" time_month: "+str(params['time_month'])+"\n") 346 if 'time_day' in params: out.write(" time_day: "+str(params['time_day'])+"\n") 347 if 'time_hour' in params: out.write(" time_hour: "+str(params['time_hour'])+"\n") 348 if 'time_min' in params: out.write(" time_min: "+str(params['time_min'])+"\n") 349 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n") 350 if 'pos_longitude' in params: out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n") 351 if 'pos_latitude' in params: out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n") 352 if 'speed' in params: out.write(" speed: "+str(params['speed'])+"\n") 353 if 'gust' in params: out.write(" gust: "+str(params['gust'])+"\n") 354 if 'direction' in params: out.write(" direction: "+str(params['direction'])+"\n") 355 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n") 356 elif 'csv'==format: 357 if None == options.fieldList: 358 options.fieldList = fieldList 359 needComma = False; 360 for field in fieldList: 361 if needComma: out.write(',') 362 needComma = True 363 if field in params: 364 out.write(str(params[field])) 365 # else: leave it empty 366 out.write("\n") 367 elif 'html'==format: 368 printHtml(params,out) 369 elif 'sql'==format: 370 sqlInsertStr(params,out) 371 elif 'kml'==format: 372 printKml(params,out) 373 elif 'kml-full'==format: 374 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") 375 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n") 376 out.write("<Document>\n") 377 out.write(" <name>sls_wind</name>\n") 378 printKml(params,out) 379 out.write("</Document>\n") 380 out.write("</kml>\n") 381 else: 382 print "ERROR: unknown format:",format 383 assert False 384 385 return # Nothing to return
386 387 speedEncodeLut = { 388 '102.2 kts or greater':'102.2', 389 } #speedEncodeLut 390 391 speedDecodeLut = { 392 '102.2':'102.2 kts or greater', 393 } # speedEncodeLut 394 395 gustEncodeLut = { 396 '102.2 kts or greater':'102.2', 397 } #gustEncodeLut 398 399 gustDecodeLut = { 400 '102.2':'102.2 kts or greater', 401 } # gustEncodeLut 402 403 ###################################################################### 404 # SQL SUPPORT 405 ###################################################################### 406
407 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None, addCoastGuardFields=True):
408 ''' 409 Return the SQL CREATE command for this message type 410 @param outfile: file like object to print to. 411 @param fields: which fields to put in the create. Defaults to all. 412 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 413 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 414 @type addCoastGuardFields: bool 415 @return: sql create string 416 @rtype: str 417 418 @see: sqlCreate 419 ''' 420 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields)))
421
422 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True):
423 ''' 424 Return the sqlhelp object to create the table. 425 426 @param fields: which fields to put in the create. Defaults to all. 427 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 428 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 429 @type addCoastGuardFields: bool 430 @return: An object that can be used to generate a return 431 @rtype: sqlhelp.create 432 ''' 433 if None == fields: fields = fieldList 434 import sqlhelp 435 c = sqlhelp.create('sls_wind') 436 if 'time_month' in fields: c.addInt ('time_month') 437 if 'time_day' in fields: c.addInt ('time_day') 438 if 'time_hour' in fields: c.addInt ('time_hour') 439 if 'time_min' in fields: c.addInt ('time_min') 440 if 'stationid' in fields: c.addVarChar('stationid',7) 441 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4) 442 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4) 443 if 'speed' in fields: c.addDecimal('speed',4,1) 444 if 'gust' in fields: c.addDecimal('gust',4,1) 445 if 'direction' in fields: c.addInt ('direction') 446 if 'reserved' in fields: c.addInt ('reserved') 447 448 if addCoastGuardFields: 449 # c.addInt('cg_rssi') # Relative signal strength indicator 450 # c.addInt('cg_d') # dBm receive strength 451 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 452 # c.addInt('cg_S') # Slot received in 453 # c.addVarChar('cg_x',10) # Idonno 454 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 455 c.addInt('cg_timestamp') # UTC seconds since the epoch 456 # FIX: maybe an actually time field? 457 458 return c
459
460 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
461 ''' 462 Return the SQL CREATE command for this message type 463 @param params: dictionary of values keyed by field name 464 @param outfile: file like object to print to. 465 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 466 @return: sql create string 467 @rtype: str 468 469 @see: sqlCreate 470 ''' 471 outfile.write(str(sqlInsert(params,extraParams)))
472 473
474 -def sqlInsert(params,extraParams=None):
475 ''' 476 Give the SQL insert statement 477 @param params: dict keyed by field name of values 478 @param extraParams: any extra fields that you have created beyond the normal ais message fields 479 @rtype: sqlhelp.insert 480 @return: insert class instance 481 @todo: allow optional type checking of params? 482 @warning: this will take invalid keys happily and do what??? 483 ''' 484 import sqlhelp 485 i = sqlhelp.insert('sls_wind') 486 for key in params: 487 #i.add(key,params[key]) 488 if type(params[key])==Decimal: i.add(key,float(params[key])) 489 else: i.add(key,params[key]) 490 if None != extraParams: 491 for key in extraParams: 492 i.add(key,extraParams[key]) 493 494 return i
495 496 497 ###################################################################### 498 # UNIT TESTING 499 ###################################################################### 500 import unittest
501 -def testParams():
502 '''Return a params file base on the testvalue tags. 503 @rtype: dict 504 @return: params based on testvalue tags 505 ''' 506 params = {} 507 params['time_month'] = 2 508 params['time_day'] = 28 509 params['time_hour'] = 23 510 params['time_min'] = 45 511 params['stationid'] = 'A345678' 512 params['pos_longitude'] = Decimal('-122.16328') 513 params['pos_latitude'] = Decimal('37.42446') 514 params['speed'] = Decimal('0.7') 515 params['gust'] = Decimal('0.7') 516 params['direction'] = 90 517 params['reserved'] = 0 518 519 return params
520
521 -class Testsls_wind(unittest.TestCase):
522 '''Use testvalue tag text from each type to build test case the sls_wind message'''
523 - def testEncodeDecode(self):
524 525 params = testParams() 526 bits = encode(params) 527 r = decode(bits) 528 529 # Check that each parameter came through ok. 530 self.failUnlessEqual(r['time_month'],params['time_month']) 531 self.failUnlessEqual(r['time_day'],params['time_day']) 532 self.failUnlessEqual(r['time_hour'],params['time_hour']) 533 self.failUnlessEqual(r['time_min'],params['time_min']) 534 self.failUnlessEqual(r['stationid'],params['stationid']) 535 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4) 536 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4) 537 self.failUnlessAlmostEqual(r['speed'],params['speed'],1) 538 self.failUnlessAlmostEqual(r['gust'],params['gust'],1) 539 self.failUnlessEqual(r['direction'],params['direction']) 540 self.failUnlessEqual(r['reserved'],params['reserved'])
541
542 -def addMsgOptions(parser):
543 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 544 help='decode a "sls_wind" AIS message') 545 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 546 help='encode a "sls_wind" AIS message') 547 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int' 548 ,help='Field parameter value [default: %default]') 549 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int' 550 ,help='Field parameter value [default: %default]') 551 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int' 552 ,help='Field parameter value [default: %default]') 553 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int' 554 ,help='Field parameter value [default: %default]') 555 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string' 556 ,help='Field parameter value [default: %default]') 557 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 558 ,help='Field parameter value [default: %default]') 559 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 560 ,help='Field parameter value [default: %default]') 561 parser.add_option('--speed-field', dest='speedField',default=Decimal('102.3'),metavar='udecimal',type='string' 562 ,help='Field parameter value [default: %default]') 563 parser.add_option('--gust-field', dest='gustField',default=Decimal('102.3'),metavar='udecimal',type='string' 564 ,help='Field parameter value [default: %default]') 565 parser.add_option('--direction-field', dest='directionField',default=511,metavar='uint',type='int' 566 ,help='Field parameter value [default: %default]')
567 568 ############################################################ 569 if __name__=='__main__': 570 571 from optparse import OptionParser 572 parser = OptionParser(usage="%prog [options]", 573 version="%prog "+__version__) 574 575 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 576 help='run the documentation tests') 577 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 578 help='run the unit tests') 579 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 580 help='Make the test output verbose') 581 582 # FIX: remove nmea from binary messages. No way to build the whole packet? 583 # FIX: or build the surrounding msg 8 for a broadcast? 584 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 585 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 586 ,default='nmeapayload' 587 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 588 589 590 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 591 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 592 ,default='std' 593 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 594 595 parser.add_option('-o','--output',dest='outputFileName',default=None, 596 help='Name of the python file to write [default: stdout]') 597 598 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 599 choices=fieldList, 600 help='Which fields to include in the output. Currently only for csv output [default: all]') 601 602 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 603 help='Print the field name for csv') 604 605 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 606 help='Print out an sql create command for the table.') 607 608 addMsgOptions(parser) 609 610 (options,args) = parser.parse_args() 611 success=True 612 613 if options.doctest: 614 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 615 sys.argv= [sys.argv[0]] 616 if options.verbose: sys.argv.append('-v') 617 import doctest 618 numfail,numtests=doctest.testmod() 619 if numfail==0: print 'ok' 620 else: 621 print 'FAILED' 622 success=False 623 624 if not success: sys.exit('Something Failed') 625 del success # Hide success from epydoc 626 627 if options.unittest: 628 sys.argv = [sys.argv[0]] 629 if options.verbose: sys.argv.append('-v') 630 unittest.main() 631 632 outfile = sys.stdout 633 if None!=options.outputFileName: 634 outfile = file(options.outputFileName,'w') 635 636 637 if options.doEncode: 638 # First make sure all non required options are specified 639 if None==options.time_monthField: parser.error("missing value for time_monthField") 640 if None==options.time_dayField: parser.error("missing value for time_dayField") 641 if None==options.time_hourField: parser.error("missing value for time_hourField") 642 if None==options.time_minField: parser.error("missing value for time_minField") 643 if None==options.stationidField: parser.error("missing value for stationidField") 644 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField") 645 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField") 646 if None==options.speedField: parser.error("missing value for speedField") 647 if None==options.gustField: parser.error("missing value for gustField") 648 if None==options.directionField: parser.error("missing value for directionField") 649 msgDict={ 650 'time_month': options.time_monthField, 651 'time_day': options.time_dayField, 652 'time_hour': options.time_hourField, 653 'time_min': options.time_minField, 654 'stationid': options.stationidField, 655 'pos_longitude': options.pos_longitudeField, 656 'pos_latitude': options.pos_latitudeField, 657 'speed': options.speedField, 658 'gust': options.gustField, 659 'direction': options.directionField, 660 'reserved': '0', 661 } 662 663 bits = encode(msgDict) 664 if 'binary'==options.ioType: print str(bits) 665 elif 'nmeapayload'==options.ioType: 666 # FIX: figure out if this might be necessary at compile time 667 print "bitLen",len(bits) 668 bitLen=len(bits) 669 if bitLen%6!=0: 670 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 671 print "result:",binary.bitvectoais6(bits)[0] 672 673 674 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 675 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 676 else: sys.exit('ERROR: unknown ioType. Help!') 677 678 679 if options.sqlCreate: 680 sqlCreateStr(outfile,options.fieldList) 681 682 if options.printCsvfieldList: 683 # Make a csv separated list of fields that will be displayed for csv 684 if None == options.fieldList: options.fieldList = fieldList 685 import StringIO 686 buf = StringIO.StringIO() 687 for field in options.fieldList: 688 buf.write(field+',') 689 result = buf.getvalue() 690 if result[-1] == ',': print result[:-1] 691 else: print result 692 693 if options.doDecode: 694 for msg in args: 695 bv = None 696 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 697 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 698 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 699 else: sys.exit('ERROR: unknown ioType. Help!') 700 701 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 702