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