1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-02-08 $'.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, addCoastGuardFields=True):
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 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
348 @type addCoastGuardFields: bool
349 @return: sql create string
350 @rtype: str
351
352 @see: sqlCreate
353 '''
354 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields)))
355
356 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True):
357 '''
358 Return the sqlhelp object to create the table.
359
360 @param fields: which fields to put in the create. Defaults to all.
361 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
362 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
363 @type addCoastGuardFields: bool
364 @return: An object that can be used to generate a return
365 @rtype: sqlhelp.create
366 '''
367 if None == fields: fields = fieldList
368 import sqlhelp
369 c = sqlhelp.create('sls_wind')
370 if 'time_month' in fields: c.addInt ('time_month')
371 if 'time_day' in fields: c.addInt ('time_day')
372 if 'time_hour' in fields: c.addInt ('time_hour')
373 if 'time_min' in fields: c.addInt ('time_min')
374 if 'stationid' in fields: c.addVarChar('stationid',7)
375 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4)
376 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4)
377 if 'flow' in fields: c.addInt ('flow')
378 if 'reserved' in fields: c.addInt ('reserved')
379
380 if addCoastGuardFields:
381
382
383
384
385
386 c.addVarChar('cg_r',15)
387 c.addInt('cg_timestamp')
388
389
390 return c
391
392 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
393 '''
394 Return the SQL CREATE command for this message type
395 @param params: dictionary of values keyed by field name
396 @param outfile: file like object to print to.
397 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
398 @return: sql create string
399 @rtype: str
400
401 @see: sqlCreate
402 '''
403 outfile.write(str(sqlInsert(params,extraParams)))
404
405
407 '''
408 Give the SQL insert statement
409 @param params: dict keyed by field name of values
410 @param extraParams: any extra fields that you have created beyond the normal ais message fields
411 @rtype: sqlhelp.insert
412 @return: insert class instance
413 @todo: allow optional type checking of params?
414 @warning: this will take invalid keys happily and do what???
415 '''
416 import sqlhelp
417 i = sqlhelp.insert('sls_wind')
418 for key in params:
419
420 if type(params[key])==Decimal: i.add(key,float(params[key]))
421 else: i.add(key,params[key])
422 if None != extraParams:
423 for key in extraParams:
424 i.add(key,extraParams[key])
425
426 return i
427
428
429
430
431
432 import unittest
434 '''Return a params file base on the testvalue tags.
435 @rtype: dict
436 @return: params based on testvalue tags
437 '''
438 params = {}
439 params['time_month'] = 2
440 params['time_day'] = 28
441 params['time_hour'] = 23
442 params['time_min'] = 45
443 params['stationid'] = 'A345678'
444 params['pos_longitude'] = Decimal('-122.16328')
445 params['pos_latitude'] = Decimal('37.42446')
446 params['flow'] = 43
447 params['reserved'] = 0
448
449 return params
450
452 '''Use testvalue tag text from each type to build test case the sls_wind message'''
454
455 params = testParams()
456 bits = encode(params)
457 r = decode(bits)
458
459
460 self.failUnlessEqual(r['time_month'],params['time_month'])
461 self.failUnlessEqual(r['time_day'],params['time_day'])
462 self.failUnlessEqual(r['time_hour'],params['time_hour'])
463 self.failUnlessEqual(r['time_min'],params['time_min'])
464 self.failUnlessEqual(r['stationid'],params['stationid'])
465 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4)
466 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4)
467 self.failUnlessEqual(r['flow'],params['flow'])
468 self.failUnlessEqual(r['reserved'],params['reserved'])
469
471 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
472 help='decode a "sls_wind" AIS message')
473 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
474 help='encode a "sls_wind" AIS message')
475 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int'
476 ,help='Field parameter value [default: %default]')
477 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int'
478 ,help='Field parameter value [default: %default]')
479 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int'
480 ,help='Field parameter value [default: %default]')
481 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int'
482 ,help='Field parameter value [default: %default]')
483 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string'
484 ,help='Field parameter value [default: %default]')
485 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string'
486 ,help='Field parameter value [default: %default]')
487 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string'
488 ,help='Field parameter value [default: %default]')
489 parser.add_option('--flow-field', dest='flowField',default=16383,metavar='uint',type='int'
490 ,help='Field parameter value [default: %default]')
491
492
493 if __name__=='__main__':
494
495 from optparse import OptionParser
496 parser = OptionParser(usage="%prog [options]",
497 version="%prog "+__version__)
498
499 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
500 help='run the documentation tests')
501 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
502 help='run the unit tests')
503 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
504 help='Make the test output verbose')
505
506
507
508 typeChoices = ('binary','nmeapayload','nmea')
509 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
510 ,default='nmeapayload'
511 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
512
513
514 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
515 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
516 ,default='std'
517 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
518
519 parser.add_option('-o','--output',dest='outputFileName',default=None,
520 help='Name of the python file to write [default: stdout]')
521
522 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
523 choices=fieldList,
524 help='Which fields to include in the output. Currently only for csv output [default: all]')
525
526 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
527 help='Print the field name for csv')
528
529 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
530 help='Print out an sql create command for the table.')
531
532 addMsgOptions(parser)
533
534 (options,args) = parser.parse_args()
535 success=True
536
537 if options.doctest:
538 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
539 sys.argv= [sys.argv[0]]
540 if options.verbose: sys.argv.append('-v')
541 import doctest
542 numfail,numtests=doctest.testmod()
543 if numfail==0: print 'ok'
544 else:
545 print 'FAILED'
546 success=False
547
548 if not success: sys.exit('Something Failed')
549 del success
550
551 if options.unittest:
552 sys.argv = [sys.argv[0]]
553 if options.verbose: sys.argv.append('-v')
554 unittest.main()
555
556 outfile = sys.stdout
557 if None!=options.outputFileName:
558 outfile = file(options.outputFileName,'w')
559
560
561 if options.doEncode:
562
563 if None==options.time_monthField: parser.error("missing value for time_monthField")
564 if None==options.time_dayField: parser.error("missing value for time_dayField")
565 if None==options.time_hourField: parser.error("missing value for time_hourField")
566 if None==options.time_minField: parser.error("missing value for time_minField")
567 if None==options.stationidField: parser.error("missing value for stationidField")
568 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField")
569 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField")
570 if None==options.flowField: parser.error("missing value for flowField")
571 msgDict={
572 'time_month': options.time_monthField,
573 'time_day': options.time_dayField,
574 'time_hour': options.time_hourField,
575 'time_min': options.time_minField,
576 'stationid': options.stationidField,
577 'pos_longitude': options.pos_longitudeField,
578 'pos_latitude': options.pos_latitudeField,
579 'flow': options.flowField,
580 'reserved': '0',
581 }
582
583 bits = encode(msgDict)
584 if 'binary'==options.ioType: print str(bits)
585 elif 'nmeapayload'==options.ioType:
586
587 print "bitLen",len(bits)
588 bitLen=len(bits)
589 if bitLen%6!=0:
590 bits = bits + BitVector(size=(6 - (bitLen%6)))
591 print "result:",binary.bitvectoais6(bits)[0]
592
593
594
595 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
596 else: sys.exit('ERROR: unknown ioType. Help!')
597
598
599 if options.sqlCreate:
600 sqlCreateStr(outfile,options.fieldList)
601
602 if options.printCsvfieldList:
603
604 if None == options.fieldList: options.fieldList = fieldList
605 import StringIO
606 buf = StringIO.StringIO()
607 for field in options.fieldList:
608 buf.write(field+',')
609 result = buf.getvalue()
610 if result[-1] == ',': print result[:-1]
611 else: print result
612
613 if options.doDecode:
614 for msg in args:
615 bv = None
616 if 'binary' == options.ioType: bv = BitVector(bitstring=msg)
617 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg)
618 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5])
619 else: sys.exit('ERROR: unknown ioType. Help!')
620
621 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList)
622