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