1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-02-16 $'.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 'time_month',
51 'time_day',
52 'time_hour',
53 'time_min',
54 'stationid',
55 'pos_longitude',
56 'pos_latitude',
57 'type',
58 'waterlevel',
59 'datum',
60 'reserved',
61 )
62
63 fieldListPostgres = (
64 'time_month',
65 'time_day',
66 'time_hour',
67 'time_min',
68 'stationid',
69 'pos_longitude',
70 'pos_latitude',
71 'type',
72 'waterlevel',
73 'datum',
74 'reserved',
75 )
76
77 toPgFields = {
78 }
79 '''
80 Go to the Postgis field names from the straight field name
81 '''
82
83 fromPgFields = {
84 }
85 '''
86 Go from the Postgis field names to the straight field name
87 '''
88
89 pgTypes = {
90 }
91 '''
92 Lookup table for each postgis field name to get its type.
93 '''
94
95 -def encode(params, validate=False):
96 '''Create a sls_waterlevel binary message payload to pack into an AIS Msg sls_waterlevel.
97
98 Fields in params:
99 - time_month(uint): Time tag of measurement month 1..12
100 - time_day(uint): Time tag of measurement day of the month 1..31
101 - time_hour(uint): Time tag of measurement UTC hours 0..23
102 - time_min(uint): Time tag of measurement minutes
103 - stationid(aisstr6): Character identifier of the station. Usually a number.
104 - pos_longitude(decimal): Location of measurement East West location
105 - pos_latitude(decimal): Location of measurement North South location
106 - type(uint): How to interpret the water level
107 - waterlevel(int): Water level in centimeters
108 - datum(uint): What reference datum applies to the value
109 - reserved(uint): Reserved bits for future use (field automatically set to "0")
110 @param params: Dictionary of field names/values. Throws a ValueError exception if required is missing
111 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
112 @rtype: BitVector
113 @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
114 @note: The returned bits may not be 6 bit aligned. It is up to you to pad out the bits.
115 '''
116
117 bvList = []
118 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4))
119 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5))
120 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5))
121 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6))
122 if 'stationid' in params:
123 bvList.append(aisstring.encode(params['stationid'],42))
124 else:
125 bvList.append(aisstring.encode('@@@@@@@',42))
126 if 'pos_longitude' in params:
127 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25))
128 else:
129 bvList.append(binary.bvFromSignedInt(10860000,25))
130 if 'pos_latitude' in params:
131 bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24))
132 else:
133 bvList.append(binary.bvFromSignedInt(5460000,24))
134 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),1))
135 if 'waterlevel' in params:
136 bvList.append(binary.bvFromSignedInt(params['waterlevel'],16))
137 else:
138 bvList.append(binary.bvFromSignedInt(-32768,16))
139 if 'datum' in params:
140 bvList.append(binary.setBitVectorSize(BitVector(intVal=params['datum']),2))
141 else:
142 bvList.append(binary.setBitVectorSize(BitVector(intVal=31),2))
143 bvList.append(binary.setBitVectorSize(BitVector(intVal=0),14))
144
145 return binary.joinBV(bvList)
146
147 -def decode(bv, validate=False):
148 '''Unpack a sls_waterlevel message
149
150 Fields in params:
151 - time_month(uint): Time tag of measurement month 1..12
152 - time_day(uint): Time tag of measurement day of the month 1..31
153 - time_hour(uint): Time tag of measurement UTC hours 0..23
154 - time_min(uint): Time tag of measurement minutes
155 - stationid(aisstr6): Character identifier of the station. Usually a number.
156 - pos_longitude(decimal): Location of measurement East West location
157 - pos_latitude(decimal): Location of measurement North South location
158 - type(uint): How to interpret the water level
159 - waterlevel(int): Water level in centimeters
160 - datum(uint): What reference datum applies to the value
161 - reserved(uint): Reserved bits for future use (field automatically set to "0")
162 @type bv: BitVector
163 @param bv: Bits defining a message
164 @param validate: Set to true to cause checking to occur. Runs slower. FIX: not implemented.
165 @rtype: dict
166 @return: params
167 '''
168
169
170
171
172 r = {}
173 r['time_month']=int(bv[0:4])
174 r['time_day']=int(bv[4:9])
175 r['time_hour']=int(bv[9:14])
176 r['time_min']=int(bv[14:20])
177 r['stationid']=aisstring.decode(bv[20:62])
178 r['pos_longitude']=Decimal(binary.signedIntFromBV(bv[62:87]))/Decimal('60000')
179 r['pos_latitude']=Decimal(binary.signedIntFromBV(bv[87:111]))/Decimal('60000')
180 r['type']=int(bv[111:112])
181 r['waterlevel']=binary.signedIntFromBV(bv[112:128])
182 r['datum']=int(bv[128:130])
183 r['reserved']=0
184 return r
185
188
191
194
196 return int(bv[14:20])
197
200
203
206
208 return int(bv[111:112])
209
212
214 return int(bv[128:130])
215
217 return 0
218
219
221 out.write("<h3>sls_waterlevel<h3>\n")
222 out.write("<table border=\"1\">\n")
223 out.write("<tr bgcolor=\"orange\">\n")
224 out.write("<th align=\"left\">Field Name</th>\n")
225 out.write("<th align=\"left\">Type</th>\n")
226 out.write("<th align=\"left\">Value</th>\n")
227 out.write("<th align=\"left\">Value in Lookup Table</th>\n")
228 out.write("<th align=\"left\">Units</th>\n")
229 out.write("\n")
230 out.write("<tr>\n")
231 out.write("<td>time_month</td>\n")
232 out.write("<td>uint</td>\n")
233 if 'time_month' in params:
234 out.write(" <td>"+str(params['time_month'])+"</td>\n")
235 out.write(" <td>"+str(params['time_month'])+"</td>\n")
236 out.write("</tr>\n")
237 out.write("\n")
238 out.write("<tr>\n")
239 out.write("<td>time_day</td>\n")
240 out.write("<td>uint</td>\n")
241 if 'time_day' in params:
242 out.write(" <td>"+str(params['time_day'])+"</td>\n")
243 out.write(" <td>"+str(params['time_day'])+"</td>\n")
244 out.write("</tr>\n")
245 out.write("\n")
246 out.write("<tr>\n")
247 out.write("<td>time_hour</td>\n")
248 out.write("<td>uint</td>\n")
249 if 'time_hour' in params:
250 out.write(" <td>"+str(params['time_hour'])+"</td>\n")
251 out.write(" <td>"+str(params['time_hour'])+"</td>\n")
252 out.write("</tr>\n")
253 out.write("\n")
254 out.write("<tr>\n")
255 out.write("<td>time_min</td>\n")
256 out.write("<td>uint</td>\n")
257 if 'time_min' in params:
258 out.write(" <td>"+str(params['time_min'])+"</td>\n")
259 out.write(" <td>"+str(params['time_min'])+"</td>\n")
260 out.write("</tr>\n")
261 out.write("\n")
262 out.write("<tr>\n")
263 out.write("<td>stationid</td>\n")
264 out.write("<td>aisstr6</td>\n")
265 if 'stationid' in params:
266 out.write(" <td>"+str(params['stationid'])+"</td>\n")
267 out.write(" <td>"+str(params['stationid'])+"</td>\n")
268 out.write("</tr>\n")
269 out.write("\n")
270 out.write("<tr>\n")
271 out.write("<td>pos_longitude</td>\n")
272 out.write("<td>decimal</td>\n")
273 if 'pos_longitude' in params:
274 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n")
275 out.write(" <td>"+str(params['pos_longitude'])+"</td>\n")
276 out.write("<td>degrees</td>\n")
277 out.write("</tr>\n")
278 out.write("\n")
279 out.write("<tr>\n")
280 out.write("<td>pos_latitude</td>\n")
281 out.write("<td>decimal</td>\n")
282 if 'pos_latitude' in params:
283 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n")
284 out.write(" <td>"+str(params['pos_latitude'])+"</td>\n")
285 out.write("<td>degrees</td>\n")
286 out.write("</tr>\n")
287 out.write("\n")
288 out.write("<tr>\n")
289 out.write("<td>type</td>\n")
290 out.write("<td>uint</td>\n")
291 if 'type' in params:
292 out.write(" <td>"+str(params['type'])+"</td>\n")
293 if str(params['type']) in typeDecodeLut:
294 out.write("<td>"+typeDecodeLut[str(params['type'])]+"</td>")
295 else:
296 out.write("<td><i>Missing LUT entry</i></td>")
297 out.write("</tr>\n")
298 out.write("\n")
299 out.write("<tr>\n")
300 out.write("<td>waterlevel</td>\n")
301 out.write("<td>int</td>\n")
302 if 'waterlevel' in params:
303 out.write(" <td>"+str(params['waterlevel'])+"</td>\n")
304 out.write(" <td>"+str(params['waterlevel'])+"</td>\n")
305 out.write("<td>cm</td>\n")
306 out.write("</tr>\n")
307 out.write("\n")
308 out.write("<tr>\n")
309 out.write("<td>datum</td>\n")
310 out.write("<td>uint</td>\n")
311 if 'datum' in params:
312 out.write(" <td>"+str(params['datum'])+"</td>\n")
313 if str(params['datum']) in datumDecodeLut:
314 out.write("<td>"+datumDecodeLut[str(params['datum'])]+"</td>")
315 else:
316 out.write("<td><i>Missing LUT entry</i></td>")
317 out.write("</tr>\n")
318 out.write("\n")
319 out.write("<tr>\n")
320 out.write("<td>reserved</td>\n")
321 out.write("<td>uint</td>\n")
322 if 'reserved' in params:
323 out.write(" <td>"+str(params['reserved'])+"</td>\n")
324 out.write(" <td>"+str(params['reserved'])+"</td>\n")
325 out.write("</tr>\n")
326 out.write("</table>\n")
327
328
330 '''KML (Keyhole Markup Language) for Google Earth, but without the header/footer'''
331 out.write("\ <Placemark>\n")
332 out.write("\t <name>"+str(params['stationid'])+"</name>\n")
333 out.write("\t\t<description>\n")
334 import StringIO
335 buf = StringIO.StringIO()
336 printHtml(params,buf)
337 import cgi
338 out.write(cgi.escape(buf.getvalue()))
339 out.write("\t\t</description>\n")
340 out.write("\t\t<styleUrl>#m_ylw-pushpin_copy0</styleUrl>\n")
341 out.write("\t\t<Point>\n")
342 out.write("\t\t\t<coordinates>")
343 out.write(str(params['pos_longitude']))
344 out.write(',')
345 out.write(str(params['pos_latitude']))
346 out.write(",0</coordinates>\n")
347 out.write("\t\t</Point>\n")
348 out.write("\t</Placemark>\n")
349
350 -def printFields(params, out=sys.stdout, format='std', fieldList=None, dbType='postgres'):
351 '''Print a reserved message to stdout.
352
353 Fields in params:
354 - time_month(uint): Time tag of measurement month 1..12
355 - time_day(uint): Time tag of measurement day of the month 1..31
356 - time_hour(uint): Time tag of measurement UTC hours 0..23
357 - time_min(uint): Time tag of measurement minutes
358 - stationid(aisstr6): Character identifier of the station. Usually a number.
359 - pos_longitude(decimal): Location of measurement East West location
360 - pos_latitude(decimal): Location of measurement North South location
361 - type(uint): How to interpret the water level
362 - waterlevel(int): Water level in centimeters
363 - datum(uint): What reference datum applies to the value
364 - reserved(uint): Reserved bits for future use (field automatically set to "0")
365 @param params: Dictionary of field names/values.
366 @param out: File like object to write to
367 @rtype: stdout
368 @return: text to out
369 '''
370
371 if 'std'==format:
372 out.write("reserved:\n")
373 if 'time_month' in params: out.write(" time_month: "+str(params['time_month'])+"\n")
374 if 'time_day' in params: out.write(" time_day: "+str(params['time_day'])+"\n")
375 if 'time_hour' in params: out.write(" time_hour: "+str(params['time_hour'])+"\n")
376 if 'time_min' in params: out.write(" time_min: "+str(params['time_min'])+"\n")
377 if 'stationid' in params: out.write(" stationid: "+str(params['stationid'])+"\n")
378 if 'pos_longitude' in params: out.write(" pos_longitude: "+str(params['pos_longitude'])+"\n")
379 if 'pos_latitude' in params: out.write(" pos_latitude: "+str(params['pos_latitude'])+"\n")
380 if 'type' in params: out.write(" type: "+str(params['type'])+"\n")
381 if 'waterlevel' in params: out.write(" waterlevel: "+str(params['waterlevel'])+"\n")
382 if 'datum' in params: out.write(" datum: "+str(params['datum'])+"\n")
383 if 'reserved' in params: out.write(" reserved: "+str(params['reserved'])+"\n")
384 elif 'csv'==format:
385 if None == options.fieldList:
386 options.fieldList = fieldList
387 needComma = False;
388 for field in fieldList:
389 if needComma: out.write(',')
390 needComma = True
391 if field in params:
392 out.write(str(params[field]))
393
394 out.write("\n")
395 elif 'html'==format:
396 printHtml(params,out)
397 elif 'sql'==format:
398 sqlInsertStr(params,out,dbType=dbType)
399 elif 'kml'==format:
400 printKml(params,out)
401 elif 'kml-full'==format:
402 out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
403 out.write("<kml xmlns=\"http://earth.google.com/kml/2.1\">\n")
404 out.write("<Document>\n")
405 out.write(" <name>sls_waterlevel</name>\n")
406 printKml(params,out)
407 out.write("</Document>\n")
408 out.write("</kml>\n")
409 else:
410 print "ERROR: unknown format:",format
411 assert False
412
413 return
414
415 typeEncodeLut = {
416 'Relative to datum':'0',
417 'Water depth':'1',
418 }
419
420 typeDecodeLut = {
421 '0':'Relative to datum',
422 '1':'Water depth',
423 }
424
425 datumEncodeLut = {
426 'MLLW':'0',
427 'IGLD-85':'1',
428 'Reserved':'2',
429 'Reserved':'3',
430 }
431
432 datumDecodeLut = {
433 '0':'MLLW',
434 '1':'IGLD-85',
435 '2':'Reserved',
436 '3':'Reserved',
437 }
438
439
440
441
442
443 -def sqlCreateStr(outfile=sys.stdout, fields=None, extraFields=None
444 ,addCoastGuardFields=True
445 ,dbType='postgres'
446 ):
447 '''
448 Return the SQL CREATE command for this message type
449 @param outfile: file like object to print to.
450 @param fields: which fields to put in the create. Defaults to all.
451 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
452 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
453 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
454 @type addCoastGuardFields: bool
455 @return: sql create string
456 @rtype: str
457
458 @see: sqlCreate
459 '''
460 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
461
462 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
463 '''
464 Return the sqlhelp object to create the table.
465
466 @param fields: which fields to put in the create. Defaults to all.
467 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
468 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
469 @type addCoastGuardFields: bool
470 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
471 @return: An object that can be used to generate a return
472 @rtype: sqlhelp.create
473 '''
474 if None == fields: fields = fieldList
475 import sqlhelp
476 c = sqlhelp.create('sls_waterlevel',dbType=dbType)
477 c.addPrimaryKey()
478 if 'time_month' in fields: c.addInt ('time_month')
479 if 'time_day' in fields: c.addInt ('time_day')
480 if 'time_hour' in fields: c.addInt ('time_hour')
481 if 'time_min' in fields: c.addInt ('time_min')
482 if 'stationid' in fields: c.addVarChar('stationid',7)
483 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4)
484 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4)
485 if 'type' in fields: c.addInt ('type')
486 if 'waterlevel' in fields: c.addInt ('waterlevel')
487 if 'datum' in fields: c.addInt ('datum')
488 if 'reserved' in fields: c.addInt ('reserved')
489
490 if addCoastGuardFields:
491
492
493
494
495
496 c.addVarChar('cg_r',15)
497 c.addInt('cg_sec')
498
499 c.addTimestamp('cg_timestamp')
500
501 return c
502
503 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
504 '''
505 Return the SQL INSERT command for this message type
506 @param params: dictionary of values keyed by field name
507 @param outfile: file like object to print to.
508 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
509 @return: sql create string
510 @rtype: str
511
512 @see: sqlCreate
513 '''
514 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
515
516
517 -def sqlInsert(params,extraParams=None,dbType='postgres'):
518 '''
519 Give the SQL INSERT statement
520 @param params: dict keyed by field name of values
521 @param extraParams: any extra fields that you have created beyond the normal ais message fields
522 @rtype: sqlhelp.insert
523 @return: insert class instance
524 @todo: allow optional type checking of params?
525 @warning: this will take invalid keys happily and do what???
526 '''
527 import sqlhelp
528 i = sqlhelp.insert('sls_waterlevel',dbType=dbType)
529
530 if dbType=='postgres':
531 finished = []
532 for key in params:
533 if key in finished:
534
535 continue
536
537 if key not in toPgFields and key not in fromPgFields:
538 if type(params[key])==Decimal: i.add(key,float(params[key]))
539 else: i.add(key,params[key])
540 else:
541 if key in fromPgFields:
542 val = params[key]
543
544 i.addPostGIS(key,val)
545 finished.append(key)
546 else:
547
548 pgName = toPgFields[key]
549
550 valStr=pgTypes[pgName]+'('
551 vals = []
552 for nonPgKey in fromPgFields[pgName]:
553 vals.append(str(params[nonPgKey]))
554 finished.append(nonPgKey)
555 valStr+=' '.join(vals)+')'
556 i.addPostGIS(pgName,valStr)
557 else:
558 for key in params:
559 if type(params[key])==Decimal: i.add(key,float(params[key]))
560 else: i.add(key,params[key])
561
562 if None != extraParams:
563 for key in extraParams:
564 i.add(key,extraParams[key])
565
566 return i
567
568
569
570
571
572 import unittest
574 '''Return a params file base on the testvalue tags.
575 @rtype: dict
576 @return: params based on testvalue tags
577 '''
578 params = {}
579 params['time_month'] = 2
580 params['time_day'] = 28
581 params['time_hour'] = 23
582 params['time_min'] = 45
583 params['stationid'] = 'A234567'
584 params['pos_longitude'] = Decimal('-122.16328')
585 params['pos_latitude'] = Decimal('37.42446')
586 params['type'] = 0
587 params['waterlevel'] = -97
588 params['datum'] = 0
589 params['reserved'] = 0
590
591 return params
592
594 '''Use testvalue tag text from each type to build test case the sls_waterlevel message'''
596
597 params = testParams()
598 bits = encode(params)
599 r = decode(bits)
600
601
602 self.failUnlessEqual(r['time_month'],params['time_month'])
603 self.failUnlessEqual(r['time_day'],params['time_day'])
604 self.failUnlessEqual(r['time_hour'],params['time_hour'])
605 self.failUnlessEqual(r['time_min'],params['time_min'])
606 self.failUnlessEqual(r['stationid'],params['stationid'])
607 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4)
608 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4)
609 self.failUnlessEqual(r['type'],params['type'])
610 self.failUnlessEqual(r['waterlevel'],params['waterlevel'])
611 self.failUnlessEqual(r['datum'],params['datum'])
612 self.failUnlessEqual(r['reserved'],params['reserved'])
613
615 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
616 help='decode a "sls_waterlevel" AIS message')
617 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
618 help='encode a "sls_waterlevel" AIS message')
619 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int'
620 ,help='Field parameter value [default: %default]')
621 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int'
622 ,help='Field parameter value [default: %default]')
623 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int'
624 ,help='Field parameter value [default: %default]')
625 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int'
626 ,help='Field parameter value [default: %default]')
627 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string'
628 ,help='Field parameter value [default: %default]')
629 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string'
630 ,help='Field parameter value [default: %default]')
631 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string'
632 ,help='Field parameter value [default: %default]')
633 parser.add_option('--type-field', dest='typeField',metavar='uint',type='int'
634 ,help='Field parameter value [default: %default]')
635 parser.add_option('--waterlevel-field', dest='waterlevelField',default=-32768,metavar='int',type='int'
636 ,help='Field parameter value [default: %default]')
637 parser.add_option('--datum-field', dest='datumField',default=31,metavar='uint',type='int'
638 ,help='Field parameter value [default: %default]')
639
640
641 if __name__=='__main__':
642
643 from optparse import OptionParser
644 parser = OptionParser(usage="%prog [options]",
645 version="%prog "+__version__)
646
647 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
648 help='run the documentation tests')
649 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
650 help='run the unit tests')
651 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
652 help='Make the test output verbose')
653
654
655
656 typeChoices = ('binary','nmeapayload','nmea')
657 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
658 ,default='nmeapayload'
659 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
660
661
662 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
663 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
664 ,default='std'
665 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
666
667 parser.add_option('-o','--output',dest='outputFileName',default=None,
668 help='Name of the python file to write [default: stdout]')
669
670 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
671 choices=fieldList,
672 help='Which fields to include in the output. Currently only for csv output [default: all]')
673
674 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
675 help='Print the field name for csv')
676
677 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
678 help='Print out an sql create command for the table.')
679
680 dbChoices = ('sqlite','postgres')
681 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
682 ,choices=dbChoices,type='choice'
683 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
684
685 addMsgOptions(parser)
686
687 (options,args) = parser.parse_args()
688 success=True
689
690 if options.doctest:
691 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
692 sys.argv= [sys.argv[0]]
693 if options.verbose: sys.argv.append('-v')
694 import doctest
695 numfail,numtests=doctest.testmod()
696 if numfail==0: print 'ok'
697 else:
698 print 'FAILED'
699 success=False
700
701 if not success: sys.exit('Something Failed')
702 del success
703
704 if options.unittest:
705 sys.argv = [sys.argv[0]]
706 if options.verbose: sys.argv.append('-v')
707 unittest.main()
708
709 outfile = sys.stdout
710 if None!=options.outputFileName:
711 outfile = file(options.outputFileName,'w')
712
713
714 if options.doEncode:
715
716 if None==options.time_monthField: parser.error("missing value for time_monthField")
717 if None==options.time_dayField: parser.error("missing value for time_dayField")
718 if None==options.time_hourField: parser.error("missing value for time_hourField")
719 if None==options.time_minField: parser.error("missing value for time_minField")
720 if None==options.stationidField: parser.error("missing value for stationidField")
721 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField")
722 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField")
723 if None==options.typeField: parser.error("missing value for typeField")
724 if None==options.waterlevelField: parser.error("missing value for waterlevelField")
725 if None==options.datumField: parser.error("missing value for datumField")
726 msgDict={
727 'time_month': options.time_monthField,
728 'time_day': options.time_dayField,
729 'time_hour': options.time_hourField,
730 'time_min': options.time_minField,
731 'stationid': options.stationidField,
732 'pos_longitude': options.pos_longitudeField,
733 'pos_latitude': options.pos_latitudeField,
734 'type': options.typeField,
735 'waterlevel': options.waterlevelField,
736 'datum': options.datumField,
737 'reserved': '0',
738 }
739
740 bits = encode(msgDict)
741 if 'binary'==options.ioType: print str(bits)
742 elif 'nmeapayload'==options.ioType:
743
744 print "bitLen",len(bits)
745 bitLen=len(bits)
746 if bitLen%6!=0:
747 bits = bits + BitVector(size=(6 - (bitLen%6)))
748 print "result:",binary.bitvectoais6(bits)[0]
749
750
751
752 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
753 else: sys.exit('ERROR: unknown ioType. Help!')
754
755
756 if options.sqlCreate:
757 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
758
759 if options.printCsvfieldList:
760
761 if None == options.fieldList: options.fieldList = fieldList
762 import StringIO
763 buf = StringIO.StringIO()
764 for field in options.fieldList:
765 buf.write(field+',')
766 result = buf.getvalue()
767 if result[-1] == ',': print result[:-1]
768 else: print result
769
770 if options.doDecode:
771 for msg in args:
772 bv = None
773
774 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
775
776
777 bv = binary.ais6tobitvec(msg.split(',')[5])
778 else:
779
780 binaryMsg=True
781 for c in msg:
782 if c not in ('0','1'):
783 binaryMsg=False
784 break
785 if binaryMsg:
786 bv = BitVector(bitstring=msg)
787 else:
788 bv = binary.ais6tobitvec(msg)
789
790 printFields(decode(bv)
791 ,out=outfile
792 ,format=options.outputType
793 ,fieldList=options.fieldList
794 ,dbType=options.dbType
795 )
796