1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-12-04 $'.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
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',
79 'corner2',
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
206
207
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
230
233
236
239
241 return int(bv[40:52])
242
244 return int(bv[52:64])
245
247 return int(bv[64:68])
248
250 return int(bv[68:69])
251
254
257
260
263
265 return int(bv[139:140])
266
268 return int(bv[140:141])
269
271 return int(bv[141:142])
272
274 return int(bv[142:145])
275
278
279
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
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
519
520 RepeatIndicatorEncodeLut = {
521 'default':'0',
522 'do not repeat any more':'3',
523 }
524
525 RepeatIndicatorDecodeLut = {
526 '0':'default',
527 '3':'do not repeat any more',
528 }
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 }
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 }
541
542 powerEncodeLut = {
543 'high':'0',
544 'low':'1',
545 }
546
547 powerDecodeLut = {
548 '0':'high',
549 '1':'low',
550 }
551
552 IndicatorTypeEncodeLut = {
553 'broadcast':'0',
554 'addressed':'1',
555 }
556
557 IndicatorTypeDecodeLut = {
558 '0':'broadcast',
559 '1':'addressed',
560 }
561
562 ChanABandwidthEncodeLut = {
563 'specified by channel number':'0',
564 '12.5kHz':'1',
565 }
566
567 ChanABandwidthDecodeLut = {
568 '0':'specified by channel number',
569 '1':'12.5kHz',
570 }
571
572 ChanBBandwidthEncodeLut = {
573 'specified by channel number':'0',
574 '12.5kHz':'1',
575 }
576
577 ChanBBandwidthDecodeLut = {
578 '0':'specified by channel number',
579 '1':'12.5kHz',
580 }
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 }
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 }
603
604
605
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
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
668
669
670
671
672 c.addVarChar('cg_r',15)
673 c.addInt('cg_sec')
674
675 c.addTimestamp('cg_timestamp')
676
677 if dbType == 'postgres':
678
679
680 c.addPostGIS('corner1','POINT',2,SRID=4326);
681
682
683 c.addPostGIS('corner2','POINT',2,SRID=4326);
684
685 return c
686
687 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
688 '''
689 Return the SQL INSERT command for this message type
690 @param params: dictionary of values keyed by field name
691 @param outfile: file like object to print to.
692 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
693 @return: sql create string
694 @rtype: str
695
696 @see: sqlCreate
697 '''
698 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
699
700
701 -def sqlInsert(params,extraParams=None,dbType='postgres'):
702 '''
703 Give the SQL INSERT statement
704 @param params: dict keyed by field name of values
705 @param extraParams: any extra fields that you have created beyond the normal ais message fields
706 @rtype: sqlhelp.insert
707 @return: insert class instance
708 @todo: allow optional type checking of params?
709 @warning: this will take invalid keys happily and do what???
710 '''
711 import sqlhelp
712 i = sqlhelp.insert('ChanMngmt',dbType=dbType)
713
714 if dbType=='postgres':
715 finished = []
716 for key in params:
717 if key in finished:
718 continue
719
720 if key not in toPgFields and key not in fromPgFields:
721 if type(params[key])==Decimal: i.add(key,float(params[key]))
722 else: i.add(key,params[key])
723 else:
724 if key in fromPgFields:
725 val = params[key]
726
727 i.addPostGIS(key,val)
728 finished.append(key)
729 else:
730
731 pgName = toPgFields[key]
732
733 valStr=pgTypes[pgName]+'('
734 vals = []
735 for nonPgKey in fromPgFields[pgName]:
736 vals.append(str(params[nonPgKey]))
737 finished.append(nonPgKey)
738 valStr+=' '.join(vals)+')'
739 i.addPostGIS(pgName,valStr)
740 else:
741 for key in params:
742 if type(params[key])==Decimal: i.add(key,float(params[key]))
743 else: i.add(key,params[key])
744
745 if None != extraParams:
746 for key in extraParams:
747 i.add(key,extraParams[key])
748
749 return i
750
751
752
753
754
757 '''
758 Return the LaTeX definition table for this message type
759 @param outfile: file like object to print to.
760 @type outfile: file obj
761 @return: LaTeX table string via the outfile
762 @rtype: str
763
764 '''
765 o = outfile
766
767 o.write('''
768 \\begin{table}%[htb]
769 \\centering
770 \\begin{tabular}{|l|c|l|}
771 \\hline
772 Parameter & Number of bits & Description
773 \\\\ \\hline\\hline
774 MessageID & 6 & AIS message number. Must be 22 \\\\ \hline
775 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
776 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
777 Spare & 2 & Not used. Should be set to zero. \\\\ \hline
778 ChanA & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline
779 ChanB & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline
780 TxRxMode & 4 & FIX: find the description \\\\ \hline
781 power & 1 & FIX: put in a description \\\\ \hline
782 corner1\_lon & 18 & north-east corner of area for assignment longitude of corner \\\\ \hline
783 corner1\_lat & 17 & north-east corner of area for assignment latitude of corner \\\\ \hline
784 corner2\_lon & 18 & south-west corner of area for assignment longitude of corner \\\\ \hline
785 corner2\_lat & 17 & south-west corner of area for assignment latitude of corner \\\\ \hline
786 IndicatorType & 1 & FIX: put in a description \\\\ \hline
787 ChanABandwidth & 1 & FIX: put in a description \\\\ \hline
788 ChanBBandwidth & 1 & FIX: put in a description \\\\ \hline
789 TransZoneSize & 3 & FIX: put in a description \\\\ \hline
790 Spare & 23 & Not used. Should be set to zero.\\\\ \\hline \\hline
791 Total bits & 168 & Appears to take 1 slot \\\\ \\hline
792 \\end{tabular}
793 \\caption{AIS message number 22: Base station report - F}
794 \\label{tab:ChanMngmt}
795 \\end{table}
796 ''')
797
798
799
800
801
802 -def textDefinitionTable(outfile=sys.stdout
803 ,delim='\t'
804 ):
805 '''
806 Return the text definition table for this message type
807 @param outfile: file like object to print to.
808 @type outfile: file obj
809 @return: text table string via the outfile
810 @rtype: str
811
812 '''
813 o = outfile
814 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
815 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 22
816 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
817 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
818 Spare'''+delim+'''2'''+delim+'''Not used. Should be set to zero.
819 ChanA'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
820 ChanB'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
821 TxRxMode'''+delim+'''4'''+delim+'''FIX: find the description
822 power'''+delim+'''1'''+delim+'''FIX: put in a description
823 corner1_lon'''+delim+'''18'''+delim+'''north-east corner of area for assignment longitude of corner
824 corner1_lat'''+delim+'''17'''+delim+'''north-east corner of area for assignment latitude of corner
825 corner2_lon'''+delim+'''18'''+delim+'''south-west corner of area for assignment longitude of corner
826 corner2_lat'''+delim+'''17'''+delim+'''south-west corner of area for assignment latitude of corner
827 IndicatorType'''+delim+'''1'''+delim+'''FIX: put in a description
828 ChanABandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
829 ChanBBandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
830 TransZoneSize'''+delim+'''3'''+delim+'''FIX: put in a description
831 Spare'''+delim+'''23'''+delim+'''Not used. Should be set to zero.
832 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
833
834
835
836
837
838 import unittest
840 '''Return a params file base on the testvalue tags.
841 @rtype: dict
842 @return: params based on testvalue tags
843 '''
844 params = {}
845 params['MessageID'] = 22
846 params['RepeatIndicator'] = 1
847 params['UserID'] = 1193046
848 params['Spare'] = 0
849 params['ChanA'] = 0
850 params['ChanB'] = 0
851 params['TxRxMode'] = 1
852 params['power'] = 1
853 params['corner1_lon'] = Decimal('-122.16')
854 params['corner1_lat'] = Decimal('37.42')
855 params['corner2_lon'] = Decimal('-122.16')
856 params['corner2_lat'] = Decimal('37.42')
857 params['IndicatorType'] = 1
858 params['ChanABandwidth'] = 1
859 params['ChanBBandwidth'] = 1
860 params['TransZoneSize'] = 1
861 params['Spare'] = 0
862
863 return params
864
866 '''Use testvalue tag text from each type to build test case the ChanMngmt message'''
868
869 params = testParams()
870 bits = encode(params)
871 r = decode(bits)
872
873
874 self.failUnlessEqual(r['MessageID'],params['MessageID'])
875 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
876 self.failUnlessEqual(r['UserID'],params['UserID'])
877 self.failUnlessEqual(r['Spare'],params['Spare'])
878 self.failUnlessEqual(r['ChanA'],params['ChanA'])
879 self.failUnlessEqual(r['ChanB'],params['ChanB'])
880 self.failUnlessEqual(r['TxRxMode'],params['TxRxMode'])
881 self.failUnlessEqual(r['power'],params['power'])
882 self.failUnlessAlmostEqual(r['corner1_lon'],params['corner1_lon'],2)
883 self.failUnlessAlmostEqual(r['corner1_lat'],params['corner1_lat'],2)
884 self.failUnlessAlmostEqual(r['corner2_lon'],params['corner2_lon'],2)
885 self.failUnlessAlmostEqual(r['corner2_lat'],params['corner2_lat'],2)
886 self.failUnlessEqual(r['IndicatorType'],params['IndicatorType'])
887 self.failUnlessEqual(r['ChanABandwidth'],params['ChanABandwidth'])
888 self.failUnlessEqual(r['ChanBBandwidth'],params['ChanBBandwidth'])
889 self.failUnlessEqual(r['TransZoneSize'],params['TransZoneSize'])
890 self.failUnlessEqual(r['Spare'],params['Spare'])
891
893 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
894 help='decode a "ChanMngmt" AIS message')
895 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
896 help='encode a "ChanMngmt" AIS message')
897 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
898 ,help='Field parameter value [default: %default]')
899 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
900 ,help='Field parameter value [default: %default]')
901 parser.add_option('--ChanA-field', dest='ChanAField',metavar='uint',type='int'
902 ,help='Field parameter value [default: %default]')
903 parser.add_option('--ChanB-field', dest='ChanBField',metavar='uint',type='int'
904 ,help='Field parameter value [default: %default]')
905 parser.add_option('--TxRxMode-field', dest='TxRxModeField',metavar='uint',type='int'
906 ,help='Field parameter value [default: %default]')
907 parser.add_option('--power-field', dest='powerField',metavar='uint',type='int'
908 ,help='Field parameter value [default: %default]')
909 parser.add_option('--corner1_lon-field', dest='corner1_lonField',default=Decimal('181'),metavar='decimal',type='string'
910 ,help='Field parameter value [default: %default]')
911 parser.add_option('--corner1_lat-field', dest='corner1_latField',default=Decimal('181'),metavar='decimal',type='string'
912 ,help='Field parameter value [default: %default]')
913 parser.add_option('--corner2_lon-field', dest='corner2_lonField',default=Decimal('181'),metavar='decimal',type='string'
914 ,help='Field parameter value [default: %default]')
915 parser.add_option('--corner2_lat-field', dest='corner2_latField',default=Decimal('181'),metavar='decimal',type='string'
916 ,help='Field parameter value [default: %default]')
917 parser.add_option('--IndicatorType-field', dest='IndicatorTypeField',metavar='uint',type='int'
918 ,help='Field parameter value [default: %default]')
919 parser.add_option('--ChanABandwidth-field', dest='ChanABandwidthField',metavar='uint',type='int'
920 ,help='Field parameter value [default: %default]')
921 parser.add_option('--ChanBBandwidth-field', dest='ChanBBandwidthField',metavar='uint',type='int'
922 ,help='Field parameter value [default: %default]')
923 parser.add_option('--TransZoneSize-field', dest='TransZoneSizeField',metavar='uint',type='int'
924 ,help='Field parameter value [default: %default]')
925
926
927 if __name__=='__main__':
928
929 from optparse import OptionParser
930 parser = OptionParser(usage="%prog [options]",
931 version="%prog "+__version__)
932
933 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
934 help='run the documentation tests')
935 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
936 help='run the unit tests')
937 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
938 help='Make the test output verbose')
939
940
941
942 typeChoices = ('binary','nmeapayload','nmea')
943 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
944 ,default='nmeapayload'
945 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
946
947
948 outputChoices = ('std','html','csv','sql' )
949 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
950 ,default='std'
951 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
952
953 parser.add_option('-o','--output',dest='outputFileName',default=None,
954 help='Name of the python file to write [default: stdout]')
955
956 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
957 choices=fieldList,
958 help='Which fields to include in the output. Currently only for csv output [default: all]')
959
960 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
961 help='Print the field name for csv')
962
963 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
964 help='Print out an sql create command for the table.')
965
966 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
967 help='Print a LaTeX table of the type')
968
969 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
970 help='Print delimited table of the type (for Word table importing)')
971 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
972 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
973
974
975 dbChoices = ('sqlite','postgres')
976 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
977 ,choices=dbChoices,type='choice'
978 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
979
980 addMsgOptions(parser)
981
982 (options,args) = parser.parse_args()
983 success=True
984
985 if options.doctest:
986 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
987 sys.argv= [sys.argv[0]]
988 if options.verbose: sys.argv.append('-v')
989 import doctest
990 numfail,numtests=doctest.testmod()
991 if numfail==0: print 'ok'
992 else:
993 print 'FAILED'
994 success=False
995
996 if not success: sys.exit('Something Failed')
997 del success
998
999 if options.unittest:
1000 sys.argv = [sys.argv[0]]
1001 if options.verbose: sys.argv.append('-v')
1002 unittest.main()
1003
1004 outfile = sys.stdout
1005 if None!=options.outputFileName:
1006 outfile = file(options.outputFileName,'w')
1007
1008
1009 if options.doEncode:
1010
1011 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1012 if None==options.UserIDField: parser.error("missing value for UserIDField")
1013 if None==options.ChanAField: parser.error("missing value for ChanAField")
1014 if None==options.ChanBField: parser.error("missing value for ChanBField")
1015 if None==options.TxRxModeField: parser.error("missing value for TxRxModeField")
1016 if None==options.powerField: parser.error("missing value for powerField")
1017 if None==options.corner1_lonField: parser.error("missing value for corner1_lonField")
1018 if None==options.corner1_latField: parser.error("missing value for corner1_latField")
1019 if None==options.corner2_lonField: parser.error("missing value for corner2_lonField")
1020 if None==options.corner2_latField: parser.error("missing value for corner2_latField")
1021 if None==options.IndicatorTypeField: parser.error("missing value for IndicatorTypeField")
1022 if None==options.ChanABandwidthField: parser.error("missing value for ChanABandwidthField")
1023 if None==options.ChanBBandwidthField: parser.error("missing value for ChanBBandwidthField")
1024 if None==options.TransZoneSizeField: parser.error("missing value for TransZoneSizeField")
1025 msgDict={
1026 'MessageID': '22',
1027 'RepeatIndicator': options.RepeatIndicatorField,
1028 'UserID': options.UserIDField,
1029 'Spare': '0',
1030 'ChanA': options.ChanAField,
1031 'ChanB': options.ChanBField,
1032 'TxRxMode': options.TxRxModeField,
1033 'power': options.powerField,
1034 'corner1_lon': options.corner1_lonField,
1035 'corner1_lat': options.corner1_latField,
1036 'corner2_lon': options.corner2_lonField,
1037 'corner2_lat': options.corner2_latField,
1038 'IndicatorType': options.IndicatorTypeField,
1039 'ChanABandwidth': options.ChanABandwidthField,
1040 'ChanBBandwidth': options.ChanBBandwidthField,
1041 'TransZoneSize': options.TransZoneSizeField,
1042 'Spare': '0',
1043 }
1044
1045 bits = encode(msgDict)
1046 if 'binary'==options.ioType: print str(bits)
1047 elif 'nmeapayload'==options.ioType:
1048
1049 print "bitLen",len(bits)
1050 bitLen=len(bits)
1051 if bitLen%6!=0:
1052 bits = bits + BitVector(size=(6 - (bitLen%6)))
1053 print "result:",binary.bitvectoais6(bits)[0]
1054
1055
1056
1057 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1058 else: sys.exit('ERROR: unknown ioType. Help!')
1059
1060
1061 if options.sqlCreate:
1062 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1063
1064 if options.latexDefinitionTable:
1065 latexDefinitionTable(outfile)
1066
1067
1068 if options.textDefinitionTable:
1069 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1070
1071 if options.printCsvfieldList:
1072
1073 if None == options.fieldList: options.fieldList = fieldList
1074 import StringIO
1075 buf = StringIO.StringIO()
1076 for field in options.fieldList:
1077 buf.write(field+',')
1078 result = buf.getvalue()
1079 if result[-1] == ',': print result[:-1]
1080 else: print result
1081
1082 if options.doDecode:
1083 if len(args)==0: args = sys.stdin
1084 for msg in args:
1085 bv = None
1086
1087 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1088
1089
1090 bv = binary.ais6tobitvec(msg.split(',')[5])
1091 else:
1092
1093 binaryMsg=True
1094 for c in msg:
1095 if c not in ('0','1'):
1096 binaryMsg=False
1097 break
1098 if binaryMsg:
1099 bv = BitVector(bitstring=msg)
1100 else:
1101 bv = binary.ais6tobitvec(msg)
1102
1103 printFields(decode(bv)
1104 ,out=outfile
1105 ,format=options.outputType
1106 ,fieldList=options.fieldList
1107 ,dbType=options.dbType
1108 )
1109