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