1
2
3 __version__ = '$Revision: 4791 $'.split()[1]
4 __date__ = '$Date: 2007-03-30 $'.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
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
623 outfile.write(str(sqlCreate(fields,extraFields,addCoastGuardFields,dbType=dbType)))
624
625 -def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
626 '''
627 Return the sqlhelp object to create the table.
628
629 @param fields: which fields to put in the create. Defaults to all.
630 @param extraFields: A sequence of tuples containing (name,sql type) for additional fields
631 @param addCoastGuardFields: Add the extra fields that come after the NMEA check some from the USCG N-AIS format
632 @type addCoastGuardFields: bool
633 @param dbType: Which flavor of database we are using so that the create is tailored ('sqlite' or 'postgres')
634 @return: An object that can be used to generate a return
635 @rtype: sqlhelp.create
636 '''
637 if None == fields: fields = fieldList
638 import sqlhelp
639 c = sqlhelp.create('sls_weatherreport',dbType=dbType)
640 c.addPrimaryKey()
641 if 'time_month' in fields: c.addInt ('time_month')
642 if 'time_day' in fields: c.addInt ('time_day')
643 if 'time_hour' in fields: c.addInt ('time_hour')
644 if 'time_min' in fields: c.addInt ('time_min')
645 if 'stationid' in fields: c.addVarChar('stationid',7)
646 if 'pos_longitude' in fields: c.addDecimal('pos_longitude',7,4)
647 if 'pos_latitude' in fields: c.addDecimal('pos_latitude',7,4)
648 if 'speed' in fields: c.addDecimal('speed',4,1)
649 if 'gust' in fields: c.addDecimal('gust',4,1)
650 if 'direction' in fields: c.addInt ('direction')
651 if 'atmpressure' in fields: c.addDecimal('atmpressure',5,1)
652 if 'airtemp' in fields: c.addDecimal('airtemp',4,1)
653 if 'dewpoint' in fields: c.addDecimal('dewpoint',4,1)
654 if 'visibility' in fields: c.addDecimal('visibility',3,1)
655 if 'watertemp' in fields: c.addDecimal('watertemp',4,1)
656 if 'reserved' in fields: c.addInt ('reserved')
657
658 if addCoastGuardFields:
659
660
661
662
663
664 c.addVarChar('cg_r',15)
665 c.addInt('cg_sec')
666
667 c.addTimestamp('cg_timestamp')
668
669 return c
670
671 -def sqlInsertStr(params, outfile=sys.stdout, extraParams=None, dbType='postgres'):
672 '''
673 Return the SQL INSERT command for this message type
674 @param params: dictionary of values keyed by field name
675 @param outfile: file like object to print to.
676 @param extraParams: A sequence of tuples containing (name,sql type) for additional fields
677 @return: sql create string
678 @rtype: str
679
680 @see: sqlCreate
681 '''
682 outfile.write(str(sqlInsert(params,extraParams,dbType=dbType)))
683
684
685 -def sqlInsert(params,extraParams=None,dbType='postgres'):
686 '''
687 Give the SQL INSERT statement
688 @param params: dict keyed by field name of values
689 @param extraParams: any extra fields that you have created beyond the normal ais message fields
690 @rtype: sqlhelp.insert
691 @return: insert class instance
692 @todo: allow optional type checking of params?
693 @warning: this will take invalid keys happily and do what???
694 '''
695 import sqlhelp
696 i = sqlhelp.insert('sls_weatherreport',dbType=dbType)
697
698 if dbType=='postgres':
699 finished = []
700 for key in params:
701 if key in finished:
702 continue
703
704 if key not in toPgFields and key not in fromPgFields:
705 if type(params[key])==Decimal: i.add(key,float(params[key]))
706 else: i.add(key,params[key])
707 else:
708 if key in fromPgFields:
709 val = params[key]
710
711 i.addPostGIS(key,val)
712 finished.append(key)
713 else:
714
715 pgName = toPgFields[key]
716
717 valStr=pgTypes[pgName]+'('
718 vals = []
719 for nonPgKey in fromPgFields[pgName]:
720 vals.append(str(params[nonPgKey]))
721 finished.append(nonPgKey)
722 valStr+=' '.join(vals)+')'
723 i.addPostGIS(pgName,valStr)
724 else:
725 for key in params:
726 if type(params[key])==Decimal: i.add(key,float(params[key]))
727 else: i.add(key,params[key])
728
729 if None != extraParams:
730 for key in extraParams:
731 i.add(key,extraParams[key])
732
733 return i
734
735
736
737
740 '''
741 Return the LaTeX definition table for this message type
742 @param outfile: file like object to print to.
743 @param fields: which fields to put in the create. Defaults to all.
744 @return: LaTeX table string
745 @rtype: str
746
747 '''
748 o = outfile
749
750 o.write('''
751 \\begin{table}%[htb]
752 \\centering
753 \\begin{tabular}{|l|c|l|}
754 \\hline
755 Parameter & Number of bits & Description
756 \\\\ \\hline\\hline
757 time\_month & 4 & Time tag of measurement month 1..12 \\\\ \hline
758 time\_day & 5 & Time tag of measurement day of the month 1..31 \\\\ \hline
759 time\_hour & 5 & Time tag of measurement UTC hours 0..23 \\\\ \hline
760 time\_min & 6 & Time tag of measurement minutes \\\\ \hline
761 stationid & 42 & Character identifier of the station \\\\ \hline
762 pos\_longitude & 25 & Location of measurement East West location \\\\ \hline
763 pos\_latitude & 24 & Location of measurement North South location \\\\ \hline
764 speed & 10 & Average wind speed \\\\ \hline
765 gust & 10 & Wind gust \\\\ \hline
766 direction & 9 & Wind direction \\\\ \hline
767 atmpressure & 14 & Atmospheric pressure \\\\ \hline
768 airtemp & 10 & Air temperature \\\\ \hline
769 dewpoint & 10 & Dew Point \\\\ \hline
770 visibility & 8 & Visibility \\\\ \hline
771 watertemp & 10 & Water Temperature \\\\ \hline
772 reserved & 4 & Reserved bits for future use\\\\ \\hline \\hline
773 Total bits & 196 & Appears to take 2 slots with 228 pad bits to fill the last slot \\\\ \\hline
774 \\end{tabular}
775 \\caption{AIS message number 8: St Lawrance Seaway wind information}
776 \\label{tab:sls_weatherreport}
777 \\end{table}
778 ''')
779
780
781
782
783
784 import unittest
786 '''Return a params file base on the testvalue tags.
787 @rtype: dict
788 @return: params based on testvalue tags
789 '''
790 params = {}
791 params['time_month'] = 2
792 params['time_day'] = 28
793 params['time_hour'] = 23
794 params['time_min'] = 45
795 params['stationid'] = 'A345678'
796 params['pos_longitude'] = Decimal('-122.16328')
797 params['pos_latitude'] = Decimal('37.42446')
798 params['speed'] = Decimal('0.7')
799 params['gust'] = Decimal('0.7')
800 params['direction'] = 41
801 params['atmpressure'] = Decimal('0.7')
802 params['airtemp'] = Decimal('-8')
803 params['dewpoint'] = Decimal('-7')
804 params['visibility'] = Decimal('12.3')
805 params['watertemp'] = Decimal('-0.2')
806 params['reserved'] = 0
807
808 return params
809
811 '''Use testvalue tag text from each type to build test case the sls_weatherreport message'''
813
814 params = testParams()
815 bits = encode(params)
816 r = decode(bits)
817
818
819 self.failUnlessEqual(r['time_month'],params['time_month'])
820 self.failUnlessEqual(r['time_day'],params['time_day'])
821 self.failUnlessEqual(r['time_hour'],params['time_hour'])
822 self.failUnlessEqual(r['time_min'],params['time_min'])
823 self.failUnlessEqual(r['stationid'],params['stationid'])
824 self.failUnlessAlmostEqual(r['pos_longitude'],params['pos_longitude'],4)
825 self.failUnlessAlmostEqual(r['pos_latitude'],params['pos_latitude'],4)
826 self.failUnlessAlmostEqual(r['speed'],params['speed'],1)
827 self.failUnlessAlmostEqual(r['gust'],params['gust'],1)
828 self.failUnlessEqual(r['direction'],params['direction'])
829 self.failUnlessAlmostEqual(r['atmpressure'],params['atmpressure'],1)
830 self.failUnlessAlmostEqual(r['airtemp'],params['airtemp'],1)
831 self.failUnlessAlmostEqual(r['dewpoint'],params['dewpoint'],1)
832 self.failUnlessAlmostEqual(r['visibility'],params['visibility'],1)
833 self.failUnlessAlmostEqual(r['watertemp'],params['watertemp'],1)
834 self.failUnlessEqual(r['reserved'],params['reserved'])
835
837 parser.add_option('-d','--decode',dest='doDecode',default=False,action='store_true',
838 help='decode a "sls_weatherreport" AIS message')
839 parser.add_option('-e','--encode',dest='doEncode',default=False,action='store_true',
840 help='encode a "sls_weatherreport" AIS message')
841 parser.add_option('--time_month-field', dest='time_monthField',metavar='uint',type='int'
842 ,help='Field parameter value [default: %default]')
843 parser.add_option('--time_day-field', dest='time_dayField',metavar='uint',type='int'
844 ,help='Field parameter value [default: %default]')
845 parser.add_option('--time_hour-field', dest='time_hourField',metavar='uint',type='int'
846 ,help='Field parameter value [default: %default]')
847 parser.add_option('--time_min-field', dest='time_minField',metavar='uint',type='int'
848 ,help='Field parameter value [default: %default]')
849 parser.add_option('--stationid-field', dest='stationidField',default='@@@@@@@',metavar='aisstr6',type='string'
850 ,help='Field parameter value [default: %default]')
851 parser.add_option('--pos_longitude-field', dest='pos_longitudeField',default=Decimal('181'),metavar='decimal',type='string'
852 ,help='Field parameter value [default: %default]')
853 parser.add_option('--pos_latitude-field', dest='pos_latitudeField',default=Decimal('91'),metavar='decimal',type='string'
854 ,help='Field parameter value [default: %default]')
855 parser.add_option('--speed-field', dest='speedField',default=Decimal('102.3'),metavar='udecimal',type='string'
856 ,help='Field parameter value [default: %default]')
857 parser.add_option('--gust-field', dest='gustField',default=Decimal('102.3'),metavar='udecimal',type='string'
858 ,help='Field parameter value [default: %default]')
859 parser.add_option('--direction-field', dest='directionField',default=511,metavar='uint',type='int'
860 ,help='Field parameter value [default: %default]')
861 parser.add_option('--atmpressure-field', dest='atmpressureField',default=Decimal('16383'),metavar='udecimal',type='string'
862 ,help='Field parameter value [default: %default]')
863 parser.add_option('--airtemp-field', dest='airtempField',default=Decimal('-51.2'),metavar='decimal',type='string'
864 ,help='Field parameter value [default: %default]')
865 parser.add_option('--dewpoint-field', dest='dewpointField',default=Decimal('-51.2'),metavar='decimal',type='string'
866 ,help='Field parameter value [default: %default]')
867 parser.add_option('--visibility-field', dest='visibilityField',default=Decimal('25.5'),metavar='udecimal',type='string'
868 ,help='Field parameter value [default: %default]')
869 parser.add_option('--watertemp-field', dest='watertempField',default=Decimal('-51.2'),metavar='decimal',type='string'
870 ,help='Field parameter value [default: %default]')
871
872
873 if __name__=='__main__':
874
875 from optparse import OptionParser
876 parser = OptionParser(usage="%prog [options]",
877 version="%prog "+__version__)
878
879 parser.add_option('--doc-test',dest='doctest',default=False,action='store_true',
880 help='run the documentation tests')
881 parser.add_option('--unit-test',dest='unittest',default=False,action='store_true',
882 help='run the unit tests')
883 parser.add_option('-v','--verbose',dest='verbose',default=False,action='store_true',
884 help='Make the test output verbose')
885
886
887
888 typeChoices = ('binary','nmeapayload','nmea')
889 parser.add_option('-t','--type',choices=typeChoices,type='choice',dest='ioType'
890 ,default='nmeapayload'
891 ,help='What kind of string to write for encoding ('+', '.join(typeChoices)+') [default: %default]')
892
893
894 outputChoices = ('std','html','csv','sql' , 'kml','kml-full')
895 parser.add_option('-T','--output-type',choices=outputChoices,type='choice',dest='outputType'
896 ,default='std'
897 ,help='What kind of string to output ('+', '.join(outputChoices)+') [default: %default]')
898
899 parser.add_option('-o','--output',dest='outputFileName',default=None,
900 help='Name of the python file to write [default: stdout]')
901
902 parser.add_option('-f','--fields',dest='fieldList',default=None, action='append',
903 choices=fieldList,
904 help='Which fields to include in the output. Currently only for csv output [default: all]')
905
906 parser.add_option('-p','--print-csv-field-list',dest='printCsvfieldList',default=False,action='store_true',
907 help='Print the field name for csv')
908
909 parser.add_option('-c','--sql-create',dest='sqlCreate',default=False,action='store_true',
910 help='Print out an sql create command for the table.')
911
912 parser.add_option('--latex-table',dest='latexDefinitionTable',default=False,action='store_true',
913 help='Print a LaTeX table of the type')
914
915 dbChoices = ('sqlite','postgres')
916 parser.add_option('-D','--db-type',dest='dbType',default='postgres'
917 ,choices=dbChoices,type='choice'
918 ,help='What kind of database ('+', '.join(dbChoices)+') [default: %default]')
919
920 addMsgOptions(parser)
921
922 (options,args) = parser.parse_args()
923 success=True
924
925 if options.doctest:
926 import os; print os.path.basename(sys.argv[0]), 'doctests ...',
927 sys.argv= [sys.argv[0]]
928 if options.verbose: sys.argv.append('-v')
929 import doctest
930 numfail,numtests=doctest.testmod()
931 if numfail==0: print 'ok'
932 else:
933 print 'FAILED'
934 success=False
935
936 if not success: sys.exit('Something Failed')
937 del success
938
939 if options.unittest:
940 sys.argv = [sys.argv[0]]
941 if options.verbose: sys.argv.append('-v')
942 unittest.main()
943
944 outfile = sys.stdout
945 if None!=options.outputFileName:
946 outfile = file(options.outputFileName,'w')
947
948
949 if options.doEncode:
950
951 if None==options.time_monthField: parser.error("missing value for time_monthField")
952 if None==options.time_dayField: parser.error("missing value for time_dayField")
953 if None==options.time_hourField: parser.error("missing value for time_hourField")
954 if None==options.time_minField: parser.error("missing value for time_minField")
955 if None==options.stationidField: parser.error("missing value for stationidField")
956 if None==options.pos_longitudeField: parser.error("missing value for pos_longitudeField")
957 if None==options.pos_latitudeField: parser.error("missing value for pos_latitudeField")
958 if None==options.speedField: parser.error("missing value for speedField")
959 if None==options.gustField: parser.error("missing value for gustField")
960 if None==options.directionField: parser.error("missing value for directionField")
961 if None==options.atmpressureField: parser.error("missing value for atmpressureField")
962 if None==options.airtempField: parser.error("missing value for airtempField")
963 if None==options.dewpointField: parser.error("missing value for dewpointField")
964 if None==options.visibilityField: parser.error("missing value for visibilityField")
965 if None==options.watertempField: parser.error("missing value for watertempField")
966 msgDict={
967 'time_month': options.time_monthField,
968 'time_day': options.time_dayField,
969 'time_hour': options.time_hourField,
970 'time_min': options.time_minField,
971 'stationid': options.stationidField,
972 'pos_longitude': options.pos_longitudeField,
973 'pos_latitude': options.pos_latitudeField,
974 'speed': options.speedField,
975 'gust': options.gustField,
976 'direction': options.directionField,
977 'atmpressure': options.atmpressureField,
978 'airtemp': options.airtempField,
979 'dewpoint': options.dewpointField,
980 'visibility': options.visibilityField,
981 'watertemp': options.watertempField,
982 'reserved': '0',
983 }
984
985 bits = encode(msgDict)
986 if 'binary'==options.ioType: print str(bits)
987 elif 'nmeapayload'==options.ioType:
988
989 print "bitLen",len(bits)
990 bitLen=len(bits)
991 if bitLen%6!=0:
992 bits = bits + BitVector(size=(6 - (bitLen%6)))
993 print "result:",binary.bitvectoais6(bits)[0]
994
995
996
997 elif 'nmea'==options.ioType: sys.exit("FIX: need to implement this capability")
998 else: sys.exit('ERROR: unknown ioType. Help!')
999
1000
1001 if options.sqlCreate:
1002 sqlCreateStr(outfile,options.fieldList,dbType=options.dbType)
1003
1004 if options.latexDefinitionTable:
1005 latexDefinitionTable(outfile)
1006
1007 if options.printCsvfieldList:
1008
1009 if None == options.fieldList: options.fieldList = fieldList
1010 import StringIO
1011 buf = StringIO.StringIO()
1012 for field in options.fieldList:
1013 buf.write(field+',')
1014 result = buf.getvalue()
1015 if result[-1] == ',': print result[:-1]
1016 else: print result
1017
1018 if options.doDecode:
1019 for msg in args:
1020 bv = None
1021
1022 if msg[0] in ('$','!') and msg[3:6] in ('VDM','VDO'):
1023
1024
1025 bv = binary.ais6tobitvec(msg.split(',')[5])
1026 else:
1027
1028 binaryMsg=True
1029 for c in msg:
1030 if c not in ('0','1'):
1031 binaryMsg=False
1032 break
1033 if binaryMsg:
1034 bv = BitVector(bitstring=msg)
1035 else:
1036 bv = binary.ais6tobitvec(msg)
1037
1038 printFields(decode(bv)
1039 ,out=outfile
1040 ,format=options.outputType
1041 ,fieldList=options.fieldList
1042 ,dbType=options.dbType
1043 )
1044