1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2008-01-09 $'.split()[1]
5 __author__ = 'xmlbinmsg'
6
7 __doc__='''
8
9 Autogenerated python functions to serialize/deserialize binary messages.
10
11 Generated by: ./aisxmlbinmsg2py.py
12
13 Need to then wrap these functions with the outer AIS packet and then
14 convert the whole binary blob to a NMEA string. Those functions are
15 not currently provided in this file.
16
17 serialize: python to ais binary
18 deserialize: ais binary to python
19
20 The generated code uses translators.py, binary.py, and aisstring.py
21 which should be packaged with the resulting files.
22
23
24 @requires: U{epydoc<http://epydoc.sourceforge.net/>} > 3.0alpha3
25 @requires: U{BitVector<http://cheeseshop.python.org/pypi/BitVector>}
26
27 @author: '''+__author__+'''
28 @version: ''' + __version__ +'''
29 @var __date__: Date of last svn commit
30 @undocumented: __version__ __author__ __doc__ parser
31 @status: under development
32 @license: Generated code has no license
33 @todo: FIX: put in a description of the message here with fields and types.
34 '''
35
36 import sys
37 from decimal import Decimal
38 from BitVector import BitVector
39
40 import binary, aisstring
41
42
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 'Spare2',
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 'Spare2',
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 - Spare2(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 - Spare2(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['Spare2']=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>Spare2</td>\n")
446 out.write("<td>uint</td>\n")
447 if 'Spare2' in params:
448 out.write(" <td>"+str(params['Spare2'])+"</td>\n")
449 out.write(" <td>"+str(params['Spare2'])+"</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 - Spare2(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 'Spare2' in params: out.write(" Spare2: "+str(params['Spare2'])+"\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 dbTableName='ChanMngmt'
609 'Database table name'
610
611 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
612 ,addCoastGuardFields=True
613 ,dbType='postgres'
614 ):
615 '''
616 Return the SQL CREATE command for this message type
617 @param outfile: file like object to print to.
618 @param fields: which fields to put in the create. Defaults to all.
619 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
620 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
621 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
622 @type addCoastGuardFields: bool
623 @return: sql create string
624 @rtype: str
625
626 @see: sqlCreate
627 '''
628
629 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
630
631 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
632 '''
633 Return the sqlhelp object to create the table.
634
635 @param fields: which fields to put in the create. Defaults to all.
636 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
637 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
638 @type addCoastGuardFields: bool
639 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
640 @return: An object that can be used to generate a return
641 @rtype: sqlhelp.create
642 '''
643 if None == fields: fields = fieldList
644 import sqlhelp
645 c = sqlhelp.create('ChanMngmt',dbType=dbType)
646 c.addPrimaryKey()
647 if 'MessageID' in fields: c.addInt ('MessageID')
648 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
649 if 'UserID' in fields: c.addInt ('UserID')
650 if 'Spare' in fields: c.addInt ('Spare')
651 if 'ChanA' in fields: c.addInt ('ChanA')
652 if 'ChanB' in fields: c.addInt ('ChanB')
653 if 'TxRxMode' in fields: c.addInt ('TxRxMode')
654 if 'power' in fields: c.addInt ('power')
655 if dbType != 'postgres':
656 if 'corner1_lon' in fields: c.addDecimal('corner1_lon',5,2)
657 if dbType != 'postgres':
658 if 'corner1_lat' in fields: c.addDecimal('corner1_lat',5,2)
659 if dbType != 'postgres':
660 if 'corner2_lon' in fields: c.addDecimal('corner2_lon',5,2)
661 if dbType != 'postgres':
662 if 'corner2_lat' in fields: c.addDecimal('corner2_lat',5,2)
663 if 'IndicatorType' in fields: c.addInt ('IndicatorType')
664 if 'ChanABandwidth' in fields: c.addInt ('ChanABandwidth')
665 if 'ChanBBandwidth' in fields: c.addInt ('ChanBBandwidth')
666 if 'TransZoneSize' in fields: c.addInt ('TransZoneSize')
667 if 'Spare2' in fields: c.addInt ('Spare2')
668
669 if addCoastGuardFields:
670
671
672
673
674
675 c.addVarChar('cg_r',15)
676 c.addInt('cg_sec')
677
678 c.addTimestamp('cg_timestamp')
679
680 if dbType == 'postgres':
681
682
683 c.addPostGIS('corner1','POINT',2,SRID=4326);
684
685
686 c.addPostGIS('corner2','POINT',2,SRID=4326);
687
688 return c
689
690 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
691 '''
692 Return the SQL INSERT command for this message type
693 @param params: dictionary of values keyed by field name
694 @param outfile: file like object to print to.
695 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
696 @return: sql create string
697 @rtype: str
698
699 @see: sqlCreate
700 '''
701 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
702
703
704 -def sqlInsert(params,extraParams=None,dbType='postgres'):
705 '''
706 Give the SQL INSERT statement
707 @param params: dict keyed by field name of values
708 @param extraParams: any extra fields that you have created beyond the normal ais message fields
709 @rtype: sqlhelp.insert
710 @return: insert class instance
711 @todo: allow optional type checking of params?
712 @warning: this will take invalid keys happily and do what???
713 '''
714 import sqlhelp
715 i = sqlhelp.insert('ChanMngmt',dbType=dbType)
716
717 if dbType=='postgres':
718 finished = []
719 for key in params:
720 if key in finished:
721 continue
722
723 if key not in toPgFields and key not in fromPgFields:
724 if type(params[key])==Decimal: i.add(key,float(params[key]))
725 else: i.add(key,params[key])
726 else:
727 if key in fromPgFields:
728 val = params[key]
729
730 i.addPostGIS(key,val)
731 finished.append(key)
732 else:
733
734 pgName = toPgFields[key]
735
736 valStr=pgTypes[pgName]+'('
737 vals = []
738 for nonPgKey in fromPgFields[pgName]:
739 vals.append(str(params[nonPgKey]))
740 finished.append(nonPgKey)
741 valStr+=' '.join(vals)+')'
742 i.addPostGIS(pgName,valStr)
743 else:
744 for key in params:
745 if type(params[key])==Decimal: i.add(key,float(params[key]))
746 else: i.add(key,params[key])
747
748 if None != extraParams:
749 for key in extraParams:
750 i.add(key,extraParams[key])
751
752 return i
753
754
755
756
757
760 '''
761 Return the LaTeX definition table for this message type
762 @param outfile: file like object to print to.
763 @type outfile: file obj
764 @return: LaTeX table string via the outfile
765 @rtype: str
766
767 '''
768 o = outfile
769
770 o.write('''
771 \\begin{table}%[htb]
772 \\centering
773 \\begin{tabular}{|l|c|l|}
774 \\hline
775 Parameter & Number of bits & Description
776 \\\\ \\hline\\hline
777 MessageID & 6 & AIS message number. Must be 22 \\\\ \hline
778 RepeatIndicator & 2 & Indicated how many times a message has been repeated \\\\ \hline
779 UserID & 30 & Unique ship identification number (MMSI) \\\\ \hline
780 Spare & 2 & Not used. Should be set to zero. \\\\ \hline
781 ChanA & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline
782 ChanB & 12 & Channel number from ITU-R M.1084 Annex 4 \\\\ \hline
783 TxRxMode & 4 & FIX: find the description \\\\ \hline
784 power & 1 & FIX: put in a description \\\\ \hline
785 corner1\_lon & 18 & north-east corner of area for assignment longitude of corner \\\\ \hline
786 corner1\_lat & 17 & north-east corner of area for assignment latitude of corner \\\\ \hline
787 corner2\_lon & 18 & south-west corner of area for assignment longitude of corner \\\\ \hline
788 corner2\_lat & 17 & south-west corner of area for assignment latitude of corner \\\\ \hline
789 IndicatorType & 1 & FIX: put in a description \\\\ \hline
790 ChanABandwidth & 1 & FIX: put in a description \\\\ \hline
791 ChanBBandwidth & 1 & FIX: put in a description \\\\ \hline
792 TransZoneSize & 3 & FIX: put in a description \\\\ \hline
793 Spare2 & 23 & Not used. Should be set to zero.\\\\ \\hline \\hline
794 Total bits & 168 & Appears to take 1 slot \\\\ \\hline
795 \\end{tabular}
796 \\caption{AIS message number 22: Base station report - F}
797 \\label{tab:ChanMngmt}
798 \\end{table}
799 ''')
800
801
802
803
804
805 -def textDefinitionTable(outfile=sys.stdout
806 ,delim='\t'
807 ):
808 '''
809 Return the text definition table for this message type
810 @param outfile: file like object to print to.
811 @type outfile: file obj
812 @return: text table string via the outfile
813 @rtype: str
814
815 '''
816 o = outfile
817 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
818 MessageID'''+delim+'''6'''+delim+'''AIS message number. Must be 22
819 RepeatIndicator'''+delim+'''2'''+delim+'''Indicated how many times a message has been repeated
820 UserID'''+delim+'''30'''+delim+'''Unique ship identification number (MMSI)
821 Spare'''+delim+'''2'''+delim+'''Not used. Should be set to zero.
822 ChanA'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
823 ChanB'''+delim+'''12'''+delim+'''Channel number from ITU-R M.1084 Annex 4
824 TxRxMode'''+delim+'''4'''+delim+'''FIX: find the description
825 power'''+delim+'''1'''+delim+'''FIX: put in a description
826 corner1_lon'''+delim+'''18'''+delim+'''north-east corner of area for assignment longitude of corner
827 corner1_lat'''+delim+'''17'''+delim+'''north-east corner of area for assignment latitude of corner
828 corner2_lon'''+delim+'''18'''+delim+'''south-west corner of area for assignment longitude of corner
829 corner2_lat'''+delim+'''17'''+delim+'''south-west corner of area for assignment latitude of corner
830 IndicatorType'''+delim+'''1'''+delim+'''FIX: put in a description
831 ChanABandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
832 ChanBBandwidth'''+delim+'''1'''+delim+'''FIX: put in a description
833 TransZoneSize'''+delim+'''3'''+delim+'''FIX: put in a description
834 Spare2'''+delim+'''23'''+delim+'''Not used. Should be set to zero.
835 Total bits'''+delim+'''168'''+delim+'''Appears to take 1 slot''')
836
837
838
839
840
841 import unittest
843 '''Return a params file base on the testvalue tags.
844 @rtype: dict
845 @return: params based on testvalue tags
846 '''
847 params = {}
848 params['MessageID'] = 22
849 params['RepeatIndicator'] = 1
850 params['UserID'] = 1193046
851 params['Spare'] = 0
852 params['ChanA'] = 0
853 params['ChanB'] = 0
854 params['TxRxMode'] = 1
855 params['power'] = 1
856 params['corner1_lon'] = Decimal('-122.16')
857 params['corner1_lat'] = Decimal('37.42')
858 params['corner2_lon'] = Decimal('-122.16')
859 params['corner2_lat'] = Decimal('37.42')
860 params['IndicatorType'] = 1
861 params['ChanABandwidth'] = 1
862 params['ChanBBandwidth'] = 1
863 params['TransZoneSize'] = 1
864 params['Spare2'] = 0
865
866 return params
867
869 '''Use testvalue tag text from each type to build test case the ChanMngmt message'''
871
872 params = testParams()
873 bits = encode(params)
874 r = decode(bits)
875
876
877 self.failUnlessEqual(r['MessageID'],params['MessageID'])
878 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
879 self.failUnlessEqual(r['UserID'],params['UserID'])
880 self.failUnlessEqual(r['Spare'],params['Spare'])
881 self.failUnlessEqual(r['ChanA'],params['ChanA'])
882 self.failUnlessEqual(r['ChanB'],params['ChanB'])
883 self.failUnlessEqual(r['TxRxMode'],params['TxRxMode'])
884 self.failUnlessEqual(r['power'],params['power'])
885 self.failUnlessAlmostEqual(r['corner1_lon'],params['corner1_lon'],2)
886 self.failUnlessAlmostEqual(r['corner1_lat'],params['corner1_lat'],2)
887 self.failUnlessAlmostEqual(r['corner2_lon'],params['corner2_lon'],2)
888 self.failUnlessAlmostEqual(r['corner2_lat'],params['corner2_lat'],2)
889 self.failUnlessEqual(r['IndicatorType'],params['IndicatorType'])
890 self.failUnlessEqual(r['ChanABandwidth'],params['ChanABandwidth'])
891 self.failUnlessEqual(r['ChanBBandwidth'],params['ChanBBandwidth'])
892 self.failUnlessEqual(r['TransZoneSize'],params['TransZoneSize'])
893 self.failUnlessEqual(r['Spare2'],params['Spare2'])
894
896 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
897 help='decode a "ChanMngmt" AIS message')
898 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
899 help='encode a "ChanMngmt" AIS message')
900 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
901 ,help='Field parameter value [default: %default]')
902 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
903 ,help='Field parameter value [default: %default]')
904 parser.add_option('--ChanA-field', dest='ChanAField',metavar='uint',type='int'
905 ,help='Field parameter value [default: %default]')
906 parser.add_option('--ChanB-field', dest='ChanBField',metavar='uint',type='int'
907 ,help='Field parameter value [default: %default]')
908 parser.add_option('--TxRxMode-field', dest='TxRxModeField',metavar='uint',type='int'
909 ,help='Field parameter value [default: %default]')
910 parser.add_option('--power-field', dest='powerField',metavar='uint',type='int'
911 ,help='Field parameter value [default: %default]')
912 parser.add_option('--corner1_lon-field', dest='corner1_lonField',default=Decimal('181'),metavar='decimal',type='string'
913 ,help='Field parameter value [default: %default]')
914 parser.add_option('--corner1_lat-field', dest='corner1_latField',default=Decimal('181'),metavar='decimal',type='string'
915 ,help='Field parameter value [default: %default]')
916 parser.add_option('--corner2_lon-field', dest='corner2_lonField',default=Decimal('181'),metavar='decimal',type='string'
917 ,help='Field parameter value [default: %default]')
918 parser.add_option('--corner2_lat-field', dest='corner2_latField',default=Decimal('181'),metavar='decimal',type='string'
919 ,help='Field parameter value [default: %default]')
920 parser.add_option('--IndicatorType-field', dest='IndicatorTypeField',metavar='uint',type='int'
921 ,help='Field parameter value [default: %default]')
922 parser.add_option('--ChanABandwidth-field', dest='ChanABandwidthField',metavar='uint',type='int'
923 ,help='Field parameter value [default: %default]')
924 parser.add_option('--ChanBBandwidth-field', dest='ChanBBandwidthField',metavar='uint',type='int'
925 ,help='Field parameter value [default: %default]')
926 parser.add_option('--TransZoneSize-field', dest='TransZoneSizeField',metavar='uint',type='int'
927 ,help='Field parameter value [default: %default]')
928
929
930 if __name__=='__main__':
931
932 from optparse import OptionParser
933 parser = OptionParser(usage="%prog [options]",
934 version="%prog "+__version__)
935
936 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
937 help='run the documentation tests')
938 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
939 help='run the unit tests')
940 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
941 help='Make the test output verbose')
942
943
944
945 typeChoices = ('binary','nmeapayload','nmea')
946 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
947 ,default='nmeapayload'
948 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
949
950
951 outputChoices = ('std','html','csv','sql' )
952 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
953 ,default='std'
954 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
955
956 parser.add_option('-o','--output',dest='outputFileName',default=None,
957 help='Name of the python file to write [default: stdout]')
958
959 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
960 choices=fieldList,
961 help='Which fields to include in the output. Currently only for csv output [default: all]')
962
963 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
964 help='Print the field name for csv')
965
966 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
967 help='Print out an sql create command for the table.')
968
969 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
970 help='Print a LaTeX table of the type')
971
972 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
973 help='Print delimited table of the type (for Word table importing)')
974 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
975 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
976
977
978 dbChoices = ('sqlite','postgres')
979 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
980 ,choices=dbChoices,type='choice'
981 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
982
983 addMsgOptions(parser)
984
985 (options,args) = parser.parse_args()
986 success=True
987
988 if options.doctest:
989 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
990 sys.argv= [sys.argv[0]]
991 if options.verbose: sys.argv.append('-v')
992 import doctest
993 numfail,numtests=doctest.testmod()
994 if numfail==0: print 'ok'
995 else:
996 print 'FAILED'
997 success=False
998
999 if not success: sys.exit('Something Failed')
1000 del success
1001
1002 if options.unittest:
1003 sys.argv = [sys.argv[0]]
1004 if options.verbose: sys.argv.append('-v')
1005 unittest.main()
1006
1007 outfile = sys.stdout
1008 if None!=options.outputFileName:
1009 outfile = file(options.outputFileName,'w')
1010
1011
1012 if options.doEncode:
1013
1014 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
1015 if None==options.UserIDField: parser.error("missing value for UserIDField")
1016 if None==options.ChanAField: parser.error("missing value for ChanAField")
1017 if None==options.ChanBField: parser.error("missing value for ChanBField")
1018 if None==options.TxRxModeField: parser.error("missing value for TxRxModeField")
1019 if None==options.powerField: parser.error("missing value for powerField")
1020 if None==options.corner1_lonField: parser.error("missing value for corner1_lonField")
1021 if None==options.corner1_latField: parser.error("missing value for corner1_latField")
1022 if None==options.corner2_lonField: parser.error("missing value for corner2_lonField")
1023 if None==options.corner2_latField: parser.error("missing value for corner2_latField")
1024 if None==options.IndicatorTypeField: parser.error("missing value for IndicatorTypeField")
1025 if None==options.ChanABandwidthField: parser.error("missing value for ChanABandwidthField")
1026 if None==options.ChanBBandwidthField: parser.error("missing value for ChanBBandwidthField")
1027 if None==options.TransZoneSizeField: parser.error("missing value for TransZoneSizeField")
1028 msgDict={
1029 'MessageID': '22',
1030 'RepeatIndicator': options.RepeatIndicatorField,
1031 'UserID': options.UserIDField,
1032 'Spare': '0',
1033 'ChanA': options.ChanAField,
1034 'ChanB': options.ChanBField,
1035 'TxRxMode': options.TxRxModeField,
1036 'power': options.powerField,
1037 'corner1_lon': options.corner1_lonField,
1038 'corner1_lat': options.corner1_latField,
1039 'corner2_lon': options.corner2_lonField,
1040 'corner2_lat': options.corner2_latField,
1041 'IndicatorType': options.IndicatorTypeField,
1042 'ChanABandwidth': options.ChanABandwidthField,
1043 'ChanBBandwidth': options.ChanBBandwidthField,
1044 'TransZoneSize': options.TransZoneSizeField,
1045 'Spare2': '0',
1046 }
1047
1048 bits = encode(msgDict)
1049 if 'binary'==options.ioType: print str(bits)
1050 elif 'nmeapayload'==options.ioType:
1051
1052 print "bitLen",len(bits)
1053 bitLen=len(bits)
1054 if bitLen%6!=0:
1055 bits = bits + BitVector(size=(6 - (bitLen%6)))
1056 print "result:",binary.bitvectoais6(bits)[0]
1057
1058
1059
1060 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
1061 else: sys.exit('ERROR: unknown ioType. Help!')
1062
1063
1064 if options.sqlCreate:
1065 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1066
1067 if options.latexDefinitionTable:
1068 latexDefinitionTable(outfile)
1069
1070
1071 if options.textDefinitionTable:
1072 textDefinitionTable(outfile,options.delimTextDefinitionTable)
1073
1074 if options.printCsvfieldList:
1075
1076 if None == options.fieldList: options.fieldList = fieldList
1077 import StringIO
1078 buf = StringIO.StringIO()
1079 for field in options.fieldList:
1080 buf.write(field+',')
1081 result = buf.getvalue()
1082 if result[-1] == ',': print result[:-1]
1083 else: print result
1084
1085 if options.doDecode:
1086 if len(args)==0: args = sys.stdin
1087 for msg in args:
1088 bv = None
1089
1090 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1091
1092
1093 bv = binary.ais6tobitvec(msg.split(',')[5])
1094 else:
1095
1096 binaryMsg=True
1097 for c in msg:
1098 if c not in ('0','1'):
1099 binaryMsg=False
1100 break
1101 if binaryMsg:
1102 bv = BitVector(bitstring=msg)
1103 else:
1104 bv = binary.ais6tobitvec(msg)
1105
1106 printFields(decode(bv)
1107 ,out=outfile
1108 ,format=options.outputType
1109 ,fieldList=options.fieldList
1110 ,dbType=options.dbType
1111 )
1112