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