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 sls_header binary message payload to pack into an AIS Msg sls_header.
50
51 Fields in params:
52 - dac(uint): Designated Area Code 366 for US
53 - fid(uint): Functional Id (field automatically set to "1")
54 - reserved(uint): say what? (field automatically set to "0")
55 - MessageID(uint): Binary message indentifier
56 - BinaryData(binary): FIX: make this consume the rest!
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=params['dac']),10))
66 bvList.append(binary.setBitVectorSize(BitVector(intVal=1),6))
67 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
68 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['MessageID']),6))
69 bvList.append(params['BinaryData'])
70
71 return binary.joinBV(bvList)
72
73 -def decode(bv, validate=False):
74 '''Unpack a sls_header message
75
76 Fields in params:
77 - dac(uint): Designated Area Code 366 for US
78 - fid(uint): Functional Id (field automatically set to "1")
79 - reserved(uint): say what? (field automatically set to "0")
80 - MessageID(uint): Binary message indentifier
81 - BinaryData(binary): FIX: make this consume the rest!
82 @type bv: BitVector
83 @param bv: Bits defining a message
84 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
85 @rtype: dict
86 @return: params
87 '''
88
89
90
91
92 r = {}
93 r['dac']=int(bv[0:10])
94 r['fid']=1
95 r['reserved']=0
96 r['MessageID']=int(bv[18:24])
97 r['BinaryData']=bv[24:]
98 return r
99
102
104 return 1
105
107 return 0
108
110 return int(bv[18:24])
111
114
116 '''Print a sls_header message to stdout.
117
118 Fields in params:
119 - dac(uint): Designated Area Code 366 for US
120 - fid(uint): Functional Id (field automatically set to "1")
121 - reserved(uint): say what? (field automatically set to "0")
122 - MessageID(uint): Binary message indentifier
123 - BinaryData(binary): FIX: make this consume the rest!
124 @param params: Dictionary of field names/values.
125 @param out: File like object to write to
126 @rtype: stdout
127 @return: text to out
128 '''
129
130 if 'std'==format:
131 out.write("sls_header:\n")
132 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n")
133 if 'fid' in params: out.write(" fid: "+str(params['fid'])+"\n")
134 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n")
135 if 'MessageID' in params: out.write(" MessageID: "+str(params['MessageID'])+"\n")
136 if 'BinaryData' in params: out.write(" BinaryData: "+str(params['BinaryData'])+"\n")
137
138 return
139
140
141
142
143
144
145 import unittest
147 '''Return a params file base on the testvalue tags.
148 @rtype: dict
149 @return: params based on testvalue tags
150 '''
151 params = {}
152 params['dac'] = 366
153 params['fid'] = 1
154 params['reserved'] = 0
155 params['MessageID'] = 3
156 params['BinaryData'] = BitVector(bitstring='0')
157
158 return params
159
161 '''Use testvalue tag text from each type to build test case the sls_header message'''
163
164 params = testParams()
165 bits = encode(params)
166 r = decode(bits)
167
168
169 self.failUnlessEqual(r['dac'],params['dac'])
170 self.failUnlessEqual(r['fid'],params['fid'])
171 self.failUnlessEqual(r['reserved'],params['reserved'])
172 self.failUnlessEqual(r['MessageID'],params['MessageID'])
173 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
174
176 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
177 help='decode a "sls_header" AIS message')
178 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
179 help='encode a "sls_header" AIS message')
180 parser.add_option('--dac-field', dest='dacField',metavar='uint',type='int'
181 ,help='Field parameter value [default: %default]')
182 parser.add_option('--MessageID-field', dest='MessageIDField',metavar='uint',type='int'
183 ,help='Field parameter value [default: %default]')
184 parser.add_option('--BinaryData-field', dest='BinaryDataField',metavar='binary',type='string'
185 ,help='Field parameter value [default: %default]')
186
187
188 if __name__=='__main__':
189
190 from optparse import OptionParser
191 parser = OptionParser(usage="%prog [options]",
192 version="%prog "+__version__)
193
194 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
195 help='run the documentation tests')
196 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
197 help='run the unit tests')
198 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
199 help='Make the test output verbose')
200
201
202
203 typeChoices = ('binary','nmeapayload','nmea')
204 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
205 ,default='nmeapayload'
206 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
207 addMsgOptions(parser)
208
209 (options,args) = parser.parse_args()
210 success=True
211
212 if options.doctest:
213 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
214 sys.argv= [sys.argv[0]]
215 if options.verbose: sys.argv.append('-v')
216 import doctest
217 numfail,numtests=doctest.testmod()
218 if numfail==0: print 'ok'
219 else:
220 print 'FAILED'
221 success=False
222
223 if not success: sys.exit('Something Failed')
224 del success
225
226 if options.unittest:
227 sys.argv = [sys.argv[0]]
228 if options.verbose: sys.argv.append('-v')
229 unittest.main()
230
231 if options.doEncode:
232
233 if None==options.dacField: parser.error("missing value for dacField")
234 if None==options.MessageIDField: parser.error("missing value for MessageIDField")
235 if None==options.BinaryDataField: parser.error("missing value for BinaryDataField")
236 msgDict={
237 'dac': options.dacField,
238 'fid': '1',
239 'reserved': '0',
240 'MessageID': options.MessageIDField,
241 'BinaryData': options.BinaryDataField,
242 }
243
244 bits = encode(msgDict)
245 if 'binary'==options.ioType: print str(bits)
246 elif 'nmeapayload'==options.ioType:
247
248 print "bitLen",len(bits)
249 bitLen=len(bits)
250 if bitLen%6!=0:
251 bits = bits + BitVector(size=(6 - (bitLen%6)))
252 print "result:",binary.bitvectoais6(bits)[0]
253
254
255
256 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
257 else: sys.exit('ERROR: unknown ioType. Help!')
258
259 if options.doDecode:
260 for msg in args:
261 if 'binary'==options.ioType:
262 bv = BitVector(bitstring=msg)
263 printFields(decode(bv))
264
265 elif 'nmeapayload'==options.ioType:
266 bv = binary.ais6tobitvec(msg)
267 printFields(decode(bv))
268
269 elif 'nmea'==options.ioType:
270 bv = binary.ais6tobitvec(msg.split(',')[5])
271 printFields(decode(bv))
272 else: sys.exit('ERROR: unknown ioType. Help!')
273