1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-05-01 $'.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 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
723 i.addPostGIS(key,val)
724 finished.append(key)
725 else:
726
727 pgName = toPgFields[key]
728
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
749
750
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
797
798 -def textDefinitionTable(outfile=sys.stdout
799 ,delim='\t'
800 ):
801 '''
802 Return the text definition table for this message type
803 @param outfile: file like object to print to.
804 @type outfile: file obj
805 @return: text table string via the outfile
806 @rtype: str
807
808 '''
809 o = outfile
810 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
811 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 22
812 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
813 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
814 Spare'''+delim+'''2'''+delim+'''Not used. Should be set to zero.
815 ChanA'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
816 ChanB'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
817 TxRxMode'''+delim+'''4'''+delim+'''FIX: find the description
818 power'''+delim+'''1'''+delim+'''FIX: put in a description
819 corner1_lon'''+delim+'''18'''+delim+'''north-east corner of area for assignment longitude of corner
820 corner1_lat'''+delim+'''17'''+delim+'''north-east corner of area for assignment latitude of corner
821 corner2_lon'''+delim+'''18'''+delim+'''south-west corner of area for assignment longitude of corner
822 corner2_lat'''+delim+'''17'''+delim+'''south-west corner of area for assignment latitude of corner
823 IndicatorType'''+delim+'''1'''+delim+'''FIX: put in a description
824 ChanABandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
825 ChanBBandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
826 TransZoneSize'''+delim+'''3'''+delim+'''FIX: put in a description
827 Spare'''+delim+'''23'''+delim+'''Not used. Should be set to zero.
828 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
829
830
831
832
833
834 import unittest
836 '''Return a params file base on the testvalue tags.
837 @rtype: dict
838 @return: params based on testvalue tags
839 '''
840 params = {}
841 params['MessageID'] = 22
842 params['RepeatIndicator'] = 1
843 params['UserID'] = 1193046
844 params['Spare'] = 0
845 params['ChanA'] = 0
846 params['ChanB'] = 0
847 params['TxRxMode'] = 1
848 params['power'] = 1
849 params['corner1_lon'] = Decimal('-122.16')
850 params['corner1_lat'] = Decimal('37.42')
851 params['corner2_lon'] = Decimal('-122.16')
852 params['corner2_lat'] = Decimal('37.42')
853 params['IndicatorType'] = 1
854 params['ChanABandwidth'] = 1
855 params['ChanBBandwidth'] = 1
856 params['TransZoneSize'] = 1
857 params['Spare'] = 0
858
859 return params
860
862 '''Use testvalue tag text from each type to build test case the ChanMngmt message'''
864
865 params = testParams()
866 bits = encode(params)
867 r = decode(bits)
868
869
870 self.failUnlessEqual(r['MessageID'],params['MessageID'])
871 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
872 self.failUnlessEqual(r['UserID'],params['UserID'])
873 self.failUnlessEqual(r['Spare'],params['Spare'])
874 self.failUnlessEqual(r['ChanA'],params['ChanA'])
875 self.failUnlessEqual(r['ChanB'],params['ChanB'])
876 self.failUnlessEqual(r['TxRxMode'],params['TxRxMode'])
877 self.failUnlessEqual(r['power'],params['power'])
878 self.failUnlessAlmostEqual(r['corner1_lon'],params['corner1_lon'],2)
879 self.failUnlessAlmostEqual(r['corner1_lat'],params['corner1_lat'],2)
880 self.failUnlessAlmostEqual(r['corner2_lon'],params['corner2_lon'],2)
881 self.failUnlessAlmostEqual(r['corner2_lat'],params['corner2_lat'],2)
882 self.failUnlessEqual(r['IndicatorType'],params['IndicatorType'])
883 self.failUnlessEqual(r['ChanABandwidth'],params['ChanABandwidth'])
884 self.failUnlessEqual(r['ChanBBandwidth'],params['ChanBBandwidth'])
885 self.failUnlessEqual(r['TransZoneSize'],params['TransZoneSize'])
886 self.failUnlessEqual(r['Spare'],params['Spare'])
887
889 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
890 help='decode a "ChanMngmt" AIS message')
891 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
892 help='encode a "ChanMngmt" AIS message')
893 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
894 ,help='Field parameter value [default: %default]')
895 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
896 ,help='Field parameter value [default: %default]')
897 parser.add_option('--ChanA-field', dest='ChanAField',metavar='uint',type='int'
898 ,help='Field parameter value [default: %default]')
899 parser.add_option('--ChanB-field', dest='ChanBField',metavar='uint',type='int'
900 ,help='Field parameter value [default: %default]')
901 parser.add_option('--TxRxMode-field', dest='TxRxModeField',metavar='uint',type='int'
902 ,help='Field parameter value [default: %default]')
903 parser.add_option('--power-field', dest='powerField',metavar='uint',type='int'
904 ,help='Field parameter value [default: %default]')
905 parser.add_option('--corner1_lon-field', dest='corner1_lonField',default=Decimal('181'),metavar='decimal',type='string'
906 ,help='Field parameter value [default: %default]')
907 parser.add_option('--corner1_lat-field', dest='corner1_latField',default=Decimal('181'),metavar='decimal',type='string'
908 ,help='Field parameter value [default: %default]')
909 parser.add_option('--corner2_lon-field', dest='corner2_lonField',default=Decimal('181'),metavar='decimal',type='string'
910 ,help='Field parameter value [default: %default]')
911 parser.add_option('--corner2_lat-field', dest='corner2_latField',default=Decimal('181'),metavar='decimal',type='string'
912 ,help='Field parameter value [default: %default]')
913 parser.add_option('--IndicatorType-field', dest='IndicatorTypeField',metavar='uint',type='int'
914 ,help='Field parameter value [default: %default]')
915 parser.add_option('--ChanABandwidth-field', dest='ChanABandwidthField',metavar='uint',type='int'
916 ,help='Field parameter value [default: %default]')
917 parser.add_option('--ChanBBandwidth-field', dest='ChanBBandwidthField',metavar='uint',type='int'
918 ,help='Field parameter value [default: %default]')
919 parser.add_option('--TransZoneSize-field', dest='TransZoneSizeField',metavar='uint',type='int'
920 ,help='Field parameter value [default: %default]')
921
922
923 if __name__=='__main__':
924
925 from optparse import OptionParser
926 parser = OptionParser(usage="%prog [options]",
927 version="%prog "+__version__)
928
929 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
930 help='run the documentation tests')
931 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
932 help='run the unit tests')
933 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
934 help='Make the test output verbose')
935
936
937
938 typeChoices = ('binary','nmeapayload','nmea')
939 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
940 ,default='nmeapayload'
941 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
942
943
944 outputChoices = ('std','html','csv','sql' )
945 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
946 ,default='std'
947 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
948
949 parser.add_option('-o','--output',dest='outputFileName',default=None,
950 help='Name of the python file to write [default: stdout]')
951
952 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
953 choices=fieldList,
954 help='Which fields to include in the output. Currently only for csv output [default: all]')
955
956 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
957 help='Print the field name for csv')
958
959 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
960 help='Print out an sql create command for the table.')
961
962 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
963 help='Print a LaTeX table of the type')
964
965 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
966 help='Print delimited table of the type (for Word table importing)')
967 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
968 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
969
970
971 dbChoices = ('sqlite','postgres')
972 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
973 ,choices=dbChoices,type='choice'
974 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
975
976 addMsgOptions(parser)
977
978 (options,args) = parser.parse_args()
979 success=True
980
981 if options.doctest:
982 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
983 sys.argv= [sys.argv[0]]
984 if options.verbose: sys.argv.append('-v')
985 import doctest
986 numfail,numtests=doctest.testmod()
987 if numfail==0: print 'ok'
988 else:
989 print 'FAILED'
990 success=False
991
992 if not success: sys.exit('Something Failed')
993 del success
994
995 if options.unittest:
996 sys.argv = [sys.argv[0]]
997 if options.verbose: sys.argv.append('-v')
998 unittest.main()
999
1000 outfile = sys.stdout
1001 if None!=options.outputFileName:
1002 outfile = file(options.outputFileName,'w')
1003
1004
1005 if options.doEncode:
1006
1007 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1008 if None==options.UserIDField: parser.error("missing value for UserIDField")
1009 if None==options.ChanAField: parser.error("missing value for ChanAField")
1010 if None==options.ChanBField: parser.error("missing value for ChanBField")
1011 if None==options.TxRxModeField: parser.error("missing value for TxRxModeField")
1012 if None==options.powerField: parser.error("missing value for powerField")
1013 if None==options.corner1_lonField: parser.error("missing value for corner1_lonField")
1014 if None==options.corner1_latField: parser.error("missing value for corner1_latField")
1015 if None==options.corner2_lonField: parser.error("missing value for corner2_lonField")
1016 if None==options.corner2_latField: parser.error("missing value for corner2_latField")
1017 if None==options.IndicatorTypeField: parser.error("missing value for IndicatorTypeField")
1018 if None==options.ChanABandwidthField: parser.error("missing value for ChanABandwidthField")
1019 if None==options.ChanBBandwidthField: parser.error("missing value for ChanBBandwidthField")
1020 if None==options.TransZoneSizeField: parser.error("missing value for TransZoneSizeField")
1021 msgDict={
1022 'MessageID': '22',
1023 'RepeatIndicator': options.RepeatIndicatorField,
1024 'UserID': options.UserIDField,
1025 'Spare': '0',
1026 'ChanA': options.ChanAField,
1027 'ChanB': options.ChanBField,
1028 'TxRxMode': options.TxRxModeField,
1029 'power': options.powerField,
1030 'corner1_lon': options.corner1_lonField,
1031 'corner1_lat': options.corner1_latField,
1032 'corner2_lon': options.corner2_lonField,
1033 'corner2_lat': options.corner2_latField,
1034 'IndicatorType': options.IndicatorTypeField,
1035 'ChanABandwidth': options.ChanABandwidthField,
1036 'ChanBBandwidth': options.ChanBBandwidthField,
1037 'TransZoneSize': options.TransZoneSizeField,
1038 'Spare': '0',
1039 }
1040
1041 bits = encode(msgDict)
1042 if 'binary'==options.ioType: print str(bits)
1043 elif 'nmeapayload'==options.ioType:
1044
1045 print "bitLen",len(bits)
1046 bitLen=len(bits)
1047 if bitLen%6!=0:
1048 bits = bits + BitVector(size=(6 - (bitLen%6)))
1049 print "result:",binary.bitvectoais6(bits)[0]
1050
1051
1052
1053 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1054 else: sys.exit('ERROR: unknown ioType. Help!')
1055
1056
1057 if options.sqlCreate:
1058 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1059
1060 if options.latexDefinitionTable:
1061 latexDefinitionTable(outfile)
1062
1063
1064 if options.textDefinitionTable:
1065 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1066
1067 if options.printCsvfieldList:
1068
1069 if None == options.fieldList: options.fieldList = fieldList
1070 import StringIO
1071 buf = StringIO.StringIO()
1072 for field in options.fieldList:
1073 buf.write(field+',')
1074 result = buf.getvalue()
1075 if result[-1] == ',': print result[:-1]
1076 else: print result
1077
1078 if options.doDecode:
1079 if len(args)==0: args = sys.stdin
1080 for msg in args:
1081 bv = None
1082
1083 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1084
1085
1086 bv = binary.ais6tobitvec(msg.split(',')[5])
1087 else:
1088
1089 binaryMsg=True
1090 for c in msg:
1091 if c not in ('0','1'):
1092 binaryMsg=False
1093 break
1094 if binaryMsg:
1095 bv = BitVector(bitstring=msg)
1096 else:
1097 bv = binary.ais6tobitvec(msg)
1098
1099 printFields(decode(bv)
1100 ,out=outfile
1101 ,format=options.outputType
1102 ,fieldList=options.fieldList
1103 ,dbType=options.dbType
1104 )
1105