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