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