1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-01-18 $'.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 '''
34
35 import sys
36 from decimal import Decimal
37 from BitVector import BitVector
38
39 import binary, aisstring
40
41
42 TrueBV = BitVector(bitstring="1")
43 "Why always rebuild the True bit? This should speed things up a bunch"
44 FalseBV = BitVector(bitstring="0")
45 "Why always rebuild the False bit? This should speed things up a bunch"
46
47
48 fieldList = [
49 'time_month',
50 'time_day',
51 'time_hour',
52 'time_min',
53 'stationid',
54 'pos_longitude',
55 'pos_latitude',
56 'type',
57 'waterlevel',
58 'datum',
59 'reserved',
60 ]
61
62 -def encode(params, validate=False):
63 '''Create a sls_waterlevel binary message payload to pack into an AIS Msg sls_waterlevel.
64
65 Fields in params:
66 - time_month(uint): Time tag of measurement month 1..12
67 - time_day(uint): Time tag of measurement day of the month 1..31
68 - time_hour(uint): Time tag of measurement UTC hours 0..23
69 - time_min(uint): Time tag of measurement minutes
70 - stationid(aisstr6): Character identifier of the station. Usually a number.
71 - pos_longitude(decimal): Location of measurement East West location
72 - pos_latitude(decimal): Location of measurement North South location
73 - type(uint): How to interpret the water level
74 - waterlevel(int): Water level in centimeters
75 - datum(uint): What reference datum applies to the value
76 - reserved(uint): Reserved bits for future use (field automatically set to "0")
77 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
78 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
79 @rtype: BitVector
80 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
81 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
82 '''
83
84 bvList = []
85 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4))
86 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5))
87 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5))
88 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6))
89 if 'stationid' in params:
90 bvList.append(aisstring.encode(params['stationid'],42))
91 else:
92 bvList.append(aisstring.encode('@@@@@@@',42))
93 if 'pos_longitude' in params:
94 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25))
95 else:
96 bvList.append(binary.bvFromSignedInt(10860000,25))
97 if 'pos_latitude' in params:
98 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24))
99 else:
100 bvList.append(binary.bvFromSignedInt(5460000,24))
101 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),1))
102 if 'waterlevel' in params:
103 bvList.append(binary.bvFromSignedInt(params['waterlevel'],16))
104 else:
105 bvList.append(binary.bvFromSignedInt(-32768,16))
106 if 'datum' in params:
107 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['datum']),2))
108 else:
109 bvList.append(binary.setBitVectorSize(BitVector(intVal=31),2))
110 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),14))
111
112 return binary.joinBV(bvList)
113
114 -def decode(bv, validate=False):
115 '''Unpack a sls_waterlevel message
116
117 Fields in params:
118 - time_month(uint): Time tag of measurement month 1..12
119 - time_day(uint): Time tag of measurement day of the month 1..31
120 - time_hour(uint): Time tag of measurement UTC hours 0..23
121 - time_min(uint): Time tag of measurement minutes
122 - stationid(aisstr6): Character identifier of the station. Usually a number.
123 - pos_longitude(decimal): Location of measurement East West location
124 - pos_latitude(decimal): Location of measurement North South location
125 - type(uint): How to interpret the water level
126 - waterlevel(int): Water level in centimeters
127 - datum(uint): What reference datum applies to the value
128 - reserved(uint): Reserved bits for future use (field automatically set to "0")
129 @type bv: BitVector
130 @param bv: Bits defining a message
131 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
132 @rtype: dict
133 @return: params
134 '''
135
136
137
138
139 r = {}
140 r['time_month']=int(bv[0:4])
141 r['time_day']=int(bv[4:9])
142 r['time_hour']=int(bv[9:14])
143 r['time_min']=int(bv[14:20])
144 r['stationid']=aisstring.decode(bv[20:62])
145 r['pos_longitude']=Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000')
146 r['pos_latitude']=Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000')
147 r['type']=int(bv[111:112])
148 r['waterlevel']=binary.signedIntFromBV(bv[112:128])
149 r['datum']=int(bv[128:130])
150 r['reserved']=0
151 return r
152
155
158
161
163 return int(bv[14:20])
164
167
170
173
175 return int(bv[111:112])
176
179
181 return int(bv[128:130])
182
184 return 0
185
186
188 out.write("<h3>sls_waterlevel<h3>\n")
189 out.write("<table border=\"1\">\n")
190 out.write("<tr bgcolor=\"orange\">\n")
191 out.write("<th align=\"left\">Field Name</th>\n")
192 out.write("<th align=\"left\">Type</th>\n")
193 out.write("<th align=\"left\">Value</th>\n")
194 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
195 out.write("<th align=\"left\">Units</th>\n")
196 out.write("\n")
197 out.write("<tr>\n")
198 out.write("<td>time_month</td>\n")
199 out.write("<td>uint</td>\n")
200 if 'time_month' in params:
201 out.write(" <td>"+str(params['time_month'])+"</td>\n")
202 out.write(" <td>"+str(params['time_month'])+"</td>\n")
203 out.write("</tr>\n")
204 out.write("\n")
205 out.write("<tr>\n")
206 out.write("<td>time_day</td>\n")
207 out.write("<td>uint</td>\n")
208 if 'time_day' in params:
209 out.write(" <td>"+str(params['time_day'])+"</td>\n")
210 out.write(" <td>"+str(params['time_day'])+"</td>\n")
211 out.write("</tr>\n")
212 out.write("\n")
213 out.write("<tr>\n")
214 out.write("<td>time_hour</td>\n")
215 out.write("<td>uint</td>\n")
216 if 'time_hour' in params:
217 out.write(" <td>"+str(params['time_hour'])+"</td>\n")
218 out.write(" <td>"+str(params['time_hour'])+"</td>\n")
219 out.write("</tr>\n")
220 out.write("\n")
221 out.write("<tr>\n")
222 out.write("<td>time_min</td>\n")
223 out.write("<td>uint</td>\n")
224 if 'time_min' in params:
225 out.write(" <td>"+str(params['time_min'])+"</td>\n")
226 out.write(" <td>"+str(params['time_min'])+"</td>\n")
227 out.write("</tr>\n")
228 out.write("\n")
229 out.write("<tr>\n")
230 out.write("<td>stationid</td>\n")
231 out.write("<td>aisstr6</td>\n")
232 if 'stationid' in params:
233 out.write(" <td>"+str(params['stationid'])+"</td>\n")
234 out.write(" <td>"+str(params['stationid'])+"</td>\n")
235 out.write("</tr>\n")
236 out.write("\n")
237 out.write("<tr>\n")
238 out.write("<td>pos_longitude</td>\n")
239 out.write("<td>decimal</td>\n")
240 if 'pos_longitude' in params:
241 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n")
242 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n")
243 out.write("<td>degrees</td>\n")
244 out.write("</tr>\n")
245 out.write("\n")
246 out.write("<tr>\n")
247 out.write("<td>pos_latitude</td>\n")
248 out.write("<td>decimal</td>\n")
249 if 'pos_latitude' in params:
250 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n")
251 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n")
252 out.write("<td>degrees</td>\n")
253 out.write("</tr>\n")
254 out.write("\n")
255 out.write("<tr>\n")
256 out.write("<td>type</td>\n")
257 out.write("<td>uint</td>\n")
258 if 'type' in params:
259 out.write(" <td>"+str(params['type'])+"</td>\n")
260 if str(params['type']) in typeDecodeLut:
261 out.write("<td>"+typeDecodeLut[str(params['type'])]+"</td>")
262 else:
263 out.write("<td><i>Missing LUT entry</i></td>")
264 out.write("</tr>\n")
265 out.write("\n")
266 out.write("<tr>\n")
267 out.write("<td>waterlevel</td>\n")
268 out.write("<td>int</td>\n")
269 if 'waterlevel' in params:
270 out.write(" <td>"+str(params['waterlevel'])+"</td>\n")
271 out.write(" <td>"+str(params['waterlevel'])+"</td>\n")
272 out.write("<td>cm</td>\n")
273 out.write("</tr>\n")
274 out.write("\n")
275 out.write("<tr>\n")
276 out.write("<td>datum</td>\n")
277 out.write("<td>uint</td>\n")
278 if 'datum' in params:
279 out.write(" <td>"+str(params['datum'])+"</td>\n")
280 if str(params['datum']) in datumDecodeLut:
281 out.write("<td>"+datumDecodeLut[str(params['datum'])]+"</td>")
282 else:
283 out.write("<td><i>Missing LUT entry</i></td>")
284 out.write("</tr>\n")
285 out.write("\n")
286 out.write("<tr>\n")
287 out.write("<td>reserved</td>\n")
288 out.write("<td>uint</td>\n")
289 if 'reserved' in params:
290 out.write(" <td>"+str(params['reserved'])+"</td>\n")
291 out.write(" <td>"+str(params['reserved'])+"</td>\n")
292 out.write("</tr>\n")
293 out.write("</table>\n")
294
295
297 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
298 out.write("\ <Placemark>\n")
299 out.write("\t <name>"+str(params['stationid'])+"</name>\n")
300 out.write("\t\t<description>\n")
301 import StringIO
302 buf = StringIO.StringIO()
303 printHtml(params,buf)
304 import cgi
305 out.write(cgi.escape(buf.getvalue()))
306 out.write("\t\t</description>\n")
307 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
308 out.write("\t\t<Point>\n")
309 out.write("\t\t\t<coordinates>")
310 out.write(str(params['pos_longitude']))
311 out.write(',')
312 out.write(str(params['pos_latitude']))
313 out.write(",0</coordinates>\n")
314 out.write("\t\t</Point>\n")
315 out.write("\t</Placemark>\n")
316
317 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
318 '''Print a reserved message to stdout.
319
320 Fields in params:
321 - time_month(uint): Time tag of measurement month 1..12
322 - time_day(uint): Time tag of measurement day of the month 1..31
323 - time_hour(uint): Time tag of measurement UTC hours 0..23
324 - time_min(uint): Time tag of measurement minutes
325 - stationid(aisstr6): Character identifier of the station. Usually a number.
326 - pos_longitude(decimal): Location of measurement East West location
327 - pos_latitude(decimal): Location of measurement North South location
328 - type(uint): How to interpret the water level
329 - waterlevel(int): Water level in centimeters
330 - datum(uint): What reference datum applies to the value
331 - reserved(uint): Reserved bits for future use (field automatically set to "0")
332 @param params: Dictionary of field names/values.
333 @param out: File like object to write to
334 @rtype: stdout
335 @return: text to out
336 '''
337
338 if 'std'==format:
339 out.write("reserved:\n")
340 if 'time_month' in params: out.write(" time_month: "+str(params['time_month'])+"\n")
341 if 'time_day' in params: out.write(" time_day: "+str(params['time_day'])+"\n")
342 if 'time_hour' in params: out.write(" time_hour: "+str(params['time_hour'])+"\n")
343 if 'time_min' in params: out.write(" time_min: "+str(params['time_min'])+"\n")
344 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n")
345 if 'pos_longitude' in params: out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n")
346 if 'pos_latitude' in params: out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n")
347 if 'type' in params: out.write(" type: "+str(params['type'])+"\n")
348 if 'waterlevel' in params: out.write(" waterlevel: "+str(params['waterlevel'])+"\n")
349 if 'datum' in params: out.write(" datum: "+str(params['datum'])+"\n")
350 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n")
351 elif 'csv'==format:
352 if None == options.fieldList:
353 options.fieldList = fieldList
354 needComma = False;
355 for field in fieldList:
356 if needComma: out.write(',')
357 needComma = True
358 if field in params:
359 out.write(str(params[field]))
360
361 out.write("\n")
362 elif 'html'==format:
363 printHtml(params,out)
364 elif 'kml'==format:
365 printKml(params,out)
366 elif 'kml-full'==format:
367 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
368 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
369 out.write("<Document>\n")
370 out.write(" <name>Position</name>\n")
371 printKml(params,out)
372 out.write("</Document>\n")
373 out.write("</kml>\n")
374 else:
375 print "ERROR: unknown format:",format
376 assert False
377
378 return
379
380 typeEncodeLut = {
381 'Relative to datum':'0',
382 'Water depth':'1',
383 }
384
385 typeDecodeLut = {
386 '0':'Relative to datum',
387 '1':'Water depth',
388 }
389
390 datumEncodeLut = {
391 'MLLW':'0',
392 'IGLD-85':'1',
393 'Reserved':'2',
394 'Reserved':'3',
395 }
396
397 datumDecodeLut = {
398 '0':'MLLW',
399 '1':'IGLD-85',
400 '2':'Reserved',
401 '3':'Reserved',
402 }
403
404
405
406
407
408
409 import unittest
411 '''Return a params file base on the testvalue tags.
412 @rtype: dict
413 @return: params based on testvalue tags
414 '''
415 params = {}
416 params['time_month'] = 2
417 params['time_day'] = 28
418 params['time_hour'] = 23
419 params['time_min'] = 45
420 params['stationid'] = 'A234567'
421 params['pos_longitude'] = Decimal('-122.16328')
422 params['pos_latitude'] = Decimal('37.42446')
423 params['type'] = 0
424 params['waterlevel'] = -97
425 params['datum'] = 0
426 params['reserved'] = 0
427
428 return params
429
431 '''Use testvalue tag text from each type to build test case the sls_waterlevel message'''
433
434 params = testParams()
435 bits = encode(params)
436 r = decode(bits)
437
438
439 self.failUnlessEqual(r['time_month'],params['time_month'])
440 self.failUnlessEqual(r['time_day'],params['time_day'])
441 self.failUnlessEqual(r['time_hour'],params['time_hour'])
442 self.failUnlessEqual(r['time_min'],params['time_min'])
443 self.failUnlessEqual(r['stationid'],params['stationid'])
444 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4)
445 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4)
446 self.failUnlessEqual(r['type'],params['type'])
447 self.failUnlessEqual(r['waterlevel'],params['waterlevel'])
448 self.failUnlessEqual(r['datum'],params['datum'])
449 self.failUnlessEqual(r['reserved'],params['reserved'])
450
452 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
453 help='decode a "sls_waterlevel" AIS message')
454 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
455 help='encode a "sls_waterlevel" AIS message')
456 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int'
457 ,help='Field parameter value [default: %default]')
458 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int'
459 ,help='Field parameter value [default: %default]')
460 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int'
461 ,help='Field parameter value [default: %default]')
462 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int'
463 ,help='Field parameter value [default: %default]')
464 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string'
465 ,help='Field parameter value [default: %default]')
466 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string'
467 ,help='Field parameter value [default: %default]')
468 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string'
469 ,help='Field parameter value [default: %default]')
470 parser.add_option('--type-field', dest='typeField',metavar='uint',type='int'
471 ,help='Field parameter value [default: %default]')
472 parser.add_option('--waterlevel-field', dest='waterlevelField',default=-32768,metavar='int',type='int'
473 ,help='Field parameter value [default: %default]')
474 parser.add_option('--datum-field', dest='datumField',default=31,metavar='uint',type='int'
475 ,help='Field parameter value [default: %default]')
476
477
478 if __name__=='__main__':
479
480 from optparse import OptionParser
481 parser = OptionParser(usage="%prog [options]",
482 version="%prog "+__version__)
483
484 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
485 help='run the documentation tests')
486 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
487 help='run the unit tests')
488 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
489 help='Make the test output verbose')
490
491
492
493 typeChoices = ('binary','nmeapayload','nmea')
494 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
495 ,default='nmeapayload'
496 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
497
498
499 outputChoices = ('std','html','csv' , 'kml','kml-full')
500 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
501 ,default='std'
502 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
503
504 parser.add_option('-o','--output',dest='outputFileName',default=None,
505 help='Name of the python file to write [default: stdout]')
506
507 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
508 choices=fieldList,
509 help='Which fields to include in the output. Currently only for csv output [default: all]')
510
511 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
512 help='Print the field name for csv')
513
514 addMsgOptions(parser)
515
516 (options,args) = parser.parse_args()
517 success=True
518
519 if options.doctest:
520 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
521 sys.argv= [sys.argv[0]]
522 if options.verbose: sys.argv.append('-v')
523 import doctest
524 numfail,numtests=doctest.testmod()
525 if numfail==0: print 'ok'
526 else:
527 print 'FAILED'
528 success=False
529
530 if not success: sys.exit('Something Failed')
531 del success
532
533 if options.unittest:
534 sys.argv = [sys.argv[0]]
535 if options.verbose: sys.argv.append('-v')
536 unittest.main()
537
538 outfile = sys.stdout
539 if None!=options.outputFileName:
540 outfile = file(options.outputFileName,'w')
541
542
543 if options.doEncode:
544
545 if None==options.time_monthField: parser.error("missing value for time_monthField")
546 if None==options.time_dayField: parser.error("missing value for time_dayField")
547 if None==options.time_hourField: parser.error("missing value for time_hourField")
548 if None==options.time_minField: parser.error("missing value for time_minField")
549 if None==options.stationidField: parser.error("missing value for stationidField")
550 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField")
551 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField")
552 if None==options.typeField: parser.error("missing value for typeField")
553 if None==options.waterlevelField: parser.error("missing value for waterlevelField")
554 if None==options.datumField: parser.error("missing value for datumField")
555 msgDict={
556 'time_month': options.time_monthField,
557 'time_day': options.time_dayField,
558 'time_hour': options.time_hourField,
559 'time_min': options.time_minField,
560 'stationid': options.stationidField,
561 'pos_longitude': options.pos_longitudeField,
562 'pos_latitude': options.pos_latitudeField,
563 'type': options.typeField,
564 'waterlevel': options.waterlevelField,
565 'datum': options.datumField,
566 'reserved': '0',
567 }
568
569 bits = encode(msgDict)
570 if 'binary'==options.ioType: print str(bits)
571 elif 'nmeapayload'==options.ioType:
572
573 print "bitLen",len(bits)
574 bitLen=len(bits)
575 if bitLen%6!=0:
576 bits = bits + BitVector(size=(6 - (bitLen%6)))
577 print "result:",binary.bitvectoais6(bits)[0]
578
579
580
581 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
582 else: sys.exit('ERROR: unknown ioType. Help!')
583
584 if options.printCsvfieldList:
585
586 if None == options.fieldList: options.fieldList = fieldList
587 import StringIO
588 buf = StringIO.StringIO()
589 for field in options.fieldList:
590 buf.write(field+',')
591 result = buf.getvalue()
592 if result[-1] == ',': print result[:-1]
593 else: print result
594
595 if options.doDecode:
596 for msg in args:
597 bv = None
598 if 'binary' == options.ioType: bv = BitVector(bitstring=msg)
599 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg)
600 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5])
601 else: sys.exit('ERROR: unknown ioType. Help!')
602
603 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList)
604