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

Source Code for Module ais.ais_msg_22

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