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 'MessageID',
50 'RepeatIndicator',
51 'UserID',
52 'Spare',
53 'BinaryData',
54 ]
55
56 -def encode(params, validate=False):
57 '''Create a bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast.
58
59 Fields in params:
60 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
61 - RepeatIndicator(uint): Indicated how many times a message has been repeated
62 - UserID(uint): Unique ship identification number (MMSI)
63 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
64 - BinaryData(binary): Bits for a binary broadcast message
65 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
66 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
67 @rtype: BitVector
68 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
69 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
70 '''
71
72 bvList = []
73 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6))
74 if 'RepeatIndicator' in params:
75 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
76 else:
77 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
78 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
79 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
80 bvList.append(params['BinaryData'])
81
82 return binary.joinBV(bvList)
83
84 -def decode(bv, validate=False):
85 '''Unpack a bin_broadcast message
86
87 Fields in params:
88 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
89 - RepeatIndicator(uint): Indicated how many times a message has been repeated
90 - UserID(uint): Unique ship identification number (MMSI)
91 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
92 - BinaryData(binary): Bits for a binary broadcast message
93 @type bv: BitVector
94 @param bv: Bits defining a message
95 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
96 @rtype: dict
97 @return: params
98 '''
99
100
101
102
103 r = {}
104 r['MessageID']=8
105 r['RepeatIndicator']=int(bv[6:8])
106 r['UserID']=int(bv[8:38])
107 r['Spare']=0
108 r['BinaryData']=bv[40:]
109 return r
110
112 return 8
113
116
119
121 return 0
122
125
126
128 out.write("<h3>bin_broadcast<h3>\n")
129 out.write("<table border=\"1\">\n")
130 out.write("<tr bgcolor=\"orange\">\n")
131 out.write("<th align=\"left\">Field Name</th>\n")
132 out.write("<th align=\"left\">Type</th>\n")
133 out.write("<th align=\"left\">Value</th>\n")
134 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
135 out.write("<th align=\"left\">Units</th>\n")
136 out.write("\n")
137 out.write("<tr>\n")
138 out.write("<td>MessageID</td>\n")
139 out.write("<td>uint</td>\n")
140 if 'MessageID' in params:
141 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
142 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
143 out.write("</tr>\n")
144 out.write("\n")
145 out.write("<tr>\n")
146 out.write("<td>RepeatIndicator</td>\n")
147 out.write("<td>uint</td>\n")
148 if 'RepeatIndicator' in params:
149 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n")
150 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut:
151 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>")
152 else:
153 out.write("<td><i>Missing LUT entry</i></td>")
154 out.write("</tr>\n")
155 out.write("\n")
156 out.write("<tr>\n")
157 out.write("<td>UserID</td>\n")
158 out.write("<td>uint</td>\n")
159 if 'UserID' in params:
160 out.write(" <td>"+str(params['UserID'])+"</td>\n")
161 out.write(" <td>"+str(params['UserID'])+"</td>\n")
162 out.write("</tr>\n")
163 out.write("\n")
164 out.write("<tr>\n")
165 out.write("<td>Spare</td>\n")
166 out.write("<td>uint</td>\n")
167 if 'Spare' in params:
168 out.write(" <td>"+str(params['Spare'])+"</td>\n")
169 out.write(" <td>"+str(params['Spare'])+"</td>\n")
170 out.write("</tr>\n")
171 out.write("\n")
172 out.write("<tr>\n")
173 out.write("<td>BinaryData</td>\n")
174 out.write("<td>binary</td>\n")
175 if 'BinaryData' in params:
176 out.write(" <td>"+str(params['BinaryData'])+"</td>\n")
177 out.write(" <td>"+str(params['BinaryData'])+"</td>\n")
178 out.write("</tr>\n")
179 out.write("</table>\n")
180
181 -def printFields(params, out=sys.stdout, format='std', fieldList=None):
182 '''Print a BinaryData message to stdout.
183
184 Fields in params:
185 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
186 - RepeatIndicator(uint): Indicated how many times a message has been repeated
187 - UserID(uint): Unique ship identification number (MMSI)
188 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
189 - BinaryData(binary): Bits for a binary broadcast message
190 @param params: Dictionary of field names/values.
191 @param out: File like object to write to
192 @rtype: stdout
193 @return: text to out
194 '''
195
196 if 'std'==format:
197 out.write("BinaryData:\n")
198 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
199 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
200 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
201 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
202 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n")
203 elif 'csv'==format:
204 if None == options.fieldList:
205 options.fieldList = fieldList
206 needComma = False;
207 for field in fieldList:
208 if needComma: out.write(',')
209 needComma = True
210 if field in params:
211 out.write(str(params[field]))
212
213 out.write("\n")
214 elif 'html'==format:
215 printHtml(params,out)
216 elif 'sql'==format:
217 sqlInsertStr(params,out)
218 else:
219 print "ERROR: unknown format:",format
220 assert False
221
222 return
223
224 RepeatIndicatorEncodeLut = {
225 'default':'0',
226 'do not repeat any more':'3',
227 }
228
229 RepeatIndicatorDecodeLut = {
230 '0':'default',
231 '3':'do not repeat any more',
232 }
233
234
235
236
237
238 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None):
239 '''
240 Return the SQL CREATE command for this message type
241 @param outfile: file like object to print to.
242 @param fields: which fields to put in the create. Defaults to all.
243 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
244 @return: sql create string
245 @rtype: str
246
247 @see: sqlCreate
248 '''
249 outfile.write(str(sqlCreate(fields,extraFields)))
250
251 -def sqlCreate(fields=None, extraFields=None):
252 '''
253 Return the sqlhelp object to create the table.
254
255 @param fields: which fields to put in the create. Defaults to all.
256 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
257 @return: An object that can be used to generate a return
258 @rtype: sqlhelp.create
259 '''
260 if None == fields: fields = fieldList
261 import sqlhelp
262 c = sqlhelp.create('bin_broadcast')
263 if 'MessageID' in fields: c.addInt ('MessageID')
264 if 'RepeatIndicator' in fields: c.addInt ('RepeatIndicator')
265 if 'UserID' in fields: c.addInt ('UserID')
266 if 'Spare' in fields: c.addInt ('Spare')
267 if 'BinaryData' in fields: c.addBitVarying('BinaryData',1024)
268
269 return c
270
271 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None):
272 '''
273 Return the SQL CREATE command for this message type
274 @param params: dictionary of values keyed by field name
275 @param outfile: file like object to print to.
276 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
277 @return: sql create string
278 @rtype: str
279
280 @see: sqlCreate
281 '''
282 outfile.write(str(sqlInsert(params,extraParams)))
283
284
286 '''
287 Give the SQL insert statement
288 @param params: dict keyed by field name of values
289 @param extraParams: any extra fields that you have created beyond the normal ais message fields
290 @rtype: sqlhelp.insert
291 @return: insert class instance
292 @todo: allow optional type checking of params?
293 @warning: this will take invalid keys happily and do what???
294 '''
295 import sqlhelp
296 i = sqlhelp.insert('bin_broadcast')
297 for key in params: i.add(key,params[key])
298 if None != extraParams:
299 for key in extraParams:
300 i.add(key,extraParams[key])
301
302 return i
303
304
305
306
307
308 import unittest
310 '''Return a params file base on the testvalue tags.
311 @rtype: dict
312 @return: params based on testvalue tags
313 '''
314 params = {}
315 params['MessageID'] = 8
316 params['RepeatIndicator'] = 1
317 params['UserID'] = 1193046
318 params['Spare'] = 0
319 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110')
320
321 return params
322
324 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
326
327 params = testParams()
328 bits = encode(params)
329 r = decode(bits)
330
331
332 self.failUnlessEqual(r['MessageID'],params['MessageID'])
333 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
334 self.failUnlessEqual(r['UserID'],params['UserID'])
335 self.failUnlessEqual(r['Spare'],params['Spare'])
336 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
337
339 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
340 help='decode a "bin_broadcast" AIS message')
341 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
342 help='encode a "bin_broadcast" AIS message')
343 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
344 ,help='Field parameter value [default: %default]')
345 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
346 ,help='Field parameter value [default: %default]')
347 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string'
348 ,help='Field parameter value [default: %default]')
349
350
351 if __name__=='__main__':
352
353 from optparse import OptionParser
354 parser = OptionParser(usage="%prog [options]",
355 version="%prog "+__version__)
356
357 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
358 help='run the documentation tests')
359 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
360 help='run the unit tests')
361 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
362 help='Make the test output verbose')
363
364
365
366 typeChoices = ('binary','nmeapayload','nmea')
367 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
368 ,default='nmeapayload'
369 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
370
371
372 outputChoices = ('std','html','csv','sql' )
373 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
374 ,default='std'
375 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
376
377 parser.add_option('-o','--output',dest='outputFileName',default=None,
378 help='Name of the python file to write [default: stdout]')
379
380 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
381 choices=fieldList,
382 help='Which fields to include in the output. Currently only for csv output [default: all]')
383
384 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
385 help='Print the field name for csv')
386
387 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
388 help='Print out an sql create command for the table.')
389
390 addMsgOptions(parser)
391
392 (options,args) = parser.parse_args()
393 success=True
394
395 if options.doctest:
396 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
397 sys.argv= [sys.argv[0]]
398 if options.verbose: sys.argv.append('-v')
399 import doctest
400 numfail,numtests=doctest.testmod()
401 if numfail==0: print 'ok'
402 else:
403 print 'FAILED'
404 success=False
405
406 if not success: sys.exit('Something Failed')
407 del success
408
409 if options.unittest:
410 sys.argv = [sys.argv[0]]
411 if options.verbose: sys.argv.append('-v')
412 unittest.main()
413
414 outfile = sys.stdout
415 if None!=options.outputFileName:
416 outfile = file(options.outputFileName,'w')
417
418
419 if options.doEncode:
420
421 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
422 if None==options.UserIDField: parser.error("missing value for UserIDField")
423 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField")
424 msgDict={
425 'MessageID': '8',
426 'RepeatIndicator': options.RepeatIndicatorField,
427 'UserID': options.UserIDField,
428 'Spare': '0',
429 'BinaryData': options.BinaryDataField,
430 }
431
432 bits = encode(msgDict)
433 if 'binary'==options.ioType: print str(bits)
434 elif 'nmeapayload'==options.ioType:
435
436 print "bitLen",len(bits)
437 bitLen=len(bits)
438 if bitLen%6!=0:
439 bits = bits + BitVector(size=(6 - (bitLen%6)))
440 print "result:",binary.bitvectoais6(bits)[0]
441
442
443
444 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
445 else: sys.exit('ERROR: unknown ioType. Help!')
446
447
448 if options.sqlCreate:
449 sqlCreateStr(outfile,options.fieldList)
450
451 if options.printCsvfieldList:
452
453 if None == options.fieldList: options.fieldList = fieldList
454 import StringIO
455 buf = StringIO.StringIO()
456 for field in options.fieldList:
457 buf.write(field+',')
458 result = buf.getvalue()
459 if result[-1] == ',': print result[:-1]
460 else: print result
461
462 if options.doDecode:
463 for msg in args:
464 bv = None
465 if 'binary' == options.ioType: bv = BitVector(bitstring=msg)
466 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg)
467 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5])
468 else: sys.exit('ERROR: unknown ioType. Help!')
469
470 printFields(decode(bv),out=outfile,format=options.outputType,fieldList=options.fieldList)
471