1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2006-12-20 $'.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__ myparser
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),1))
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[39:162]
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 out.write(" MessageID: "+str(params['MessageID'])+"\n")
136 out.write(" RepeatIndicator: "+str(params['RepeatIndicator'])+"\n")
137 out.write(" UserID: "+str(params['UserID'])+"\n")
138 out.write(" Spare: "+str(params['Spare'])+"\n")
139 out.write(" BinaryData: "+str(params['BinaryData'])+"\n")
140
141 return
142
143
144
145
146
147
148 import unittest
150 '''Return a params file base on the testvalue tags.
151 @rtype: dict
152 @return: params based on testvalue tags
153 '''
154 params = {}
155 params['MessageID'] = 8
156 params['RepeatIndicator'] = 1
157 params['UserID'] = 1193046
158 params['Spare'] = 0
159 params['BinaryData'] = BitVector(bitstring='110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110')
160
161 return params
162
164 '''Use testvalue tag text from each type to build test case the bin_broadcast message'''
166
167 params = testParams()
168 bits = encode(params)
169 r = decode(bits)
170
171
172 self.failUnlessEqual(r['MessageID'],params['MessageID'])
173 self.failUnlessEqual(r['RepeatIndicator'],params['RepeatIndicator'])
174 self.failUnlessEqual(r['UserID'],params['UserID'])
175 self.failUnlessEqual(r['Spare'],params['Spare'])
176 self.failUnlessEqual(r['BinaryData'],params['BinaryData'])
177
178
179 if __name__=='__main__':
180
181 from optparse import OptionParser
182 myparser = OptionParser(usage="%prog [options]",
183 version="%prog "+__version__)
184
185
186 myparser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
187 help='run the documentation tests')
188 myparser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
189 help='run the unit tests')
190 myparser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
191 help='Make the test output verbose')
192
193
194 myparser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
195 help='decode a "bin_broadcast" AIS message')
196 myparser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
197 help='encode a "bin_broadcast" AIS message')
198
199
200
201
202 typeChoices = ('binary','nmeapayload','nmea')
203 myparser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
204 ,default='nmeapayload'
205 ,help='What kind of string to expect ('+', '.join(typeChoices)+') [default: %default]')
206
207 myparser.add_option('--RepeatIndicator-field', dest='RepeatIndicatorField',default=0
208 ,help='Field parameter value [default: %default]'
209 ,metavar='uint'
210 ,type='int'
211 )
212 myparser.add_option('--UserID-field', dest='UserIDField'
213 ,help='Field parameter value [default: %default]'
214 ,metavar='uint'
215 ,type='int'
216 )
217 myparser.add_option('--BinaryData-field', dest='BinaryDataField'
218 ,help='Field parameter value [default: %default]'
219 ,metavar='binary'
220 ,type='string'
221 )
222
223 (options,args) = myparser.parse_args()
224 success=True
225
226 if options.doctest:
227 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
228 sys.argv= [sys.argv[0]]
229 if options.verbose: sys.argv.append('-v')
230 import doctest
231 numfail,numtests=doctest.testmod()
232 if numfail==0: print 'ok'
233 else:
234 print 'FAILED'
235 success=False
236
237 if not success:
238 sys.exit('Something Failed')
239
240 del success
241
242 if options.unittest:
243 sys.argv = [sys.argv[0]]
244 if options.verbose: sys.argv.append('-v')
245 unittest.main()
246
247 if options.doEncode:
248
249 if None==options.RepeatIndicatorField: myparser.error("missing value for RepeatIndicatorField")
250 if None==options.UserIDField: myparser.error("missing value for UserIDField")
251 if None==options.BinaryDataField: myparser.error("missing value for BinaryDataField")
252 msgDict={
253 'MessageID': '8',
254 'RepeatIndicator': options.RepeatIndicatorField,
255 'UserID': options.UserIDField,
256 'Spare': '0',
257 'BinaryData': options.BinaryDataField,
258 }
259 bits = encode(msgDict)
260 if 'binary'==options.ioType: print str(bits)
261 elif 'nmeapayload'==options.ioType:
262 print "bitLen",len(bits)
263 bitLen=len(bits)
264 if bitLen%6!=0:
265 bits = bits + BitVector(size=(6 - (bitLen%6)))
266 print "result:",binary.bitvectoais6(bits)[0]
267 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
268 else: sys.exit('ERROR: unknown ioType. Help!')
269
270 if options.doDecode:
271 for msg in args:
272 if 'binary'==options.ioType:
273 bv = BitVector(bitstring=msg)
274 printFields(decode(bv))
275 elif 'nmeapayload'==options.ioType:
276 bv = binary.ais6tobitvec(msg)
277 printFields(decode(bv))
278 elif 'nmea'==options.ioType:
279 bv = binary.ais6tobitvec(msg.split(',')[5])
280 printFields(decode(bv))
281 else: sys.exit('ERROR: unknown ioType. Help!')
282