1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2008-01-09 $'.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 @todo: FIX: put in a description of the message here with fields and types.
34 '''
35
36 import sys
37 from decimal import Decimal
38 from BitVector import BitVector
39
40 import binary, aisstring
41
42
43 TrueBV = BitVector(bitstring="1")
44 "Why always rebuild the True bit? This should speed things up a bunch"
45 FalseBV = BitVector(bitstring="0")
46 "Why always rebuild the False bit? This should speed things up a bunch"
47
48
49 fieldList = (
50 'dac',
51 'reqDecimal',
52 'unavail_uint',
53 'anUInt',
54 'anInt',
55 'aBool',
56 'aStr',
57 'anUDecimal',
58 'aDecimal',
59 'aFloat',
60 )
61
62 fieldListPostgres = (
63 'dac',
64 'reqDecimal',
65 'unavail_uint',
66 'anUInt',
67 'anInt',
68 'aBool',
69 'aStr',
70 'anUDecimal',
71 'aDecimal',
72 'aFloat',
73 )
74
75 toPgFields = {
76 }
77 '''
78 Go to the Postgis field names from the straight field name
79 '''
80
81 fromPgFields = {
82 }
83 '''
84 Go from the Postgis field names to the straight field name
85 '''
86
87 pgTypes = {
88 }
89 '''
90 Lookup table for each postgis field name to get its type.
91 '''
92
93 -def encode(params, validate=False):
94 '''Create a alltypesmsg binary message payload to pack into an AIS Msg alltypesmsg.
95
96 Fields in params:
97 - dac(uint): Designated Area Code (field automatically set to "366")
98 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
99 - unavail_uint(uint): Unavailable unsigned integer
100 - anUInt(uint): NO unavailable unsigned integer
101 - anInt(int): NO unavailable signed integer
102 - aBool(bool): Simple bool
103 - aStr(aisstr6): An ais string of 5 characters
104 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
105 - aDecimal(decimal): A decimal
106 - aFloat(float): An IEEE floating point number
107 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
108 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
109 @rtype: BitVector
110 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
111 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
112 '''
113
114 bvList = []
115 bvList.append(binary.setBitVectorSize(BitVector(intVal=366),16))
116 bvList.append(binary.bvFromSignedInt(122,8))
117 if 'unavail_uint' in params:
118 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['unavail_uint']),2))
119 else:
120 bvList.append(binary.setBitVectorSize(BitVector(intVal=3),2))
121 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['anUInt']),2))
122 bvList.append(binary.bvFromSignedInt(params['anInt'],3))
123 if params["aBool"]: bvList.append(TrueBV)
124 else: bvList.append(FalseBV)
125 bvList.append(aisstring.encode(params['aStr'],30))
126 bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['anUDecimal'])*Decimal('10')))),16))
127 bvList.append(binary.bvFromSignedInt(int(Decimal(params['aDecimal'])*Decimal('10')),16))
128 bvList.append(binary.float2bitvec(params['aFloat']))
129
130 return binary.joinBV(bvList)
131
132 -def decode(bv, validate=False):
133 '''Unpack a alltypesmsg message
134
135 Fields in params:
136 - dac(uint): Designated Area Code (field automatically set to "366")
137 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
138 - unavail_uint(uint): Unavailable unsigned integer
139 - anUInt(uint): NO unavailable unsigned integer
140 - anInt(int): NO unavailable signed integer
141 - aBool(bool): Simple bool
142 - aStr(aisstr6): An ais string of 5 characters
143 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
144 - aDecimal(decimal): A decimal
145 - aFloat(float): An IEEE floating point number
146 @type bv: BitVector
147 @param bv: Bits defining a message
148 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
149 @rtype: dict
150 @return: params
151 '''
152
153
154
155
156 r = {}
157 r['dac']=366
158 r['reqDecimal']=122/Decimal('1')
159 r['unavail_uint']=int(bv[24:26])
160 r['anUInt']=int(bv[26:28])
161 r['anInt']=binary.signedIntFromBV(bv[28:31])
162 r['aBool']=bool(int(bv[31:32]))
163 r['aStr']=aisstring.decode(bv[32:62])
164 r['anUDecimal']=Decimal(int(bv[62:78]))/Decimal('10')
165 r['aDecimal']=Decimal(binary.signedIntFromBV(bv[78:94]))/Decimal('10')
166 r['aFloat']=binary.bitvec2float(bv[94:126])
167 return r
168
171
173 return 122/Decimal('1')
174
176 return int(bv[24:26])
177
179 return int(bv[26:28])
180
183
185 return bool(int(bv[31:32]))
186
189
191 return Decimal(int(bv[62:78]))/Decimal('10')
192
195
198
199
201 out.write("<h3>alltypesmsg</h3>\n")
202 out.write("<table border=\"1\">\n")
203 out.write("<tr bgcolor=\"orange\">\n")
204 out.write("<th align=\"left\">Field Name</th>\n")
205 out.write("<th align=\"left\">Type</th>\n")
206 out.write("<th align=\"left\">Value</th>\n")
207 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
208 out.write("<th align=\"left\">Units</th>\n")
209 out.write("\n")
210 out.write("<tr>\n")
211 out.write("<td>dac</td>\n")
212 out.write("<td>uint</td>\n")
213 if 'dac' in params:
214 out.write(" <td>"+str(params['dac'])+"</td>\n")
215 out.write(" <td>"+str(params['dac'])+"</td>\n")
216 out.write("</tr>\n")
217 out.write("\n")
218 out.write("<tr>\n")
219 out.write("<td>reqDecimal</td>\n")
220 out.write("<td>decimal</td>\n")
221 if 'reqDecimal' in params:
222 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n")
223 out.write(" <td>"+str(params['reqDecimal'])+"</td>\n")
224 out.write("</tr>\n")
225 out.write("\n")
226 out.write("<tr>\n")
227 out.write("<td>unavail_uint</td>\n")
228 out.write("<td>uint</td>\n")
229 if 'unavail_uint' in params:
230 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n")
231 out.write(" <td>"+str(params['unavail_uint'])+"</td>\n")
232 out.write("</tr>\n")
233 out.write("\n")
234 out.write("<tr>\n")
235 out.write("<td>anUInt</td>\n")
236 out.write("<td>uint</td>\n")
237 if 'anUInt' in params:
238 out.write(" <td>"+str(params['anUInt'])+"</td>\n")
239 out.write(" <td>"+str(params['anUInt'])+"</td>\n")
240 out.write("</tr>\n")
241 out.write("\n")
242 out.write("<tr>\n")
243 out.write("<td>anInt</td>\n")
244 out.write("<td>int</td>\n")
245 if 'anInt' in params:
246 out.write(" <td>"+str(params['anInt'])+"</td>\n")
247 out.write(" <td>"+str(params['anInt'])+"</td>\n")
248 out.write("</tr>\n")
249 out.write("\n")
250 out.write("<tr>\n")
251 out.write("<td>aBool</td>\n")
252 out.write("<td>bool</td>\n")
253 if 'aBool' in params:
254 out.write(" <td>"+str(params['aBool'])+"</td>\n")
255 out.write(" <td>"+str(params['aBool'])+"</td>\n")
256 out.write("</tr>\n")
257 out.write("\n")
258 out.write("<tr>\n")
259 out.write("<td>aStr</td>\n")
260 out.write("<td>aisstr6</td>\n")
261 if 'aStr' in params:
262 out.write(" <td>"+str(params['aStr'])+"</td>\n")
263 out.write(" <td>"+str(params['aStr'])+"</td>\n")
264 out.write("</tr>\n")
265 out.write("\n")
266 out.write("<tr>\n")
267 out.write("<td>anUDecimal</td>\n")
268 out.write("<td>udecimal</td>\n")
269 if 'anUDecimal' in params:
270 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n")
271 out.write(" <td>"+str(params['anUDecimal'])+"</td>\n")
272 out.write("</tr>\n")
273 out.write("\n")
274 out.write("<tr>\n")
275 out.write("<td>aDecimal</td>\n")
276 out.write("<td>decimal</td>\n")
277 if 'aDecimal' in params:
278 out.write(" <td>"+str(params['aDecimal'])+"</td>\n")
279 out.write(" <td>"+str(params['aDecimal'])+"</td>\n")
280 out.write("</tr>\n")
281 out.write("\n")
282 out.write("<tr>\n")
283 out.write("<td>aFloat</td>\n")
284 out.write("<td>float</td>\n")
285 if 'aFloat' in params:
286 out.write(" <td>"+str(params['aFloat'])+"</td>\n")
287 out.write(" <td>"+str(params['aFloat'])+"</td>\n")
288 out.write("</tr>\n")
289 out.write("</table>\n")
290
291 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
292 '''Print a alltypesmsg message to stdout.
293
294 Fields in params:
295 - dac(uint): Designated Area Code (field automatically set to "366")
296 - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
297 - unavail_uint(uint): Unavailable unsigned integer
298 - anUInt(uint): NO unavailable unsigned integer
299 - anInt(int): NO unavailable signed integer
300 - aBool(bool): Simple bool
301 - aStr(aisstr6): An ais string of 5 characters
302 - anUDecimal(udecimal): An unsigned decimal. Allow smaller numbers
303 - aDecimal(decimal): A decimal
304 - aFloat(float): An IEEE floating point number
305 @param params: Dictionary of field names/values.
306 @param out: File like object to write to
307 @rtype: stdout
308 @return: text to out
309 '''
310
311 if 'std'==format:
312 out.write("alltypesmsg:\n")
313 if 'dac' in params: out.write(" dac: "+str(params['dac'])+"\n")
314 if 'reqDecimal' in params: out.write(" reqDecimal: "+str(params['reqDecimal'])+"\n")
315 if 'unavail_uint' in params: out.write(" unavail_uint: "+str(params['unavail_uint'])+"\n")
316 if 'anUInt' in params: out.write(" anUInt: "+str(params['anUInt'])+"\n")
317 if 'anInt' in params: out.write(" anInt: "+str(params['anInt'])+"\n")
318 if 'aBool' in params: out.write(" aBool: "+str(params['aBool'])+"\n")
319 if 'aStr' in params: out.write(" aStr: "+str(params['aStr'])+"\n")
320 if 'anUDecimal' in params: out.write(" anUDecimal: "+str(params['anUDecimal'])+"\n")
321 if 'aDecimal' in params: out.write(" aDecimal: "+str(params['aDecimal'])+"\n")
322 if 'aFloat' in params: out.write(" aFloat: "+str(params['aFloat'])+"\n")
323 elif 'csv'==format:
324 if None == options.fieldList:
325 options.fieldList = fieldList
326 needComma = False;
327 for field in fieldList:
328 if needComma: out.write(',')
329 needComma = True
330 if field in params:
331 out.write(str(params[field]))
332
333 out.write("\n")
334 elif 'html'==format:
335 printHtml(params,out)
336 elif 'sql'==format:
337 sqlInsertStr(params,out,dbType=dbType)
338 else:
339 print "ERROR: unknown format:",format
340 assert False
341
342 return
343
344
345
346
347
348 dbTableName='alltypesmsg'
349 'Database table name'
350
351 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
352 ,addCoastGuardFields=True
353 ,dbType='postgres'
354 ):
355 '''
356 Return the SQL CREATE command for this message type
357 @param outfile: file like object to print to.
358 @param fields: which fields to put in the create. Defaults to all.
359 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
360 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
361 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
362 @type addCoastGuardFields: bool
363 @return: sql create string
364 @rtype: str
365
366 @see: sqlCreate
367 '''
368
369 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
370
371 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
372 '''
373 Return the sqlhelp object to create the table.
374
375 @param fields: which fields to put in the create. Defaults to all.
376 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
377 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
378 @type addCoastGuardFields: bool
379 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
380 @return: An object that can be used to generate a return
381 @rtype: sqlhelp.create
382 '''
383 if None == fields: fields = fieldList
384 import sqlhelp
385 c = sqlhelp.create('alltypesmsg',dbType=dbType)
386 c.addPrimaryKey()
387 if 'dac' in fields: c.addInt ('dac')
388 if 'reqDecimal' in fields: c.addDecimal('reqDecimal',3,0)
389 if 'unavail_uint' in fields: c.addInt ('unavail_uint')
390 if 'anUInt' in fields: c.addInt ('anUInt')
391 if 'anInt' in fields: c.addInt ('anInt')
392 if 'aBool' in fields: c.addBool('aBool')
393 if 'aStr' in fields: c.addVarChar('aStr',5)
394 if 'anUDecimal' in fields: c.addDecimal('anUDecimal',5,1)
395 if 'aDecimal' in fields: c.addDecimal('aDecimal',4,0)
396 if 'aFloat' in fields: c.addReal('aFloat')
397
398 if addCoastGuardFields:
399
400
401
402
403
404 c.addVarChar('cg_r',15)
405 c.addInt('cg_sec')
406
407 c.addTimestamp('cg_timestamp')
408
409 return c
410
411 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
412 '''
413 Return the SQL INSERT command for this message type
414 @param params: dictionary of values keyed by field name
415 @param outfile: file like object to print to.
416 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
417 @return: sql create string
418 @rtype: str
419
420 @see: sqlCreate
421 '''
422 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
423
424
425 -def sqlInsert(params,extraParams=None,dbType='postgres'):
426 '''
427 Give the SQL INSERT statement
428 @param params: dict keyed by field name of values
429 @param extraParams: any extra fields that you have created beyond the normal ais message fields
430 @rtype: sqlhelp.insert
431 @return: insert class instance
432 @todo: allow optional type checking of params?
433 @warning: this will take invalid keys happily and do what???
434 '''
435 import sqlhelp
436 i = sqlhelp.insert('alltypesmsg',dbType=dbType)
437
438 if dbType=='postgres':
439 finished = []
440 for key in params:
441 if key in finished:
442 continue
443
444 if key not in toPgFields and key not in fromPgFields:
445 if type(params[key])==Decimal: i.add(key,float(params[key]))
446 else: i.add(key,params[key])
447 else:
448 if key in fromPgFields:
449 val = params[key]
450
451 i.addPostGIS(key,val)
452 finished.append(key)
453 else:
454
455 pgName = toPgFields[key]
456
457 valStr=pgTypes[pgName]+'('
458 vals = []
459 for nonPgKey in fromPgFields[pgName]:
460 vals.append(str(params[nonPgKey]))
461 finished.append(nonPgKey)
462 valStr+=' '.join(vals)+')'
463 i.addPostGIS(pgName,valStr)
464 else:
465 for key in params:
466 if type(params[key])==Decimal: i.add(key,float(params[key]))
467 else: i.add(key,params[key])
468
469 if None != extraParams:
470 for key in extraParams:
471 i.add(key,extraParams[key])
472
473 return i
474
475
476
477
478
481 '''
482 Return the LaTeX definition table for this message type
483 @param outfile: file like object to print to.
484 @type outfile: file obj
485 @return: LaTeX table string via the outfile
486 @rtype: str
487
488 '''
489 o = outfile
490
491 o.write('''
492 \\begin{table}%[htb]
493 \\centering
494 \\begin{tabular}{|l|c|l|}
495 \\hline
496 Parameter & Number of bits & Description
497 \\\\ \\hline\\hline
498 dac & 16 & Designated Area Code \\\\ \hline
499 reqDecimal & 8 & required decimal value... FIX: scale or no? \\\\ \hline
500 unavail\_uint & 2 & Unavailable unsigned integer \\\\ \hline
501 anUInt & 2 & NO unavailable unsigned integer \\\\ \hline
502 anInt & 3 & NO unavailable signed integer \\\\ \hline
503 aBool & 1 & Simple bool \\\\ \hline
504 aStr & 30 & An ais string of 5 characters \\\\ \hline
505 anUDecimal & 16 & An unsigned decimal. Allow smaller numbers \\\\ \hline
506 aDecimal & 16 & A decimal \\\\ \hline
507 aFloat & 32 & An IEEE floating point number\\\\ \\hline \\hline
508 Total bits & 126 & Appears to take 1 slot with 42 pad bits to fill the last slot \\\\ \\hline
509 \\end{tabular}
510 \\caption{AIS message number 8: Message to demonstrate all the ais types. Good for testing}
511 \\label{tab:alltypesmsg}
512 \\end{table}
513 ''')
514
515
516
517
518
519 -def textDefinitionTable(outfile=sys.stdout
520 ,delim='\t'
521 ):
522 '''
523 Return the text definition table for this message type
524 @param outfile: file like object to print to.
525 @type outfile: file obj
526 @return: text table string via the outfile
527 @rtype: str
528
529 '''
530 o = outfile
531 o.write('''Parameter'''+delim+'Number of bits'''+delim+'''Description
532 dac'''+delim+'''16'''+delim+'''Designated Area Code
533 reqDecimal'''+delim+'''8'''+delim+'''required decimal value... FIX: scale or no?
534 unavail_uint'''+delim+'''2'''+delim+'''Unavailable unsigned integer
535 anUInt'''+delim+'''2'''+delim+'''NO unavailable unsigned integer
536 anInt'''+delim+'''3'''+delim+'''NO unavailable signed integer
537 aBool'''+delim+'''1'''+delim+'''Simple bool
538 aStr'''+delim+'''30'''+delim+'''An ais string of 5 characters
539 anUDecimal'''+delim+'''16'''+delim+'''An unsigned decimal. Allow smaller numbers
540 aDecimal'''+delim+'''16'''+delim+'''A decimal
541 aFloat'''+delim+'''32'''+delim+'''An IEEE floating point number
542 Total bits'''+delim+'''126'''+delim+'''Appears to take 1 slot with 42 pad bits to fill the last slot''')
543
544
545
546
547
548 import unittest
550 '''Return a params file base on the testvalue tags.
551 @rtype: dict
552 @return: params based on testvalue tags
553 '''
554 params = {}
555 params['dac'] = 366
556 params['reqDecimal'] = Decimal('122')
557 params['unavail_uint'] = 2
558 params['anUInt'] = 1
559 params['anInt'] = -1
560 params['aBool'] = True
561 params['aStr'] = 'ASDF1'
562 params['anUDecimal'] = Decimal('9.5')
563 params['aDecimal'] = Decimal('-9.6')
564 params['aFloat'] = -1234.5678
565
566 return params
567
569 '''Use testvalue tag text from each type to build test case the alltypesmsg message'''
571
572 params = testParams()
573 bits = encode(params)
574 r = decode(bits)
575
576
577 self.failUnlessEqual(r['dac'],params['dac'])
578 self.failUnlessAlmostEqual(r['reqDecimal'],params['reqDecimal'],0)
579 self.failUnlessEqual(r['unavail_uint'],params['unavail_uint'])
580 self.failUnlessEqual(r['anUInt'],params['anUInt'])
581 self.failUnlessEqual(r['anInt'],params['anInt'])
582 self.failUnlessEqual(r['aBool'],params['aBool'])
583 self.failUnlessEqual(r['aStr'],params['aStr'])
584 self.failUnlessAlmostEqual(r['anUDecimal'],params['anUDecimal'],1)
585 self.failUnlessAlmostEqual(r['aDecimal'],params['aDecimal'],0)
586 self.failUnlessAlmostEqual(r['aFloat'],params['aFloat'],3)
587
589 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
590 help='decode a "alltypesmsg" AIS message')
591 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
592 help='encode a "alltypesmsg" AIS message')
593 parser.add_option('--unavail_uint-field', dest='unavail_uintField',default=3,metavar='uint',type='int'
594 ,help='Field parameter value [default: %default]')
595 parser.add_option('--anUInt-field', dest='anUIntField',metavar='uint',type='int'
596 ,help='Field parameter value [default: %default]')
597 parser.add_option('--anInt-field', dest='anIntField',metavar='int',type='int'
598 ,help='Field parameter value [default: %default]')
599 parser.add_option('--aBool-field', dest='aBoolField',metavar='bool',type='int'
600 ,help='Field parameter value [default: %default]')
601 parser.add_option('--aStr-field', dest='aStrField',metavar='aisstr6',type='string'
602 ,help='Field parameter value [default: %default]')
603 parser.add_option('--anUDecimal-field', dest='anUDecimalField',metavar='udecimal',type='string'
604 ,help='Field parameter value [default: %default]')
605 parser.add_option('--aDecimal-field', dest='aDecimalField',metavar='decimal',type='string'
606 ,help='Field parameter value [default: %default]')
607 parser.add_option('--aFloat-field', dest='aFloatField',metavar='float',type='float'
608 ,help='Field parameter value [default: %default]')
609
610
611 if __name__=='__main__':
612
613 from optparse import OptionParser
614 parser = OptionParser(usage="%prog [options]",
615 version="%prog "+__version__)
616
617 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
618 help='run the documentation tests')
619 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
620 help='run the unit tests')
621 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
622 help='Make the test output verbose')
623
624
625
626 typeChoices = ('binary','nmeapayload','nmea')
627 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
628 ,default='nmeapayload'
629 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
630
631
632 outputChoices = ('std','html','csv','sql' )
633 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
634 ,default='std'
635 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
636
637 parser.add_option('-o','--output',dest='outputFileName',default=None,
638 help='Name of the python file to write [default: stdout]')
639
640 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
641 choices=fieldList,
642 help='Which fields to include in the output. Currently only for csv output [default: all]')
643
644 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
645 help='Print the field name for csv')
646
647 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
648 help='Print out an sql create command for the table.')
649
650 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
651 help='Print a LaTeX table of the type')
652
653 parser.add_option('--text-table',dest='textDefinitionTable',default=False,action='store_true',
654 help='Print delimited table of the type (for Word table importing)')
655 parser.add_option('--delimt-text-table',dest='delimTextDefinitionTable',default='\t'
656 ,help='Delimiter for text table [default: \'%default\'](for Word table importing)')
657
658
659 dbChoices = ('sqlite','postgres')
660 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
661 ,choices=dbChoices,type='choice'
662 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
663
664 addMsgOptions(parser)
665
666 (options,args) = parser.parse_args()
667 success=True
668
669 if options.doctest:
670 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
671 sys.argv= [sys.argv[0]]
672 if options.verbose: sys.argv.append('-v')
673 import doctest
674 numfail,numtests=doctest.testmod()
675 if numfail==0: print 'ok'
676 else:
677 print 'FAILED'
678 success=False
679
680 if not success: sys.exit('Something Failed')
681 del success
682
683 if options.unittest:
684 sys.argv = [sys.argv[0]]
685 if options.verbose: sys.argv.append('-v')
686 unittest.main()
687
688 outfile = sys.stdout
689 if None!=options.outputFileName:
690 outfile = file(options.outputFileName,'w')
691
692
693 if options.doEncode:
694
695 if None==options.unavail_uintField: parser.error("missing value for unavail_uintField")
696 if None==options.anUIntField: parser.error("missing value for anUIntField")
697 if None==options.anIntField: parser.error("missing value for anIntField")
698 if None==options.aBoolField: parser.error("missing value for aBoolField")
699 if None==options.aStrField: parser.error("missing value for aStrField")
700 if None==options.anUDecimalField: parser.error("missing value for anUDecimalField")
701 if None==options.aDecimalField: parser.error("missing value for aDecimalField")
702 if None==options.aFloatField: parser.error("missing value for aFloatField")
703 msgDict={
704 'dac': '366',
705 'reqDecimal': '122',
706 'unavail_uint': options.unavail_uintField,
707 'anUInt': options.anUIntField,
708 'anInt': options.anIntField,
709 'aBool': options.aBoolField,
710 'aStr': options.aStrField,
711 'anUDecimal': options.anUDecimalField,
712 'aDecimal': options.aDecimalField,
713 'aFloat': options.aFloatField,
714 }
715
716 bits = encode(msgDict)
717 if 'binary'==options.ioType: print str(bits)
718 elif 'nmeapayload'==options.ioType:
719
720 print "bitLen",len(bits)
721 bitLen=len(bits)
722 if bitLen%6!=0:
723 bits = bits + BitVector(size=(6 - (bitLen%6)))
724 print "result:",binary.bitvectoais6(bits)[0]
725
726
727
728 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
729 else: sys.exit('ERROR: unknown ioType. Help!')
730
731
732 if options.sqlCreate:
733 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
734
735 if options.latexDefinitionTable:
736 latexDefinitionTable(outfile)
737
738
739 if options.textDefinitionTable:
740 textDefinitionTable(outfile,options.delimTextDefinitionTable)
741
742 if options.printCsvfieldList:
743
744 if None == options.fieldList: options.fieldList = fieldList
745 import StringIO
746 buf = StringIO.StringIO()
747 for field in options.fieldList:
748 buf.write(field+',')
749 result = buf.getvalue()
750 if result[-1] == ',': print result[:-1]
751 else: print result
752
753 if options.doDecode:
754 if len(args)==0: args = sys.stdin
755 for msg in args:
756 bv = None
757
758 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
759
760
761 bv = binary.ais6tobitvec(msg.split(',')[5])
762 else:
763
764 binaryMsg=True
765 for c in msg:
766 if c not in ('0','1'):
767 binaryMsg=False
768 break
769 if binaryMsg:
770 bv = BitVector(bitstring=msg)
771 else:
772 bv = binary.ais6tobitvec(msg)
773
774 printFields(decode(bv)
775 ,out=outfile
776 ,format=options.outputType
777 ,fieldList=options.fieldList
778 ,dbType=options.dbType
779 )
780