1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-01-02 $'.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 alltypesmsg binary message payload to pack into an AIS Msg alltypesmsg.
50
51 Fields in params:
52 - dac(uint): Designated Area Code (field automatically set to "366")
53 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
54 - unavail_uint(uint): Unavailable unsigned integer
55 - anUInt(uint): NO unavailable unsigned integer
56 - anInt(int): NO unavailable signed integer
57 - aBool(bool): Simple bool
58 - aStr(aisstr6): An ais string of 5 characters
59 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
60 - aDecimal(decimal): A decimal
61 - aFloat(float): An IEEE floating point number
62 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
63 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
64 @rtype: BitVector
65 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
66 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
67 '''
68
69 bvList = []
70 bvList.append(binary.setBitVectorSize(BitVector(intVal=366),16))
71 bvList.append(binary.bvFromSignedInt(122,8))
72 if 'unavail_uint' in params:
73 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['unavail_uint']),2))
74 else:
75 bvList.append(binary.setBitVectorSize(BitVector(intVal=3),2))
76 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['anUInt']),2))
77 bvList.append(binary.bvFromSignedInt(params['anInt'],3))
78 if params["aBool"]: bvList.append(TrueBV)
79 else: bvList.append(FalseBV)
80 bvList.append(aisstring.encode(params['aStr'],30))
81 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['anUDecimal'])*Decimal('10')))),16))
82 bvList.append(binary.bvFromSignedInt(int(Decimal(params['aDecimal'])*Decimal('10')),16))
83 bvList.append(binary.float2bitvec(params['aFloat']))
84
85 return binary.joinBV(bvList)
86
87 -def decode(bv, validate=False):
88 '''Unpack a alltypesmsg message
89
90 Fields in params:
91 - dac(uint): Designated Area Code (field automatically set to "366")
92 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
93 - unavail_uint(uint): Unavailable unsigned integer
94 - anUInt(uint): NO unavailable unsigned integer
95 - anInt(int): NO unavailable signed integer
96 - aBool(bool): Simple bool
97 - aStr(aisstr6): An ais string of 5 characters
98 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
99 - aDecimal(decimal): A decimal
100 - aFloat(float): An IEEE floating point number
101 @type bv: BitVector
102 @param bv: Bits defining a message
103 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
104 @rtype: dict
105 @return: params
106 '''
107
108
109
110
111 r = {}
112 r['dac']=366
113 r['reqDecimal']=122/Decimal('1')
114 r['unavail_uint']=int(bv[24:26])
115 r['anUInt']=int(bv[26:28])
116 r['anInt']=binary.signedIntFromBV(bv[28:31])
117 r['aBool']=bool(int(bv[31:32]))
118 r['aStr']=aisstring.decode(bv[32:62])
119 r['anUDecimal']=Decimal(int(bv[62:78]))/Decimal('10')
120 r['aDecimal']=Decimal(binary.signedIntFromBV(bv[78:94]))/Decimal('10')
121 r['aFloat']=binary.bitvec2float(bv[94:126])
122 return r
123
125 return 366
126
128 return 122/Decimal('1')
129
131 return int(bv[24:26])
132
134 return int(bv[26:28])
135
138
140 return bool(int(bv[31:32]))
141
144
146 return Decimal(int(bv[62:78]))/Decimal('10')
147
150
153
155 '''Print a alltypesmsg message to stdout.
156
157 Fields in params:
158 - dac(uint): Designated Area Code (field automatically set to "366")
159 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
160 - unavail_uint(uint): Unavailable unsigned integer
161 - anUInt(uint): NO unavailable unsigned integer
162 - anInt(int): NO unavailable signed integer
163 - aBool(bool): Simple bool
164 - aStr(aisstr6): An ais string of 5 characters
165 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
166 - aDecimal(decimal): A decimal
167 - aFloat(float): An IEEE floating point number
168 @param params: Dictionary of field names/values.
169 @param out: File like object to write to
170 @rtype: stdout
171 @return: text to out
172 '''
173
174 if 'std'==format:
175 out.write("alltypesmsg:\n")
176 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n")
177 if 'reqDecimal' in params: out.write(" reqDecimal: "+str(params['reqDecimal'])+"\n")
178 if 'unavail_uint' in params: out.write(" unavail_uint: "+str(params['unavail_uint'])+"\n")
179 if 'anUInt' in params: out.write(" anUInt: "+str(params['anUInt'])+"\n")
180 if 'anInt' in params: out.write(" anInt: "+str(params['anInt'])+"\n")
181 if 'aBool' in params: out.write(" aBool: "+str(params['aBool'])+"\n")
182 if 'aStr' in params: out.write(" aStr: "+str(params['aStr'])+"\n")
183 if 'anUDecimal' in params: out.write(" anUDecimal: "+str(params['anUDecimal'])+"\n")
184 if 'aDecimal' in params: out.write(" aDecimal: "+str(params['aDecimal'])+"\n")
185 if 'aFloat' in params: out.write(" aFloat: "+str(params['aFloat'])+"\n")
186
187 return
188
189
190
191
192
193
194 import unittest
196 '''Return a params file base on the testvalue tags.
197 @rtype: dict
198 @return: params based on testvalue tags
199 '''
200 params = {}
201 params['dac'] = 366
202 params['reqDecimal'] = Decimal('122')
203 params['unavail_uint'] = 2
204 params['anUInt'] = 1
205 params['anInt'] = -1
206 params['aBool'] = True
207 params['aStr'] = 'ASDF1'
208 params['anUDecimal'] = Decimal('9.5')
209 params['aDecimal'] = Decimal('-9.6')
210 params['aFloat'] = -1234.5678
211
212 return params
213
215 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
217
218 params = testParams()
219 bits = encode(params)
220 r = decode(bits)
221
222
223 self.failUnlessEqual(r['dac'],params['dac'])
224 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],3)
225 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint'])
226 self.failUnlessEqual(r['anUInt'],params['anUInt'])
227 self.failUnlessEqual(r['anInt'],params['anInt'])
228 self.failUnlessEqual(r['aBool'],params['aBool'])
229 self.failUnlessEqual(r['aStr'],params['aStr'])
230 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1)
231 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0)
232 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
233
235 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
236 help='decode a "alltypesmsg" AIS message')
237 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
238 help='encode a "alltypesmsg" AIS message')
239 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int'
240 ,help='Field parameter value [default: %default]')
241 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int'
242 ,help='Field parameter value [default: %default]')
243 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int'
244 ,help='Field parameter value [default: %default]')
245 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int'
246 ,help='Field parameter value [default: %default]')
247 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string'
248 ,help='Field parameter value [default: %default]')
249 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string'
250 ,help='Field parameter value [default: %default]')
251 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string'
252 ,help='Field parameter value [default: %default]')
253 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float'
254 ,help='Field parameter value [default: %default]')
255
256
257 if __name__=='__main__':
258
259 from optparse import OptionParser
260 parser = OptionParser(usage="%prog [options]",
261 version="%prog "+__version__)
262
263 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
264 help='run the documentation tests')
265 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
266 help='run the unit tests')
267 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
268 help='Make the test output verbose')
269
270
271
272 typeChoices = ('binary','nmeapayload','nmea')
273 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
274 ,default='nmeapayload'
275 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
276 addMsgOptions(parser)
277
278 (options,args) = parser.parse_args()
279 success=True
280
281 if options.doctest:
282 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
283 sys.argv= [sys.argv[0]]
284 if options.verbose: sys.argv.append('-v')
285 import doctest
286 numfail,numtests=doctest.testmod()
287 if numfail==0: print 'ok'
288 else:
289 print 'FAILED'
290 success=False
291
292 if not success: sys.exit('Something Failed')
293 del success
294
295 if options.unittest:
296 sys.argv = [sys.argv[0]]
297 if options.verbose: sys.argv.append('-v')
298 unittest.main()
299
300 if options.doEncode:
301
302 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField")
303 if None==options.anUIntField: parser.error("missing value for anUIntField")
304 if None==options.anIntField: parser.error("missing value for anIntField")
305 if None==options.aBoolField: parser.error("missing value for aBoolField")
306 if None==options.aStrField: parser.error("missing value for aStrField")
307 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField")
308 if None==options.aDecimalField: parser.error("missing value for aDecimalField")
309 if None==options.aFloatField: parser.error("missing value for aFloatField")
310 msgDict={
311 'dac': '366',
312 'reqDecimal': '122',
313 'unavail_uint': options.unavail_uintField,
314 'anUInt': options.anUIntField,
315 'anInt': options.anIntField,
316 'aBool': options.aBoolField,
317 'aStr': options.aStrField,
318 'anUDecimal': options.anUDecimalField,
319 'aDecimal': options.aDecimalField,
320 'aFloat': options.aFloatField,
321 }
322
323 bits = encode(msgDict)
324 if 'binary'==options.ioType: print str(bits)
325 elif 'nmeapayload'==options.ioType:
326
327 print "bitLen",len(bits)
328 bitLen=len(bits)
329 if bitLen%6!=0:
330 bits = bits + BitVector(size=(6 - (bitLen%6)))
331 print "result:",binary.bitvectoais6(bits)[0]
332
333
334
335 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
336 else: sys.exit('ERROR: unknown ioType. Help!')
337
338 if options.doDecode:
339 for msg in args:
340 if 'binary'==options.ioType:
341 bv = BitVector(bitstring=msg)
342 printFields(decode(bv))
343
344 elif 'nmeapayload'==options.ioType:
345 bv = binary.ais6tobitvec(msg)
346 printFields(decode(bv))
347
348 elif 'nmea'==options.ioType:
349 bv = binary.ais6tobitvec(msg.split(',')[5])
350 printFields(decode(bv))
351 else: sys.exit('ERROR: unknown ioType. Help!')
352