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

Source Code for Module ais.whalenotice1

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