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

Source Code for Module ais.ais_msg_15

  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          'DestID', 
 54          'MessageID1', 
 55          'SlotOffset', 
 56          'Spare', 
 57          'MessageID12', 
 58          'SlotOffset12', 
 59          'Spare2', 
 60          'DestID2', 
 61          'MessageID2', 
 62          'SlotOffset2', 
 63          'Spare3', 
 64  ) 
 65   
 66  fieldListPostgres = ( 
 67          'MessageID', 
 68          'RepeatIndicator', 
 69          'UserID', 
 70          'DestID', 
 71          'MessageID1', 
 72          'SlotOffset', 
 73          'Spare', 
 74          'MessageID12', 
 75          'SlotOffset12', 
 76          'Spare2', 
 77          'DestID2', 
 78          'MessageID2', 
 79          'SlotOffset2', 
 80          'Spare3', 
 81  ) 
 82   
 83  toPgFields = { 
 84  } 
 85  ''' 
 86  Go to the Postgis field names from the straight field name 
 87  ''' 
 88   
 89  fromPgFields = { 
 90  } 
 91  ''' 
 92  Go from the Postgis field names to the straight field name 
 93  ''' 
 94   
 95  pgTypes = { 
 96  } 
 97  ''' 
 98  Lookup table for each postgis field name to get its type. 
 99  ''' 
100   
101 -def encode(params, validate=False):
102 '''Create a interrogation binary message payload to pack into an AIS Msg interrogation. 103 104 Fields in params: 105 - MessageID(uint): AIS message number. Must be 15 (field automatically set to "15") 106 - RepeatIndicator(uint): Indicated how many times a message has been repeated 107 - UserID(uint): MMSI number of interrogating station 108 - DestID(uint): MMSI number of interrogated station 109 - MessageID1(uint): requested message type from interrogated station 110 - SlotOffset(uint): requested message type from interrogated station 111 - Spare(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 112 - MessageID12(uint): requested message type from interrogated station 113 - SlotOffset12(uint): requested message type from interrogated station 114 - Spare2(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 115 - DestID2(uint): MMSI number of interrogated station 116 - MessageID2(uint): requested message type from interrogated station 117 - SlotOffset2(uint): requested message type from interrogated station 118 - Spare3(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 119 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing 120 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented. 121 @rtype: BitVector 122 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8 123 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits. 124 ''' 125 126 bvList = [] 127 bvList.append(binary.setBitVectorSize(BitVector(intVal=15),6)) 128 if 'RepeatIndicator' in params: 129 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2)) 130 else: 131 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 132 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30)) 133 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['DestID']),30)) 134 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID1']),6)) 135 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['SlotOffset']),6)) 136 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 137 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID12']),6)) 138 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['SlotOffset12']),6)) 139 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 140 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['DestID2']),30)) 141 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID2']),6)) 142 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['SlotOffset2']),6)) 143 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2)) 144 145 return binary.joinBV(bvList)
146
147 -def decode(bv, validate=False):
148 '''Unpack a interrogation message 149 150 Fields in params: 151 - MessageID(uint): AIS message number. Must be 15 (field automatically set to "15") 152 - RepeatIndicator(uint): Indicated how many times a message has been repeated 153 - UserID(uint): MMSI number of interrogating station 154 - DestID(uint): MMSI number of interrogated station 155 - MessageID1(uint): requested message type from interrogated station 156 - SlotOffset(uint): requested message type from interrogated station 157 - Spare(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 158 - MessageID12(uint): requested message type from interrogated station 159 - SlotOffset12(uint): requested message type from interrogated station 160 - Spare2(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 161 - DestID2(uint): MMSI number of interrogated station 162 - MessageID2(uint): requested message type from interrogated station 163 - SlotOffset2(uint): requested message type from interrogated station 164 - Spare3(uint): Not used. Should be set to zero. Researved 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['MessageID']=15 177 r['RepeatIndicator']=int(bv[6:8]) 178 r['UserID']=int(bv[8:38]) 179 r['DestID']=int(bv[38:68]) 180 r['MessageID1']=int(bv[68:74]) 181 r['SlotOffset']=int(bv[74:80]) 182 r['Spare']=0 183 r['MessageID12']=int(bv[82:88]) 184 r['SlotOffset12']=int(bv[88:94]) 185 r['Spare2']=0 186 r['DestID2']=int(bv[96:126]) 187 r['MessageID2']=int(bv[126:132]) 188 r['SlotOffset2']=int(bv[132:138]) 189 r['Spare3']=0 190 return r
191
192 -def decodeMessageID(bv, validate=False):
193 return 15
194
195 -def decodeRepeatIndicator(bv, validate=False):
196 return int(bv[6:8])
197
198 -def decodeUserID(bv, validate=False):
199 return int(bv[8:38])
200
201 -def decodeDestID(bv, validate=False):
202 return int(bv[38:68])
203
204 -def decodeMessageID1(bv, validate=False):
205 return int(bv[68:74])
206
207 -def decodeSlotOffset(bv, validate=False):
208 return int(bv[74:80])
209
210 -def decodeSpare(bv, validate=False):
211 return 0
212
213 -def decodeMessageID12(bv, validate=False):
214 return int(bv[82:88])
215
216 -def decodeSlotOffset12(bv, validate=False):
217 return int(bv[88:94])
218
219 -def decodeSpare2(bv, validate=False):
220 return 0
221
222 -def decodeDestID2(bv, validate=False):
223 return int(bv[96:126])
224
225 -def decodeMessageID2(bv, validate=False):
226 return int(bv[126:132])
227
228 -def decodeSlotOffset2(bv, validate=False):
229 return int(bv[132:138])
230
231 -def decodeSpare3(bv, validate=False):
232 return 0
233 234
235 -def printHtml(params, out=sys.stdout):
236 out.write("<h3>interrogation</h3>\n") 237 out.write("<table border=\"1\">\n") 238 out.write("<tr bgcolor=\"orange\">\n") 239 out.write("<th align=\"left\">Field Name</th>\n") 240 out.write("<th align=\"left\">Type</th>\n") 241 out.write("<th align=\"left\">Value</th>\n") 242 out.write("<th align=\"left\">Value in Lookup Table</th>\n") 243 out.write("<th align=\"left\">Units</th>\n") 244 out.write("\n") 245 out.write("<tr>\n") 246 out.write("<td>MessageID</td>\n") 247 out.write("<td>uint</td>\n") 248 if 'MessageID' in params: 249 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 250 out.write(" <td>"+str(params['MessageID'])+"</td>\n") 251 out.write("</tr>\n") 252 out.write("\n") 253 out.write("<tr>\n") 254 out.write("<td>RepeatIndicator</td>\n") 255 out.write("<td>uint</td>\n") 256 if 'RepeatIndicator' in params: 257 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n") 258 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut: 259 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>") 260 else: 261 out.write("<td><i>Missing LUT entry</i></td>") 262 out.write("</tr>\n") 263 out.write("\n") 264 out.write("<tr>\n") 265 out.write("<td>UserID</td>\n") 266 out.write("<td>uint</td>\n") 267 if 'UserID' in params: 268 out.write(" <td>"+str(params['UserID'])+"</td>\n") 269 out.write(" <td>"+str(params['UserID'])+"</td>\n") 270 out.write("</tr>\n") 271 out.write("\n") 272 out.write("<tr>\n") 273 out.write("<td>DestID</td>\n") 274 out.write("<td>uint</td>\n") 275 if 'DestID' in params: 276 out.write(" <td>"+str(params['DestID'])+"</td>\n") 277 out.write(" <td>"+str(params['DestID'])+"</td>\n") 278 out.write("</tr>\n") 279 out.write("\n") 280 out.write("<tr>\n") 281 out.write("<td>MessageID1</td>\n") 282 out.write("<td>uint</td>\n") 283 if 'MessageID1' in params: 284 out.write(" <td>"+str(params['MessageID1'])+"</td>\n") 285 out.write(" <td>"+str(params['MessageID1'])+"</td>\n") 286 out.write("</tr>\n") 287 out.write("\n") 288 out.write("<tr>\n") 289 out.write("<td>SlotOffset</td>\n") 290 out.write("<td>uint</td>\n") 291 if 'SlotOffset' in params: 292 out.write(" <td>"+str(params['SlotOffset'])+"</td>\n") 293 out.write(" <td>"+str(params['SlotOffset'])+"</td>\n") 294 out.write("</tr>\n") 295 out.write("\n") 296 out.write("<tr>\n") 297 out.write("<td>Spare</td>\n") 298 out.write("<td>uint</td>\n") 299 if 'Spare' in params: 300 out.write(" <td>"+str(params['Spare'])+"</td>\n") 301 out.write(" <td>"+str(params['Spare'])+"</td>\n") 302 out.write("</tr>\n") 303 out.write("\n") 304 out.write("<tr>\n") 305 out.write("<td>MessageID12</td>\n") 306 out.write("<td>uint</td>\n") 307 if 'MessageID12' in params: 308 out.write(" <td>"+str(params['MessageID12'])+"</td>\n") 309 out.write(" <td>"+str(params['MessageID12'])+"</td>\n") 310 out.write("</tr>\n") 311 out.write("\n") 312 out.write("<tr>\n") 313 out.write("<td>SlotOffset12</td>\n") 314 out.write("<td>uint</td>\n") 315 if 'SlotOffset12' in params: 316 out.write(" <td>"+str(params['SlotOffset12'])+"</td>\n") 317 out.write(" <td>"+str(params['SlotOffset12'])+"</td>\n") 318 out.write("</tr>\n") 319 out.write("\n") 320 out.write("<tr>\n") 321 out.write("<td>Spare2</td>\n") 322 out.write("<td>uint</td>\n") 323 if 'Spare2' in params: 324 out.write(" <td>"+str(params['Spare2'])+"</td>\n") 325 out.write(" <td>"+str(params['Spare2'])+"</td>\n") 326 out.write("</tr>\n") 327 out.write("\n") 328 out.write("<tr>\n") 329 out.write("<td>DestID2</td>\n") 330 out.write("<td>uint</td>\n") 331 if 'DestID2' in params: 332 out.write(" <td>"+str(params['DestID2'])+"</td>\n") 333 out.write(" <td>"+str(params['DestID2'])+"</td>\n") 334 out.write("</tr>\n") 335 out.write("\n") 336 out.write("<tr>\n") 337 out.write("<td>MessageID2</td>\n") 338 out.write("<td>uint</td>\n") 339 if 'MessageID2' in params: 340 out.write(" <td>"+str(params['MessageID2'])+"</td>\n") 341 out.write(" <td>"+str(params['MessageID2'])+"</td>\n") 342 out.write("</tr>\n") 343 out.write("\n") 344 out.write("<tr>\n") 345 out.write("<td>SlotOffset2</td>\n") 346 out.write("<td>uint</td>\n") 347 if 'SlotOffset2' in params: 348 out.write(" <td>"+str(params['SlotOffset2'])+"</td>\n") 349 out.write(" <td>"+str(params['SlotOffset2'])+"</td>\n") 350 out.write("</tr>\n") 351 out.write("\n") 352 out.write("<tr>\n") 353 out.write("<td>Spare3</td>\n") 354 out.write("<td>uint</td>\n") 355 if 'Spare3' in params: 356 out.write(" <td>"+str(params['Spare3'])+"</td>\n") 357 out.write(" <td>"+str(params['Spare3'])+"</td>\n") 358 out.write("</tr>\n") 359 out.write("</table>\n")
360
361 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
362 '''Print a interrogation message to stdout. 363 364 Fields in params: 365 - MessageID(uint): AIS message number. Must be 15 (field automatically set to "15") 366 - RepeatIndicator(uint): Indicated how many times a message has been repeated 367 - UserID(uint): MMSI number of interrogating station 368 - DestID(uint): MMSI number of interrogated station 369 - MessageID1(uint): requested message type from interrogated station 370 - SlotOffset(uint): requested message type from interrogated station 371 - Spare(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 372 - MessageID12(uint): requested message type from interrogated station 373 - SlotOffset12(uint): requested message type from interrogated station 374 - Spare2(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 375 - DestID2(uint): MMSI number of interrogated station 376 - MessageID2(uint): requested message type from interrogated station 377 - SlotOffset2(uint): requested message type from interrogated station 378 - Spare3(uint): Not used. Should be set to zero. Researved for future use. (field automatically set to "0") 379 @param params: Dictionary of field names/values. 380 @param out: File like object to write to 381 @rtype: stdout 382 @return: text to out 383 ''' 384 385 if 'std'==format: 386 out.write("interrogation:\n") 387 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n") 388 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n") 389 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n") 390 if 'DestID' in params: out.write(" DestID: "+str(params['DestID'])+"\n") 391 if 'MessageID1' in params: out.write(" MessageID1: "+str(params['MessageID1'])+"\n") 392 if 'SlotOffset' in params: out.write(" SlotOffset: "+str(params['SlotOffset'])+"\n") 393 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n") 394 if 'MessageID12' in params: out.write(" MessageID12: "+str(params['MessageID12'])+"\n") 395 if 'SlotOffset12' in params: out.write(" SlotOffset12: "+str(params['SlotOffset12'])+"\n") 396 if 'Spare2' in params: out.write(" Spare2: "+str(params['Spare2'])+"\n") 397 if 'DestID2' in params: out.write(" DestID2: "+str(params['DestID2'])+"\n") 398 if 'MessageID2' in params: out.write(" MessageID2: "+str(params['MessageID2'])+"\n") 399 if 'SlotOffset2' in params: out.write(" SlotOffset2: "+str(params['SlotOffset2'])+"\n") 400 if 'Spare3' in params: out.write(" Spare3: "+str(params['Spare3'])+"\n") 401 elif 'csv'==format: 402 if None == options.fieldList: 403 options.fieldList = fieldList 404 needComma = False; 405 for field in fieldList: 406 if needComma: out.write(',') 407 needComma = True 408 if field in params: 409 out.write(str(params[field])) 410 # else: leave it empty 411 out.write("\n") 412 elif 'html'==format: 413 printHtml(params,out) 414 elif 'sql'==format: 415 sqlInsertStr(params,out,dbType=dbType) 416 else: 417 print "ERROR: unknown format:",format 418 assert False 419 420 return # Nothing to return
421 422 RepeatIndicatorEncodeLut = { 423 'default':'0', 424 'do not repeat any more':'3', 425 } #RepeatIndicatorEncodeLut 426 427 RepeatIndicatorDecodeLut = { 428 '0':'default', 429 '3':'do not repeat any more', 430 } # RepeatIndicatorEncodeLut 431 432 ###################################################################### 433 # SQL SUPPORT 434 ###################################################################### 435 436 dbTableName='interrogation' 437 'Database table name' 438
439 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None 440 ,addCoastGuardFields=True 441 ,dbType='postgres' 442 ):
443 ''' 444 Return the SQL CREATE command for this message type 445 @param outfile: file like object to print to. 446 @param fields: which fields to put in the create. Defaults to all. 447 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 448 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 449 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 450 @type addCoastGuardFields: bool 451 @return: sql create string 452 @rtype: str 453 454 @see: sqlCreate 455 ''' 456 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 457 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
458
459 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
460 ''' 461 Return the sqlhelp object to create the table. 462 463 @param fields: which fields to put in the create. Defaults to all. 464 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 465 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 466 @type addCoastGuardFields: bool 467 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 468 @return: An object that can be used to generate a return 469 @rtype: sqlhelp.create 470 ''' 471 if None == fields: fields = fieldList 472 import sqlhelp 473 c = sqlhelp.create('interrogation',dbType=dbType) 474 c.addPrimaryKey() 475 if 'MessageID' in fields: c.addInt ('MessageID') 476 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 477 if 'UserID' in fields: c.addInt ('UserID') 478 if 'DestID' in fields: c.addInt ('DestID') 479 if 'MessageID1' in fields: c.addInt ('MessageID1') 480 if 'SlotOffset' in fields: c.addInt ('SlotOffset') 481 if 'Spare' in fields: c.addInt ('Spare') 482 if 'MessageID12' in fields: c.addInt ('MessageID12') 483 if 'SlotOffset12' in fields: c.addInt ('SlotOffset12') 484 if 'Spare2' in fields: c.addInt ('Spare2') 485 if 'DestID2' in fields: c.addInt ('DestID2') 486 if 'MessageID2' in fields: c.addInt ('MessageID2') 487 if 'SlotOffset2' in fields: c.addInt ('SlotOffset2') 488 if 'Spare3' in fields: c.addInt ('Spare3') 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('interrogation',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 # LATEX SUPPORT 569 ###################################################################### 570
571 -def latexDefinitionTable(outfile=sys.stdout 572 ):
573 ''' 574 Return the LaTeX definition table for this message type 575 @param outfile: file like object to print to. 576 @type outfile: file obj 577 @return: LaTeX table string via the outfile 578 @rtype: str 579 580 ''' 581 o = outfile 582 583 o.write(''' 584 \\begin{table}%[htb] 585 \\centering 586 \\begin{tabular}{|l|c|l|} 587 \\hline 588 Parameter & Number of bits & Description 589 \\\\ \\hline\\hline 590 MessageID & 6 & AIS message number. Must be 15 \\\\ \hline 591 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 592 UserID & 30 & MMSI number of interrogating station \\\\ \hline 593 DestID & 30 & MMSI number of interrogated station \\\\ \hline 594 MessageID1 & 6 & requested message type from interrogated station \\\\ \hline 595 SlotOffset & 6 & requested message type from interrogated station \\\\ \hline 596 Spare & 2 & Not used. Should be set to zero. Researved for future use. \\\\ \hline 597 MessageID12 & 6 & requested message type from interrogated station \\\\ \hline 598 SlotOffset12 & 6 & requested message type from interrogated station \\\\ \hline 599 Spare2 & 2 & Not used. Should be set to zero. Researved for future use. \\\\ \hline 600 DestID2 & 30 & MMSI number of interrogated station \\\\ \hline 601 MessageID2 & 6 & requested message type from interrogated station \\\\ \hline 602 SlotOffset2 & 6 & requested message type from interrogated station \\\\ \hline 603 Spare3 & 2 & Not used. Should be set to zero. Researved for future use.\\\\ \\hline \\hline 604 Total bits & 140 & Appears to take 1 slot with 28 pad bits to fill the last slot \\\\ \\hline 605 \\end{tabular} 606 \\caption{AIS message number 15: FIX: need a description} 607 \\label{tab:interrogation} 608 \\end{table} 609 ''')
610 611 ###################################################################### 612 # Text Definition 613 ###################################################################### 614
615 -def textDefinitionTable(outfile=sys.stdout 616 ,delim='\t' 617 ):
618 ''' 619 Return the text definition table for this message type 620 @param outfile: file like object to print to. 621 @type outfile: file obj 622 @return: text table string via the outfile 623 @rtype: str 624 625 ''' 626 o = outfile 627 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description 628 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 15 629 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated 630 UserID'''+delim+'''30'''+delim+'''MMSI number of interrogating station 631 DestID'''+delim+'''30'''+delim+'''MMSI number of interrogated station 632 MessageID1'''+delim+'''6'''+delim+'''requested message type from interrogated station 633 SlotOffset'''+delim+'''6'''+delim+'''requested message type from interrogated station 634 Spare'''+delim+'''2'''+delim+'''Not used. Should be set to zero. Researved for future use. 635 MessageID12'''+delim+'''6'''+delim+'''requested message type from interrogated station 636 SlotOffset12'''+delim+'''6'''+delim+'''requested message type from interrogated station 637 Spare2'''+delim+'''2'''+delim+'''Not used. Should be set to zero. Researved for future use. 638 DestID2'''+delim+'''30'''+delim+'''MMSI number of interrogated station 639 MessageID2'''+delim+'''6'''+delim+'''requested message type from interrogated station 640 SlotOffset2'''+delim+'''6'''+delim+'''requested message type from interrogated station 641 Spare3'''+delim+'''2'''+delim+'''Not used. Should be set to zero. Researved for future use. 642 Total bits'''+delim+'''140'''+delim+'''Appears to take 1 slot with 28 pad bits to fill the last slot''')
643 644 645 ###################################################################### 646 # UNIT TESTING 647 ###################################################################### 648 import unittest
649 -def testParams():
650 '''Return a params file base on the testvalue tags. 651 @rtype: dict 652 @return: params based on testvalue tags 653 ''' 654 params = {} 655 params['MessageID'] = 15 656 params['RepeatIndicator'] = 1 657 params['UserID'] = 1193046 658 params['DestID'] = 1193046 659 params['MessageID1'] = 7 660 params['SlotOffset'] = 4 661 params['Spare'] = 0 662 params['MessageID12'] = 9 663 params['SlotOffset12'] = 5 664 params['Spare2'] = 0 665 params['DestID2'] = 1193045 666 params['MessageID2'] = 12 667 params['SlotOffset2'] = 2 668 params['Spare3'] = 0 669 670 return params
671
672 -class Testinterrogation(unittest.TestCase):
673 '''Use testvalue tag text from each type to build test case the interrogation 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['MessageID'],params['MessageID']) 682 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 683 self.failUnlessEqual(r['UserID'],params['UserID']) 684 self.failUnlessEqual(r['DestID'],params['DestID']) 685 self.failUnlessEqual(r['MessageID1'],params['MessageID1']) 686 self.failUnlessEqual(r['SlotOffset'],params['SlotOffset']) 687 self.failUnlessEqual(r['Spare'],params['Spare']) 688 self.failUnlessEqual(r['MessageID12'],params['MessageID12']) 689 self.failUnlessEqual(r['SlotOffset12'],params['SlotOffset12']) 690 self.failUnlessEqual(r['Spare2'],params['Spare2']) 691 self.failUnlessEqual(r['DestID2'],params['DestID2']) 692 self.failUnlessEqual(r['MessageID2'],params['MessageID2']) 693 self.failUnlessEqual(r['SlotOffset2'],params['SlotOffset2']) 694 self.failUnlessEqual(r['Spare3'],params['Spare3'])
695
696 -def addMsgOptions(parser):
697 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 698 help='decode a "interrogation" AIS message') 699 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 700 help='encode a "interrogation" AIS message') 701 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 702 ,help='Field parameter value [default: %default]') 703 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 704 ,help='Field parameter value [default: %default]') 705 parser.add_option('--DestID-field', dest='DestIDField',metavar='uint',type='int' 706 ,help='Field parameter value [default: %default]') 707 parser.add_option('--MessageID1-field', dest='MessageID1Field',metavar='uint',type='int' 708 ,help='Field parameter value [default: %default]') 709 parser.add_option('--SlotOffset-field', dest='SlotOffsetField',metavar='uint',type='int' 710 ,help='Field parameter value [default: %default]') 711 parser.add_option('--MessageID12-field', dest='MessageID12Field',metavar='uint',type='int' 712 ,help='Field parameter value [default: %default]') 713 parser.add_option('--SlotOffset12-field', dest='SlotOffset12Field',metavar='uint',type='int' 714 ,help='Field parameter value [default: %default]') 715 parser.add_option('--DestID2-field', dest='DestID2Field',metavar='uint',type='int' 716 ,help='Field parameter value [default: %default]') 717 parser.add_option('--MessageID2-field', dest='MessageID2Field',metavar='uint',type='int' 718 ,help='Field parameter value [default: %default]') 719 parser.add_option('--SlotOffset2-field', dest='SlotOffset2Field',metavar='uint',type='int' 720 ,help='Field parameter value [default: %default]')
721 722 ############################################################ 723 if __name__=='__main__': 724 725 from optparse import OptionParser 726 parser = OptionParser(usage="%prog [options]", 727 version="%prog "+__version__) 728 729 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 730 help='run the documentation tests') 731 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 732 help='run the unit tests') 733 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 734 help='Make the test output verbose') 735 736 # FIX: remove nmea from binary messages. No way to build the whole packet? 737 # FIX: or build the surrounding msg 8 for a broadcast? 738 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 739 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 740 ,default='nmeapayload' 741 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 742 743 744 outputChoices = ('std','html','csv','sql' ) 745 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 746 ,default='std' 747 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 748 749 parser.add_option('-o','--output',dest='outputFileName',default=None, 750 help='Name of the python file to write [default: stdout]') 751 752 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 753 choices=fieldList, 754 help='Which fields to include in the output. Currently only for csv output [default: all]') 755 756 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 757 help='Print the field name for csv') 758 759 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 760 help='Print out an sql create command for the table.') 761 762 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 763 help='Print a LaTeX table of the type') 764 765 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true', 766 help='Print delimited table of the type (for Word table importing)') 767 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t' 768 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)') 769 770 771 dbChoices = ('sqlite','postgres') 772 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 773 ,choices=dbChoices,type='choice' 774 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 775 776 addMsgOptions(parser) 777 778 (options,args) = parser.parse_args() 779 success=True 780 781 if options.doctest: 782 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 783 sys.argv= [sys.argv[0]] 784 if options.verbose: sys.argv.append('-v') 785 import doctest 786 numfail,numtests=doctest.testmod() 787 if numfail==0: print 'ok' 788 else: 789 print 'FAILED' 790 success=False 791 792 if not success: sys.exit('Something Failed') 793 del success # Hide success from epydoc 794 795 if options.unittest: 796 sys.argv = [sys.argv[0]] 797 if options.verbose: sys.argv.append('-v') 798 unittest.main() 799 800 outfile = sys.stdout 801 if None!=options.outputFileName: 802 outfile = file(options.outputFileName,'w') 803 804 805 if options.doEncode: 806 # First make sure all non required options are specified 807 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 808 if None==options.UserIDField: parser.error("missing value for UserIDField") 809 if None==options.DestIDField: parser.error("missing value for DestIDField") 810 if None==options.MessageID1Field: parser.error("missing value for MessageID1Field") 811 if None==options.SlotOffsetField: parser.error("missing value for SlotOffsetField") 812 if None==options.MessageID12Field: parser.error("missing value for MessageID12Field") 813 if None==options.SlotOffset12Field: parser.error("missing value for SlotOffset12Field") 814 if None==options.DestID2Field: parser.error("missing value for DestID2Field") 815 if None==options.MessageID2Field: parser.error("missing value for MessageID2Field") 816 if None==options.SlotOffset2Field: parser.error("missing value for SlotOffset2Field") 817 msgDict={ 818 'MessageID': '15', 819 'RepeatIndicator': options.RepeatIndicatorField, 820 'UserID': options.UserIDField, 821 'DestID': options.DestIDField, 822 'MessageID1': options.MessageID1Field, 823 'SlotOffset': options.SlotOffsetField, 824 'Spare': '0', 825 'MessageID12': options.MessageID12Field, 826 'SlotOffset12': options.SlotOffset12Field, 827 'Spare2': '0', 828 'DestID2': options.DestID2Field, 829 'MessageID2': options.MessageID2Field, 830 'SlotOffset2': options.SlotOffset2Field, 831 'Spare3': '0', 832 } 833 834 bits = encode(msgDict) 835 if 'binary'==options.ioType: print str(bits) 836 elif 'nmeapayload'==options.ioType: 837 # FIX: figure out if this might be necessary at compile time 838 print "bitLen",len(bits) 839 bitLen=len(bits) 840 if bitLen%6!=0: 841 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 842 print "result:",binary.bitvectoais6(bits)[0] 843 844 845 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 846 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 847 else: sys.exit('ERROR: unknown ioType. Help!') 848 849 850 if options.sqlCreate: 851 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 852 853 if options.latexDefinitionTable: 854 latexDefinitionTable(outfile) 855 856 # For conversion to word tables 857 if options.textDefinitionTable: 858 textDefinitionTable(outfile,options.delimTextDefinitionTable) 859 860 if options.printCsvfieldList: 861 # Make a csv separated list of fields that will be displayed for csv 862 if None == options.fieldList: options.fieldList = fieldList 863 import StringIO 864 buf = StringIO.StringIO() 865 for field in options.fieldList: 866 buf.write(field+',') 867 result = buf.getvalue() 868 if result[-1] == ',': print result[:-1] 869 else: print result 870 871 if options.doDecode: 872 if len(args)==0: args = sys.stdin 873 for msg in args: 874 bv = None 875 876 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 877 # Found nmea 878 # FIX: do checksum 879 bv = binary.ais6tobitvec(msg.split(',')[5]) 880 else: # either binary or nmeapayload... expect mostly nmeapayloads 881 # assumes that an all 0 and 1 string can not be a nmeapayload 882 binaryMsg=True 883 for c in msg: 884 if c not in ('0','1'): 885 binaryMsg=False 886 break 887 if binaryMsg: 888 bv = BitVector(bitstring=msg) 889 else: # nmeapayload 890 bv = binary.ais6tobitvec(msg) 891 892 printFields(decode(bv) 893 ,out=outfile 894 ,format=options.outputType 895 ,fieldList=options.fieldList 896 ,dbType=options.dbType 897 ) 898