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-01-23 $'.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):
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 @return: sql create string 414 @rtype: str 415 416 @see: sqlCreate 417 ''' 418 outfile.write(str(sqlCreate(fields,extraFields)))
419
420 -def sqlCreate(fields=None, extraFields=None):
421 ''' 422 Return the sqlhelp object to create the table. 423 424 @param fields: which fields to put in the create. Defaults to all. 425 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 426 @return: An object that can be used to generate a return 427 @rtype: sqlhelp.create 428 ''' 429 if None == fields: fields = fieldList 430 import sqlhelp 431 c = sqlhelp.create('sls_wind') 432 if 'time_month' in fields: c.addInt ('time_month') 433 if 'time_day' in fields: c.addInt ('time_day') 434 if 'time_hour' in fields: c.addInt ('time_hour') 435 if 'time_min' in fields: c.addInt ('time_min') 436 if 'stationid' in fields: c.addVarChar(stationid,7) 437 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4) 438 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4) 439 if 'speed' in fields: c.addDecimal('speed',4,1) 440 if 'gust' in fields: c.addDecimal('gust',4,1) 441 if 'direction' in fields: c.addInt ('direction') 442 if 'reserved' in fields: c.addInt ('reserved') 443 444 return c
445
446 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
447 ''' 448 Return the SQL CREATE command for this message type 449 @param params: dictionary of values keyed by field name 450 @param outfile: file like object to print to. 451 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 452 @return: sql create string 453 @rtype: str 454 455 @see: sqlCreate 456 ''' 457 outfile.write(str(sqlInsert(params,extraParams)))
458 459
460 -def sqlInsert(params,extraParams=None):
461 ''' 462 Give the SQL insert statement 463 @param params: dict keyed by field name of values 464 @param extraParams: any extra fields that you have created beyond the normal ais message fields 465 @rtype: sqlhelp.insert 466 @return: insert class instance 467 @todo: allow optional type checking of params? 468 @warning: this will take invalid keys happily and do what??? 469 ''' 470 import sqlhelp 471 i = sqlhelp.insert('sls_wind') 472 for key in params: i.add(key,params[key]) 473 if None != extraParams: 474 for key in extraParams: 475 i.add(key,extraParams[key]) 476 477 return i
478 479 480 ###################################################################### 481 # UNIT TESTING 482 ###################################################################### 483 import unittest
484 -def testParams():
485 '''Return a params file base on the testvalue tags. 486 @rtype: dict 487 @return: params based on testvalue tags 488 ''' 489 params = {} 490 params['time_month'] = 2 491 params['time_day'] = 28 492 params['time_hour'] = 23 493 params['time_min'] = 45 494 params['stationid'] = 'A345678' 495 params['pos_longitude'] = Decimal('-122.16328') 496 params['pos_latitude'] = Decimal('37.42446') 497 params['speed'] = Decimal('0.7') 498 params['gust'] = Decimal('0.7') 499 params['direction'] = 90 500 params['reserved'] = 0 501 502 return params
503
504 -class Testsls_wind(unittest.TestCase):
505 '''Use testvalue tag text from each type to build test case the sls_wind message'''
506 - def testEncodeDecode(self):
507 508 params = testParams() 509 bits = encode(params) 510 r = decode(bits) 511 512 # Check that each parameter came through ok. 513 self.failUnlessEqual(r['time_month'],params['time_month']) 514 self.failUnlessEqual(r['time_day'],params['time_day']) 515 self.failUnlessEqual(r['time_hour'],params['time_hour']) 516 self.failUnlessEqual(r['time_min'],params['time_min']) 517 self.failUnlessEqual(r['stationid'],params['stationid']) 518 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4) 519 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4) 520 self.failUnlessAlmostEqual(r['speed'],params['speed'],1) 521 self.failUnlessAlmostEqual(r['gust'],params['gust'],1) 522 self.failUnlessEqual(r['direction'],params['direction']) 523 self.failUnlessEqual(r['reserved'],params['reserved'])
524
525 -def addMsgOptions(parser):
526 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 527 help='decode a "sls_wind" AIS message') 528 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 529 help='encode a "sls_wind" AIS message') 530 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int' 531 ,help='Field parameter value [default: %default]') 532 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int' 533 ,help='Field parameter value [default: %default]') 534 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int' 535 ,help='Field parameter value [default: %default]') 536 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int' 537 ,help='Field parameter value [default: %default]') 538 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string' 539 ,help='Field parameter value [default: %default]') 540 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string' 541 ,help='Field parameter value [default: %default]') 542 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string' 543 ,help='Field parameter value [default: %default]') 544 parser.add_option('--speed-field', dest='speedField',default=Decimal('102.3'),metavar='udecimal',type='string' 545 ,help='Field parameter value [default: %default]') 546 parser.add_option('--gust-field', dest='gustField',default=Decimal('102.3'),metavar='udecimal',type='string' 547 ,help='Field parameter value [default: %default]') 548 parser.add_option('--direction-field', dest='directionField',default=511,metavar='uint',type='int' 549 ,help='Field parameter value [default: %default]')
550 551 ############################################################ 552 if __name__=='__main__': 553 554 from optparse import OptionParser 555 parser = OptionParser(usage="%prog [options]", 556 version="%prog "+__version__) 557 558 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 559 help='run the documentation tests') 560 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 561 help='run the unit tests') 562 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 563 help='Make the test output verbose') 564 565 # FIX: remove nmea from binary messages. No way to build the whole packet? 566 # FIX: or build the surrounding msg 8 for a broadcast? 567 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 568 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 569 ,default='nmeapayload' 570 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]') 571 572 573 outputChoices = ('std','html','csv','sql' , 'kml','kml-full') 574 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 575 ,default='std' 576 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 577 578 parser.add_option('-o','--output',dest='outputFileName',default=None, 579 help='Name of the python file to write [default: stdout]') 580 581 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 582 choices=fieldList, 583 help='Which fields to include in the output. Currently only for csv output [default: all]') 584 585 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 586 help='Print the field name for csv') 587 588 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 589 help='Print out an sql create command for the table.') 590 591 addMsgOptions(parser) 592 593 (options,args) = parser.parse_args() 594 success=True 595 596 if options.doctest: 597 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 598 sys.argv= [sys.argv[0]] 599 if options.verbose: sys.argv.append('-v') 600 import doctest 601 numfail,numtests=doctest.testmod() 602 if numfail==0: print 'ok' 603 else: 604 print 'FAILED' 605 success=False 606 607 if not success: sys.exit('Something Failed') 608 del success # Hide success from epydoc 609 610 if options.unittest: 611 sys.argv = [sys.argv[0]] 612 if options.verbose: sys.argv.append('-v') 613 unittest.main() 614 615 outfile = sys.stdout 616 if None!=options.outputFileName: 617 outfile = file(options.outputFileName,'w') 618 619 620 if options.doEncode: 621 # First make sure all non required options are specified 622 if None==options.time_monthField: parser.error("missing value for time_monthField") 623 if None==options.time_dayField: parser.error("missing value for time_dayField") 624 if None==options.time_hourField: parser.error("missing value for time_hourField") 625 if None==options.time_minField: parser.error("missing value for time_minField") 626 if None==options.stationidField: parser.error("missing value for stationidField") 627 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField") 628 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField") 629 if None==options.speedField: parser.error("missing value for speedField") 630 if None==options.gustField: parser.error("missing value for gustField") 631 if None==options.directionField: parser.error("missing value for directionField") 632 msgDict={ 633 'time_month': options.time_monthField, 634 'time_day': options.time_dayField, 635 'time_hour': options.time_hourField, 636 'time_min': options.time_minField, 637 'stationid': options.stationidField, 638 'pos_longitude': options.pos_longitudeField, 639 'pos_latitude': options.pos_latitudeField, 640 'speed': options.speedField, 641 'gust': options.gustField, 642 'direction': options.directionField, 643 'reserved': '0', 644 } 645 646 bits = encode(msgDict) 647 if 'binary'==options.ioType: print str(bits) 648 elif 'nmeapayload'==options.ioType: 649 # FIX: figure out if this might be necessary at compile time 650 print "bitLen",len(bits) 651 bitLen=len(bits) 652 if bitLen%6!=0: 653 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 654 print "result:",binary.bitvectoais6(bits)[0] 655 656 657 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 658 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 659 else: sys.exit('ERROR: unknown ioType. Help!') 660 661 662 if options.sqlCreate: 663 sqlCreateStr(outfile,options.fieldList) 664 665 if options.printCsvfieldList: 666 # Make a csv separated list of fields that will be displayed for csv 667 if None == options.fieldList: options.fieldList = fieldList 668 import StringIO 669 buf = StringIO.StringIO() 670 for field in options.fieldList: 671 buf.write(field+',') 672 result = buf.getvalue() 673 if result[-1] == ',': print result[:-1] 674 else: print result 675 676 if options.doDecode: 677 for msg in args: 678 bv = None 679 if 'binary' == options.ioType: bv = BitVector(bitstring=msg) 680 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg) 681 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5]) 682 else: sys.exit('ERROR: unknown ioType. Help!') 683 684 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList) 685