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