1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-01-04 $'.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 bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast.
50
51 Fields in params:
52 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
53 - RepeatIndicator(uint): Indicated how many times a message has been repeated
54 - UserID(uint): Unique ship identification number (MMSI)
55 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
56 - BinaryData(binary): Bits for a binary broadcast message
57 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
58 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
59 @rtype: BitVector
60 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
61 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
62 '''
63
64 bvList = []
65 bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6))
66 if 'RepeatIndicator' in params:
67 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
68 else:
69 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
70 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
71 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
72 bvList.append(params['BinaryData'])
73
74 return binary.joinBV(bvList)
75
76 -def decode(bv, validate=False):
77 '''Unpack a bin_broadcast message
78
79 Fields in params:
80 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
81 - RepeatIndicator(uint): Indicated how many times a message has been repeated
82 - UserID(uint): Unique ship identification number (MMSI)
83 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
84 - BinaryData(binary): Bits for a binary broadcast message
85 @type bv: BitVector
86 @param bv: Bits defining a message
87 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
88 @rtype: dict
89 @return: params
90 '''
91
92
93
94
95 r = {}
96 r['MessageID']=8
97 r['RepeatIndicator']=int(bv[6:8])
98 r['UserID']=int(bv[8:38])
99 r['Spare']=0
100 r['BinaryData']=bv[40:]
101 return r
102
104 return 8
105
108
111
113 return 0
114
117
119 '''Print a bin_broadcast message to stdout.
120
121 Fields in params:
122 - MessageID(uint): AIS message number. Must be 8 (field automatically set to "8")
123 - RepeatIndicator(uint): Indicated how many times a message has been repeated
124 - UserID(uint): Unique ship identification number (MMSI)
125 - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
126 - BinaryData(binary): Bits for a binary broadcast message
127 @param params: Dictionary of field names/values.
128 @param out: File like object to write to
129 @rtype: stdout
130 @return: text to out
131 '''
132
133 if 'std'==format:
134 out.write("bin_broadcast:\n")
135 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
136 if 'RepeatIndicator' in params: out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
137 if 'UserID' in params: out.write(" UserID: "+str(params['UserID'])+"\n")
138 if 'Spare' in params: out.write(" Spare: "+str(params['Spare'])+"\n")
139 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n")
140 elif 'html'==format:
141 out.write("<h3>BinaryData<h3>\n")
142 out.write("<table border=\"1\">\n")
143 out.write("<tr bgcolor=\"orange\">\n")
144 out.write("<th align=\"left\">Field Name</th>\n")
145 out.write("<th align=\"left\">Type</th>\n")
146 out.write("<th align=\"left\">Value</th>\n")
147 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
148 out.write("\n")
149 out.write("<tr>\n")
150 out.write("<td>MessageID</td>\n")
151 out.write("<td>uint</td>\n")
152 if 'MessageID' in params:
153 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
154 out.write(" <td>"+str(params['MessageID'])+"</td>\n")
155 out.write("</tr>\n")
156 out.write("\n")
157 out.write("<tr>\n")
158 out.write("<td>RepeatIndicator</td>\n")
159 out.write("<td>uint</td>\n")
160 if 'RepeatIndicator' in params:
161 out.write(" <td>"+str(params['RepeatIndicator'])+"</td>\n")
162 if str(params['RepeatIndicator']) in RepeatIndicatorDecodeLut:
163 out.write("<td>"+RepeatIndicatorDecodeLut[str(params['RepeatIndicator'])]+"</td>")
164 else:
165 out.write("<td><i>Missing LUT entry</i></td>")
166 out.write("</tr>\n")
167 out.write("\n")
168 out.write("<tr>\n")
169 out.write("<td>UserID</td>\n")
170 out.write("<td>uint</td>\n")
171 if 'UserID' in params:
172 out.write(" <td>"+str(params['UserID'])+"</td>\n")
173 out.write(" <td>"+str(params['UserID'])+"</td>\n")
174 out.write("</tr>\n")
175 out.write("\n")
176 out.write("<tr>\n")
177 out.write("<td>Spare</td>\n")
178 out.write("<td>uint</td>\n")
179 if 'Spare' in params:
180 out.write(" <td>"+str(params['Spare'])+"</td>\n")
181 out.write(" <td>"+str(params['Spare'])+"</td>\n")
182 out.write("</tr>\n")
183 out.write("\n")
184 out.write("<tr>\n")
185 out.write("<td>BinaryData</td>\n")
186 out.write("<td>binary</td>\n")
187 if 'BinaryData' in params:
188 out.write(" <td>"+str(params['BinaryData'])+"</td>\n")
189 out.write(" <td>"+str(params['BinaryData'])+"</td>\n")
190 out.write("</tr>\n")
191 out.write("</table>\n")
192 else:
193 print "ERROR: unknown format:",format
194 assert False
195
196 return
197
198 RepeatIndicatorEncodeLut = {
199 'default':'0',
200 'do not repeat any more':'3',
201 }
202
203 RepeatIndicatorDecodeLut = {
204 '0':'default',
205 '3':'do not repeat any more',
206 }
207
208
209
210
211
212
213 import unittest
215 '''Return a params file base on the testvalue tags.
216 @rtype: dict
217 @return: params based on testvalue tags
218 '''
219 params = {}
220 params['MessageID'] = 8
221 params['RepeatIndicator'] = 1
222 params['UserID'] = 1193046
223 params['Spare'] = 0
224 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110')
225
226 return params
227
229 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
231
232 params = testParams()
233 bits = encode(params)
234 r = decode(bits)
235
236
237 self.failUnlessEqual(r['MessageID'],params['MessageID'])
238 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
239 self.failUnlessEqual(r['UserID'],params['UserID'])
240 self.failUnlessEqual(r['Spare'],params['Spare'])
241 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
242
244 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
245 help='decode a "bin_broadcast" AIS message')
246 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
247 help='encode a "bin_broadcast" AIS message')
248 parser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0,metavar='uint',type='int'
249 ,help='Field parameter value [default: %default]')
250 parser.add_option('--UserID-field', dest='UserIDField',metavar='uint',type='int'
251 ,help='Field parameter value [default: %default]')
252 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string'
253 ,help='Field parameter value [default: %default]')
254
255
256 if __name__=='__main__':
257
258 from optparse import OptionParser
259 parser = OptionParser(usage="%prog [options]",
260 version="%prog "+__version__)
261
262 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
263 help='run the documentation tests')
264 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
265 help='run the unit tests')
266 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
267 help='Make the test output verbose')
268
269
270
271 typeChoices = ('binary','nmeapayload','nmea')
272 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
273 ,default='nmeapayload'
274 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
275
276 outputChoices = ('std','html','xml')
277 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
278 ,default='std'
279 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
280
281 parser.add_option('-o','--output',dest='outputFileName',default=None,
282 help='Name of the python file to write [default: stdout]')
283
284 addMsgOptions(parser)
285
286 (options,args) = parser.parse_args()
287 success=True
288
289 if options.doctest:
290 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
291 sys.argv= [sys.argv[0]]
292 if options.verbose: sys.argv.append('-v')
293 import doctest
294 numfail,numtests=doctest.testmod()
295 if numfail==0: print 'ok'
296 else:
297 print 'FAILED'
298 success=False
299
300 if not success: sys.exit('Something Failed')
301 del success
302
303 if options.unittest:
304 sys.argv = [sys.argv[0]]
305 if options.verbose: sys.argv.append('-v')
306 unittest.main()
307
308 outfile = sys.stdout
309 if None!=options.outputFileName:
310 outfile = file(options.outputFileName,'w')
311
312
313 if options.doEncode:
314
315 if None==options.RepeatIndicatorField: parser.error("missing value for RepeatIndicatorField")
316 if None==options.UserIDField: parser.error("missing value for UserIDField")
317 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField")
318 msgDict={
319 'MessageID': '8',
320 'RepeatIndicator': options.RepeatIndicatorField,
321 'UserID': options.UserIDField,
322 'Spare': '0',
323 'BinaryData': options.BinaryDataField,
324 }
325
326 bits = encode(msgDict)
327 if 'binary'==options.ioType: print str(bits)
328 elif 'nmeapayload'==options.ioType:
329
330 print "bitLen",len(bits)
331 bitLen=len(bits)
332 if bitLen%6!=0:
333 bits = bits + BitVector(size=(6 - (bitLen%6)))
334 print "result:",binary.bitvectoais6(bits)[0]
335
336
337
338 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
339 else: sys.exit('ERROR: unknown ioType. Help!')
340
341 if options.doDecode:
342 for msg in args:
343 bv = None
344 if 'binary' == options.ioType: bv = BitVector(bitstring=msg)
345 elif 'nmeapayload'== options.ioType: bv = binary.ais6tobitvec(msg)
346 elif 'nmea' == options.ioType: bv = binary.ais6tobitvec(msg.split(',')[5])
347 else: sys.exit('ERROR: unknown ioType. Help!')
348
349 printFields(decode(bv),out=outfile,format=options.outputType)
350