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

Source Code for Module ais.sls_waterlevel

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