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