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-31 $'.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): FIX: find the description 124 - power(uint): FIX: put in a description 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): FIX: put in a description 130 - ChanABandwidth(uint): FIX: put in a description 131 - ChanBBandwidth(uint): FIX: put in a description 132 - TransZoneSize(uint): FIX: put in a description 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): FIX: find the description 188 - power(uint): FIX: put in a description 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): FIX: put in a description 194 - ChanABandwidth(uint): FIX: put in a description 195 - ChanBBandwidth(uint): FIX: put in a description 196 - TransZoneSize(uint): FIX: put in a description 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): FIX: find the description 464 - power(uint): FIX: put in a description 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): FIX: put in a description 470 - ChanABandwidth(uint): FIX: put in a description 471 - ChanBBandwidth(uint): FIX: put in a description 472 - TransZoneSize(uint): FIX: put in a description 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 # FIX: should this sqlCreate be the same as in LaTeX (createFuncName) rather than hard coded? 626 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
627
628 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
629 ''' 630 Return the sqlhelp object to create the table. 631 632 @param fields: which fields to put in the create. Defaults to all. 633 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields 634 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format 635 @type addCoastGuardFields: bool 636 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres') 637 @return: An object that can be used to generate a return 638 @rtype: sqlhelp.create 639 ''' 640 if None == fields: fields = fieldList 641 import sqlhelp 642 c = sqlhelp.create('ChanMngmt',dbType=dbType) 643 c.addPrimaryKey() 644 if 'MessageID' in fields: c.addInt ('MessageID') 645 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator') 646 if 'UserID' in fields: c.addInt ('UserID') 647 if 'Spare' in fields: c.addInt ('Spare') 648 if 'ChanA' in fields: c.addInt ('ChanA') 649 if 'ChanB' in fields: c.addInt ('ChanB') 650 if 'TxRxMode' in fields: c.addInt ('TxRxMode') 651 if 'power' in fields: c.addInt ('power') 652 if dbType != 'postgres': 653 if 'corner1_lon' in fields: c.addDecimal('corner1_lon',5,2) 654 if dbType != 'postgres': 655 if 'corner1_lat' in fields: c.addDecimal('corner1_lat',5,2) 656 if dbType != 'postgres': 657 if 'corner2_lon' in fields: c.addDecimal('corner2_lon',5,2) 658 if dbType != 'postgres': 659 if 'corner2_lat' in fields: c.addDecimal('corner2_lat',5,2) 660 if 'IndicatorType' in fields: c.addInt ('IndicatorType') 661 if 'ChanABandwidth' in fields: c.addInt ('ChanABandwidth') 662 if 'ChanBBandwidth' in fields: c.addInt ('ChanBBandwidth') 663 if 'TransZoneSize' in fields: c.addInt ('TransZoneSize') 664 if 'Spare' in fields: c.addInt ('Spare') 665 666 if addCoastGuardFields: 667 # c.addInt('cg_rssi') # Relative signal strength indicator 668 # c.addInt('cg_d') # dBm receive strength 669 # c.addInt('cg_T') # Receive timestamp from the AIS equipment 670 # c.addInt('cg_S') # Slot received in 671 # c.addVarChar('cg_x',10) # Idonno 672 c.addVarChar('cg_r',15) # Receiver station ID - should usually be an MMSI, but sometimes is a string 673 c.addInt('cg_sec') # UTC seconds since the epoch 674 675 c.addTimestamp('cg_timestamp') # UTC decoded cg_sec - not actually in the data stream 676 677 if dbType == 'postgres': 678 c.addPostGIS('corner1','POINT',2); 679 c.addPostGIS('corner2','POINT',2); 680 681 return c
682
683 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
684 ''' 685 Return the SQL INSERT command for this message type 686 @param params: dictionary of values keyed by field name 687 @param outfile: file like object to print to. 688 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields 689 @return: sql create string 690 @rtype: str 691 692 @see: sqlCreate 693 ''' 694 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
695 696
697 -def sqlInsert(params,extraParams=None,dbType='postgres'):
698 ''' 699 Give the SQL INSERT statement 700 @param params: dict keyed by field name of values 701 @param extraParams: any extra fields that you have created beyond the normal ais message fields 702 @rtype: sqlhelp.insert 703 @return: insert class instance 704 @todo: allow optional type checking of params? 705 @warning: this will take invalid keys happily and do what??? 706 ''' 707 import sqlhelp 708 i = sqlhelp.insert('ChanMngmt',dbType=dbType) 709 710 if dbType=='postgres': 711 finished = [] 712 for key in params: 713 if key in finished: 714 continue 715 716 if key not in toPgFields and key not in fromPgFields: 717 if type(params[key])==Decimal: i.add(key,float(params[key])) 718 else: i.add(key,params[key]) 719 else: 720 if key in fromPgFields: 721 val = params[key] 722 # Had better be a WKT type like POINT(-88.1 30.321) 723 i.addPostGIS(key,val) 724 finished.append(key) 725 else: 726 # Need to construct the type. 727 pgName = toPgFields[key] 728 #valStr='GeomFromText(\''+pgTypes[pgName]+'(' 729 valStr=pgTypes[pgName]+'(' 730 vals = [] 731 for nonPgKey in fromPgFields[pgName]: 732 vals.append(str(params[nonPgKey])) 733 finished.append(nonPgKey) 734 valStr+=' '.join(vals)+')' 735 i.addPostGIS(pgName,valStr) 736 else: 737 for key in params: 738 if type(params[key])==Decimal: i.add(key,float(params[key])) 739 else: i.add(key,params[key]) 740 741 if None != extraParams: 742 for key in extraParams: 743 i.add(key,extraParams[key]) 744 745 return i
746 747 ###################################################################### 748 # LATEX SUPPORT 749 ###################################################################### 750
751 -def latexDefinitionTable(outfile=sys.stdout 752 ):
753 ''' 754 Return the LaTeX definition table for this message type 755 @param outfile: file like object to print to. 756 @type outfile: file obj 757 @return: LaTeX table string via the outfile 758 @rtype: str 759 760 ''' 761 o = outfile 762 763 o.write(''' 764 \\begin{table}%[htb] 765 \\centering 766 \\begin{tabular}{|l|c|l|} 767 \\hline 768 Parameter & Number of bits & Description 769 \\\\ \\hline\\hline 770 MessageID & 6 & AIS message number. Must be 22 \\\\ \hline 771 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline 772 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline 773 Spare & 2 & Not used. Should be set to zero. \\\\ \hline 774 ChanA & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline 775 ChanB & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline 776 TxRxMode & 4 & FIX: find the description \\\\ \hline 777 power & 1 & FIX: put in a description \\\\ \hline 778 corner1\_lon & 18 & north-east corner of area for assignment longitude of corner \\\\ \hline 779 corner1\_lat & 17 & north-east corner of area for assignment latitude of corner \\\\ \hline 780 corner2\_lon & 18 & south-west corner of area for assignment longitude of corner \\\\ \hline 781 corner2\_lat & 17 & south-west corner of area for assignment latitude of corner \\\\ \hline 782 IndicatorType & 1 & FIX: put in a description \\\\ \hline 783 ChanABandwidth & 1 & FIX: put in a description \\\\ \hline 784 ChanBBandwidth & 1 & FIX: put in a description \\\\ \hline 785 TransZoneSize & 3 & FIX: put in a description \\\\ \hline 786 Spare & 23 & Not used. Should be set to zero.\\\\ \\hline \\hline 787 Total bits & 168 & Appears to take 1 slot \\\\ \\hline 788 \\end{tabular} 789 \\caption{AIS message number 22: Base station report - F} 790 \\label{tab:ChanMngmt} 791 \\end{table} 792 ''')
793 794 795 ###################################################################### 796 # UNIT TESTING 797 ###################################################################### 798 import unittest
799 -def testParams():
800 '''Return a params file base on the testvalue tags. 801 @rtype: dict 802 @return: params based on testvalue tags 803 ''' 804 params = {} 805 params['MessageID'] = 22 806 params['RepeatIndicator'] = 1 807 params['UserID'] = 1193046 808 params['Spare'] = 0 809 params['ChanA'] = 0 810 params['ChanB'] = 0 811 params['TxRxMode'] = 1 812 params['power'] = 1 813 params['corner1_lon'] = Decimal('-122.16') 814 params['corner1_lat'] = Decimal('37.42') 815 params['corner2_lon'] = Decimal('-122.16') 816 params['corner2_lat'] = Decimal('37.42') 817 params['IndicatorType'] = 1 818 params['ChanABandwidth'] = 1 819 params['ChanBBandwidth'] = 1 820 params['TransZoneSize'] = 1 821 params['Spare'] = 0 822 823 return params
824
825 -class TestChanMngmt(unittest.TestCase):
826 '''Use testvalue tag text from each type to build test case the ChanMngmt message'''
827 - def testEncodeDecode(self):
828 829 params = testParams() 830 bits = encode(params) 831 r = decode(bits) 832 833 # Check that each parameter came through ok. 834 self.failUnlessEqual(r['MessageID'],params['MessageID']) 835 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator']) 836 self.failUnlessEqual(r['UserID'],params['UserID']) 837 self.failUnlessEqual(r['Spare'],params['Spare']) 838 self.failUnlessEqual(r['ChanA'],params['ChanA']) 839 self.failUnlessEqual(r['ChanB'],params['ChanB']) 840 self.failUnlessEqual(r['TxRxMode'],params['TxRxMode']) 841 self.failUnlessEqual(r['power'],params['power']) 842 self.failUnlessAlmostEqual(r['corner1_lon'],params['corner1_lon'],2) 843 self.failUnlessAlmostEqual(r['corner1_lat'],params['corner1_lat'],2) 844 self.failUnlessAlmostEqual(r['corner2_lon'],params['corner2_lon'],2) 845 self.failUnlessAlmostEqual(r['corner2_lat'],params['corner2_lat'],2) 846 self.failUnlessEqual(r['IndicatorType'],params['IndicatorType']) 847 self.failUnlessEqual(r['ChanABandwidth'],params['ChanABandwidth']) 848 self.failUnlessEqual(r['ChanBBandwidth'],params['ChanBBandwidth']) 849 self.failUnlessEqual(r['TransZoneSize'],params['TransZoneSize']) 850 self.failUnlessEqual(r['Spare'],params['Spare'])
851
852 -def addMsgOptions(parser):
853 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true', 854 help='decode a "ChanMngmt" AIS message') 855 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true', 856 help='encode a "ChanMngmt" AIS message') 857 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int' 858 ,help='Field parameter value [default: %default]') 859 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int' 860 ,help='Field parameter value [default: %default]') 861 parser.add_option('--ChanA-field', dest='ChanAField',metavar='uint',type='int' 862 ,help='Field parameter value [default: %default]') 863 parser.add_option('--ChanB-field', dest='ChanBField',metavar='uint',type='int' 864 ,help='Field parameter value [default: %default]') 865 parser.add_option('--TxRxMode-field', dest='TxRxModeField',metavar='uint',type='int' 866 ,help='Field parameter value [default: %default]') 867 parser.add_option('--power-field', dest='powerField',metavar='uint',type='int' 868 ,help='Field parameter value [default: %default]') 869 parser.add_option('--corner1_lon-field', dest='corner1_lonField',default=Decimal('181'),metavar='decimal',type='string' 870 ,help='Field parameter value [default: %default]') 871 parser.add_option('--corner1_lat-field', dest='corner1_latField',default=Decimal('181'),metavar='decimal',type='string' 872 ,help='Field parameter value [default: %default]') 873 parser.add_option('--corner2_lon-field', dest='corner2_lonField',default=Decimal('181'),metavar='decimal',type='string' 874 ,help='Field parameter value [default: %default]') 875 parser.add_option('--corner2_lat-field', dest='corner2_latField',default=Decimal('181'),metavar='decimal',type='string' 876 ,help='Field parameter value [default: %default]') 877 parser.add_option('--IndicatorType-field', dest='IndicatorTypeField',metavar='uint',type='int' 878 ,help='Field parameter value [default: %default]') 879 parser.add_option('--ChanABandwidth-field', dest='ChanABandwidthField',metavar='uint',type='int' 880 ,help='Field parameter value [default: %default]') 881 parser.add_option('--ChanBBandwidth-field', dest='ChanBBandwidthField',metavar='uint',type='int' 882 ,help='Field parameter value [default: %default]') 883 parser.add_option('--TransZoneSize-field', dest='TransZoneSizeField',metavar='uint',type='int' 884 ,help='Field parameter value [default: %default]')
885 886 ############################################################ 887 if __name__=='__main__': 888 889 from optparse import OptionParser 890 parser = OptionParser(usage="%prog [options]", 891 version="%prog "+__version__) 892 893 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true', 894 help='run the documentation tests') 895 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true', 896 help='run the unit tests') 897 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true', 898 help='Make the test output verbose') 899 900 # FIX: remove nmea from binary messages. No way to build the whole packet? 901 # FIX: or build the surrounding msg 8 for a broadcast? 902 typeChoices = ('binary','nmeapayload','nmea') # FIX: what about a USCG type message? 903 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType' 904 ,default='nmeapayload' 905 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]') 906 907 908 outputChoices = ('std','html','csv','sql' ) 909 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType' 910 ,default='std' 911 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]') 912 913 parser.add_option('-o','--output',dest='outputFileName',default=None, 914 help='Name of the python file to write [default: stdout]') 915 916 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append', 917 choices=fieldList, 918 help='Which fields to include in the output. Currently only for csv output [default: all]') 919 920 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true', 921 help='Print the field name for csv') 922 923 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true', 924 help='Print out an sql create command for the table.') 925 926 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true', 927 help='Print a LaTeX table of the type') 928 929 dbChoices = ('sqlite','postgres') 930 parser.add_option('-D','--db-type',dest='dbType',default='postgres' 931 ,choices=dbChoices,type='choice' 932 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]') 933 934 addMsgOptions(parser) 935 936 (options,args) = parser.parse_args() 937 success=True 938 939 if options.doctest: 940 import os; print os.path.basename(sys.argv[0]), 'doctests ...', 941 sys.argv= [sys.argv[0]] 942 if options.verbose: sys.argv.append('-v') 943 import doctest 944 numfail,numtests=doctest.testmod() 945 if numfail==0: print 'ok' 946 else: 947 print 'FAILED' 948 success=False 949 950 if not success: sys.exit('Something Failed') 951 del success # Hide success from epydoc 952 953 if options.unittest: 954 sys.argv = [sys.argv[0]] 955 if options.verbose: sys.argv.append('-v') 956 unittest.main() 957 958 outfile = sys.stdout 959 if None!=options.outputFileName: 960 outfile = file(options.outputFileName,'w') 961 962 963 if options.doEncode: 964 # First make sure all non required options are specified 965 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField") 966 if None==options.UserIDField: parser.error("missing value for UserIDField") 967 if None==options.ChanAField: parser.error("missing value for ChanAField") 968 if None==options.ChanBField: parser.error("missing value for ChanBField") 969 if None==options.TxRxModeField: parser.error("missing value for TxRxModeField") 970 if None==options.powerField: parser.error("missing value for powerField") 971 if None==options.corner1_lonField: parser.error("missing value for corner1_lonField") 972 if None==options.corner1_latField: parser.error("missing value for corner1_latField") 973 if None==options.corner2_lonField: parser.error("missing value for corner2_lonField") 974 if None==options.corner2_latField: parser.error("missing value for corner2_latField") 975 if None==options.IndicatorTypeField: parser.error("missing value for IndicatorTypeField") 976 if None==options.ChanABandwidthField: parser.error("missing value for ChanABandwidthField") 977 if None==options.ChanBBandwidthField: parser.error("missing value for ChanBBandwidthField") 978 if None==options.TransZoneSizeField: parser.error("missing value for TransZoneSizeField") 979 msgDict={ 980 'MessageID': '22', 981 'RepeatIndicator': options.RepeatIndicatorField, 982 'UserID': options.UserIDField, 983 'Spare': '0', 984 'ChanA': options.ChanAField, 985 'ChanB': options.ChanBField, 986 'TxRxMode': options.TxRxModeField, 987 'power': options.powerField, 988 'corner1_lon': options.corner1_lonField, 989 'corner1_lat': options.corner1_latField, 990 'corner2_lon': options.corner2_lonField, 991 'corner2_lat': options.corner2_latField, 992 'IndicatorType': options.IndicatorTypeField, 993 'ChanABandwidth': options.ChanABandwidthField, 994 'ChanBBandwidth': options.ChanBBandwidthField, 995 'TransZoneSize': options.TransZoneSizeField, 996 'Spare': '0', 997 } 998 999 bits = encode(msgDict) 1000 if 'binary'==options.ioType: print str(bits) 1001 elif 'nmeapayload'==options.ioType: 1002 # FIX: figure out if this might be necessary at compile time 1003 print "bitLen",len(bits) 1004 bitLen=len(bits) 1005 if bitLen%6!=0: 1006 bits = bits + BitVector(size=(6 - (bitLen%6))) # Pad out to multiple of 6 1007 print "result:",binary.bitvectoais6(bits)[0] 1008 1009 1010 # FIX: Do not emit this option for the binary message payloads. Does not make sense. 1011 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability") 1012 else: sys.exit('ERROR: unknown ioType. Help!') 1013 1014 1015 if options.sqlCreate: 1016 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType) 1017 1018 if options.latexDefinitionTable: 1019 latexDefinitionTable(outfile) 1020 1021 if options.printCsvfieldList: 1022 # Make a csv separated list of fields that will be displayed for csv 1023 if None == options.fieldList: options.fieldList = fieldList 1024 import StringIO 1025 buf = StringIO.StringIO() 1026 for field in options.fieldList: 1027 buf.write(field+',') 1028 result = buf.getvalue() 1029 if result[-1] == ',': print result[:-1] 1030 else: print result 1031 1032 if options.doDecode: 1033 for msg in args: 1034 bv = None 1035 1036 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'): 1037 # Found nmea 1038 # FIX: do checksum 1039 bv = binary.ais6tobitvec(msg.split(',')[5]) 1040 else: # either binary or nmeapayload... expect mostly nmeapayloads 1041 # assumes that an all 0 and 1 string can not be a nmeapayload 1042 binaryMsg=True 1043 for c in msg: 1044 if c not in ('0','1'): 1045 binaryMsg=False 1046 break 1047 if binaryMsg: 1048 bv = BitVector(bitstring=msg) 1049 else: # nmeapayload 1050 bv = binary.ais6tobitvec(msg) 1051 1052 printFields(decode(bv) 1053 ,out=outfile 1054 ,format=options.outputType 1055 ,fieldList=options.fieldList 1056 ,dbType=options.dbType 1057 ) 1058