forked from joanpc/XplaneNoaaWeather
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PI_noaaWeather.py
1264 lines (1085 loc) · 51.2 KB
/
PI_noaaWeather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
X-plane NOAA GFS weather plugin.
Sets x-plane wind and cloud layers using NOAA real/forecast data.
This plugin downloads required data from NOAA servers.
Uses wgrib2 to parse NOAA grib2 data files.
Includes wgrib2 binaries for Mac Win32 and linux i386glibc6
Win32 wgrib2 requires cgywin now included in the resources folder
TODO:
- Remove shear and turbulence on transition
- Rain, snow, wind shears, visibility
- msl pressure
- remove old grib files from cache
Copyright (C) 2012 Joan Perez i Cauhe
---
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
__VERSION__ = '1.5.9'
#Python includes
from datetime import datetime, timedelta
import threading
from math import hypot, atan2, degrees, exp
import os
import sys
import cPickle
import multiprocessing
import Queue
import urllib
import subprocess
#### stderr stdout ebeded python workaround ####
class wr_stdout():
write = sys.stdout.write
def flush(self):
pass
class wr_stderr():
write = sys.stderr.write
def flush(self):
pass
sys.stdout = wr_stdout()
sys.stderr = wr_stderr()
# Argv missing on windows
sys.argv = ['']
### ############################################
class AsyncDownload():
'''
Asyncronous download
'''
def __init__(self, conf, url, cachefile):
self.q = Queue.Queue()
self.dirsep = conf.dirsep[:]
cachepath = conf.cachepath[:]
self.wgrib2bin = conf.wgrib2bin[:]
'''if sys.platform == 'win32':
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
self.child = multiprocessing.Process(target=self.run, args=(url, cachepath, cachefile))
self.child.start()
'''
t = threading.Thread(target = self.run, args = (url, cachepath, cachefile))
t.daemon = True
t.start()
def run(self, url, cachepath, cachefile):
filepath = cachepath + "/" + cachefile
tempfile = filepath + '.tmp'
urllib.urlretrieve(url, tempfile)
if os.path.getsize(tempfile) > 500:
# Downloaded
# unpack grib file
subprocess.call([self.wgrib2bin, tempfile, '-set_grib_type', 'simple', '-grib_out', filepath])
os.remove(tempfile)
self.q.put(cachefile)
else:
# File unavaliable, empty file; wait 5 minutes
#print "XPGFS: Error downloading: %s" % (self.cachefile)
if os.path.exists(tempfile):
os.remove(tempfile)
self.q.put(False)
def die(self):
pass
# Detect x-plane plugin
if sys.platform != 'win32' or 'plane' in sys.executable.lower():
# X-plane includes
from XPLMDefs import *
from XPLMProcessing import *
from XPLMDataAccess import *
from XPLMUtilities import *
from XPLMPlanes import *
from XPLMNavigation import *
from SandyBarbourUtilities import *
from PythonScriptMessaging import *
from XPLMPlugin import *
from XPLMMenus import *
from XPWidgetDefs import *
from XPWidgets import *
from XPStandardWidgets import *
from EasyDref import EasyDref
class c:
'''
Conversion tools
'''
@classmethod
def ms2knots(self, val):
return val * 1.94384
@classmethod
def kel2cel(self, val):
return val - 273.15
@classmethod
def c2p(self, x, y):
#Cartesian 2 polar conversion
r = hypot(x, y)
a = degrees(atan2(x, y))
if a < 0:
a += 360
if a <= 180:
a = a + 180
else:
a = a -180
return a, r
@classmethod
def mb2alt(self, mb):
altpress = 44330.8 - (4946.54 * (mb*100)**0.1902632)
return altpress
@classmethod
def oat2msltemp(self, oat, alt):
# Convert layer temperature to mean sea level
return oat + 0.0065 * alt - 273.15
@classmethod
def interpolate(self, t1, t2, alt1, alt2, alt):
if (alt2 - alt1) == 0:
print '[XPGFS] BUG: please report: ', t1, t2, alt1, alt2, alt
return t2
return t1 + (alt - alt1)*(t2 -t1)/(alt2 -alt1)
@classmethod
def fog2(self, rh):
return (80 - rh)/20*24634
@classmethod
def toFloat(self, string, default = 0):
# try to convert to float or return default
try:
val = float(string)
except ValueError:
val = default
return val
@classmethod
def rh2visibility(self, rh):
return 60.0*exp(-2.5*(rh-15)/80.0)
@classmethod
def shortHdg(self, a, b):
if a == 360: a = 0
if b == 360: b = 0
if a > b:
cw = (360 - a + b)
ccw = -(a - b);
else:
cw = -(360 - b + a)
ccw = (b - a)
if abs(cw) < abs(ccw):
return cw
return ccw
class Conf:
'''
Configuration variables
'''
syspath, dirsep = '','/'
def __init__(self):
# Inits conf
self.syspath = XPLMGetSystemPath(self.syspath)[:-1]
self.respath = self.dirsep.join([self.syspath, 'Resources', 'plugins', 'PythonScripts', 'noaaWeatherResources'])
self.settingsfile = self.respath + self.dirsep + 'settings.pkl'
self.cachepath = self.dirsep.join([self.respath, 'cache'])
if not os.path.exists(self.cachepath):
os.makedirs(self.cachepath)
# Storable settings, Defaults
self.enabled = True
self.set_wind = True
self.set_clouds = True
self.set_temp = True
self.set_visibility = False
self.set_turb = True
self.transalt = 32808.399000000005
self.use_metar = False
self.lastgrib = False
self.lastwafsgrib = False
self.updaterate = 4
self.parserate = 0.05
self.vatsim = False
self.download = True
self.load()
# Override config
self.parserate = 0.1
if self.lastgrib and not os.path.exists(self.cachepath + self.dirsep + self.lastgrib):
self.lastgrib = False
# Selects the apropiate wgrib binary
platform = sys.platform
maxsize = sys.maxsize
self.spinfo = False
if platform == 'darwin':
sysname, nodename, release, version, machine = os.uname()
if float(release[0:4]) > 10.6:
wgbin = 'OSX106wgrib2'
else:
wgbin = 'OSX106wgrib2'
elif platform == 'win32':
wgbin = 'WIN32wgrib2.exe'
# Configure subprocess
self.spinfo = subprocess.STARTUPINFO()
self.spinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
elif platform.startswith('linux'):
if maxsize > 2**32:
wgbin = 'wgrib2'
else:
wgbin = 'linux-glib2.5-i686-wgrib2'
else:
# Linux?
wgbin = 'linux-glib2.5-i686-wgrib2'
self.wgrib2bin = self.dirsep.join([self.respath, 'bin', wgbin])
# Enforce execution rights
try:
os.chmod(self.wgrib2bin, 0775)
except:
pass
def save(self):
conf = {
'version' : __VERSION__,
'lastgrib' : self.lastgrib,
'set_temp' : self.set_temp,
'set_clouds': self.set_clouds,
'set_wind' : self.set_wind,
'set_turb' : self.set_turb,
'transalt' : self.transalt,
'use_metar' : self.use_metar,
'enabled' : self.enabled,
'updaterate': self.updaterate,
'vatsim' : self.vatsim,
'lastwafsgrib' : self.lastwafsgrib,
'download' : self.download
}
f = open(self.settingsfile, 'w')
cPickle.dump(conf, f)
f.close()
def load(self):
if os.path.exists(self.settingsfile):
f = open(self.settingsfile, 'r')
try:
conf = cPickle.load(f)
f.close()
except:
# Corrupted settings, remove file
os.remove(self.settingsfile)
return
# may be "dangerous"
for var in conf:
if var in self.__dict__:
self.__dict__[var] = conf[var]
class Weather:
'''
Sets x-plane weather from GSF parsed data
'''
alt = 0.0
ref_winds = {}
def __init__(self, conf):
self.conf = conf
'''
Bind datarefs
'''
self.winds = []
self.clouds = []
self.turbulence = {}
for i in range(3):
self.winds.append({
'alt': EasyDref('"sim/weather/wind_altitude_msl_m[%d]"' % (i), 'float'),
'hdg': EasyDref('"sim/weather/wind_direction_degt[%d]"' % (i), 'float'),
'speed': EasyDref('"sim/weather/wind_speed_kt[%d]"' % (i), 'float'),
'turbulence': EasyDref('"sim/weather/turbulence[%d]"' % (i), 'float'),
})
for i in range(3):
self.clouds.append({
'top': EasyDref('"sim/weather/cloud_tops_msl_m[%d]"' % (i), 'float'),
'bottom': EasyDref('"sim/weather/cloud_base_msl_m[%d]"' % (i), 'float'),
'coverage': EasyDref('"sim/weather/cloud_type[%d]"' % (i), 'int'),
# XP10 'coverage': EasyDref('"sim/weather/cloud_coverage[%d]"' % (i), 'float'),
})
self.windata = []
self.xpWeatherOn = EasyDref('sim/weather/use_real_weather_bool', 'int')
self.msltemp = EasyDref('sim/weather/temperature_sealevel_c', 'float')
self.dewpoint = EasyDref('sim/weather/dewpoi_sealevel_c', 'float')
self.thermalAlt = EasyDref('sim/weather/thermal_altitude_msl_m', 'float')
self.visibility = EasyDref('sim/weather/visibility_reported_m', 'float')
def setWindLayer(self,xpwind, layer, data, elapsed):
# Sets wind layer and does transition if needed
alt, hdg, speed = data[0], data[1], data[2]
calt = xpwind['alt'].value
if int(alt*100) != int(calt*100):
# layer change trasition not needed xplane does interpolation
xpwind['alt'].value, xpwind['hdg'].value, xpwind['speed'].value = alt, hdg, speed
self.ref_winds[layer] = (alt, hdg, speed)
else:
# Transition
if not layer in self.ref_winds:
# Store reference wind layer to ignore x-plane roundings
self.ref_winds[layer] = ( xpwind['alt'].value, xpwind['hdg'].value, xpwind['speed'].value)
if self.ref_winds[layer] == (data[0], data[1], data[2]):
# No need to transition if the data is updated
return
calt, chdg, cspeed = self.ref_winds[layer]
hdg = self.transHdg(chdg, hdg, elapsed)
speed = self.transWind(cspeed, speed, elapsed)
self.ref_winds[layer] = calt, hdg, speed
xpwind['hdg'].value = hdg
xpwind['speed'].value = speed
def transWind(self, current, new, elapsed, vel=1):
'''
Time based wind speed transition
'''
if current > new:
dir = -1
else:
dir = 1
if abs(current - new) < vel*elapsed + 0.1:
return new
else:
return current + dir * vel * elapsed
def transHdg(self, current, new, elapsed, vel=12):
'''
Time based wind heading transition
'''
diff = c.shortHdg(current, new)
if abs(diff) < vel*elapsed:
return new
else:
if diff > 0:
diff = +1
else:
diff = -1
newval = current + diff * vel * elapsed
if newval < 0:
return newval + 360
else:
return newval % 360
def setTurbulence(self, turbulence):
'''
Set turbulence for all wind layers with our own interpolation
'''
prevlayer = False
if len(turbulence) > 1:
for clayer in turbulence:
if clayer[0] > self.alt:
#last layer
break
else:
prevlayer = clayer
if prevlayer:
turb = c.interpolate(prevlayer[1], clayer[1], prevlayer[0], clayer[0], self.alt)
else:
turb = clayer[1]
# set turbulence
self.winds[0]['turbulence'].value = turb
self.winds[1]['turbulence'].value = turb
self.winds[2]['turbulence'].value = turb
def setWinds(self, winds, elapsed):
# Sets wind layers and temperature
prevlayer = False
wl = self.winds
if len(winds) > 1:
for wind in range(len(winds)):
wlayer = winds[wind]
if wlayer[0] > self.alt:
#last layer
break
else:
prevlayer = wlayer
if prevlayer:
self.setWindLayer(wl[1], 1, prevlayer, elapsed)
self.setWindLayer(wl[2], 2, wlayer, elapsed)
else:
self.setWindLayer(wl[1], 1, wlayer, elapsed)
# Set temperature
if self.conf.set_temp and wlayer[3]['temp']:
# Interpolate with previous layer
if prevlayer and prevlayer[0] != wlayer[0] and wlayer[3]['temp']:
temp = c.interpolate(prevlayer[3]['temp'], wlayer[3]['temp'], prevlayer[0], wlayer[0], self.alt)
self.msltemp.value = temp
else:
self.msltemp.value = wlayer[3]['temp']
'''
# Set visibility
if self.conf.set_visibility and wlayer[3]['vis']:
if prevlayer and prevlayer[0] != wlayer[0] and wlayer[3]['vis']:
self.visibility.value = c.interpolate(prevlayer[3]['vis'], wlayer[3]['vis'], prevlayer[0], wlayer[0], self.alt)
else:
self.visibility.value = wlayer[3]['vis']
'''
# First wind level
if self.conf.vatsim:
return
if not self.conf.use_metar:
# Set first wind level if we don't use metar
self.setWindLayer(wl[0], 0, winds[0], elapsed)
elif self.alt > winds[0][0]:
# Set first wind level on "descent"
self.setWindLayer(wl[0], 0, winds[0], elapsed)
def setClouds(self, clouds):
if len(clouds) > 2:
for i in range(3):
clayer = clouds.pop()
cl = self.clouds
if clayer[2] == '0':
cl[i]['coverage'].value = clayer[2]
else:
if int(cl[i]['bottom'].value) != int(clayer[0]) and cl[i]['coverage'].value != clayer[2]:
cl[i]['bottom'].value, cl[i]['top'].value, cl[i]['coverage'].value = clayer
@classmethod
def cc2xp(self, cover):
#Cloud cover to X-plane
xp = cover/100.0*4
if xp < 1 and cover > 0:
xp = 1
elif cover > 89:
xp = 4
return xp
class GFS(threading.Thread):
'''
NOAA GFS download and parse functions.
'''
cycles = [0, 6, 12, 18]
baseurl = 'http://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p50.pl?' # Patch by qwerty2k2
params = [
'leftlon=0',
'rightlon=360',
'toplat=90',
'bottomlat=-90',
]
levels = [
'700_mb', # FL100
'500_mb', # FL180
'400_mb', # FL235
'300_mb', # FL300
'200_mb', # FL380
'150_mb', # FL443
'100_mb', # FL518
'high_cloud_bottom_level',
'high_cloud_layer',
'high_cloud_top_level',
'low_cloud_bottom_level',
'low_cloud_layer',
'low_cloud_top_level',
#'mean_sea_level',
'middle_cloud_bottom_level',
'middle_cloud_layer',
'middle_cloud_top_level',
#'surface',
]
variables = ['PRES',
'TCDC',
'UGRD',
'VGRD',
'TMP',
#'RH',
]
nwinds, nclouds = 0, 0
downloading = False
downloadWait = 0
# wait n seconds to start download
lastgrib = False
lat, lon, lastlat, lastlon = False, False, False, False
cycle = ''
lastcycle = ''
winds = False
clouds = False
newGrib = False
parsed_latlon = (0, 0)
die = threading.Event()
lock = threading.Lock()
def __init__(self, conf):
self.conf = conf
self.lastgrib = self.conf.lastgrib
self.wafs = WAFS(conf, self.lock)
self.dummy_event = threading.Event()
threading.Thread.__init__(self)
def run(self):
# Worker thread
while not self.die.isSet():
if not self.conf.enabled:
#Sleep if disabled
self.dummy_event.wait(timeout=self.conf.parserate * 2)
continue
# Parse grib if required
lat, lon = round(self.lat/5,1)*5, round(self.lon/5,1)*5
if self.lastgrib and (lat != self.lastlat or lon != self.lastlon):
#print "XPGFS: parsing - %s - %i,%i" % (self.lastgrib, lat, lon)
self.parseGribData(self.lastgrib, lat, lon)
self.lastlat, self.lastlon = lat, lon
self.newGrib = False
datecycle, cycle, forecast = self.getCycleDate()
if self.downloadWait < 1:
self.downloadCycle(datecycle, cycle, forecast)
elif self.downloadWait > 0:
self.downloadWait -= self.conf.parserate
# Run WAFS
self.wafs.run(self.lat, self.lon, self.conf.parserate)
#wait
if self.die.isSet():
# Kill downloaders if avaliable
if self.wafs and self.wafs.downloading and self.wafs.download:
self.wafs.download.die()
if self.downloading and self.download:
self.download.die()
return
self.dummy_event.wait(timeout=self.conf.parserate)
def getCycleDate(self):
'''
Returns last cycle date avaliable
'''
now = datetime.utcnow()
#cycle is published with 3 hours delay
cnow = now - timedelta(hours=3, minutes=0)
#get last cycle
for cycle in self.cycles:
if cnow.hour >= cycle:
lcycle = cycle
# Forecast
adjs = 0
if cnow.day != now.day:
adjs = +24
forecast = (adjs + now.hour - lcycle)/3*3
return ( '%d%02d%02d%02d' % (cnow.year, cnow.month, cnow.day, lcycle), lcycle, forecast)
def downloadCycle(self, datecycle, cycle, forecast):
'''
Downloads the requested grib file
'''
filename = 'gfs.t%02dz.pgrb2full.0p50.f0%02d' % (cycle, forecast) # Patch by qwerty2k2
path = self.conf.dirsep.join([self.conf.cachepath, datecycle])
cachefile = datecycle + self.conf.dirsep + filename + '.grib'
if cachefile == self.lastgrib:
# No need to download
return
if not os.path.exists(path):
os.makedirs(path)
if self.downloading == True:
if not self.download.q.empty():
#Finished downloading
lastgrib = self.download.q.get()
# Dowload success
if lastgrib:
self.lock.acquire()
self.lastgrib = lastgrib
self.conf.lastgrib = self.lastgrib
self.newGrib = True
#print "new grib file: " + self.lastgrib
self.lock.release()
else:
# Wait a minute
self.downloadWait = 60
self.downloading = False
elif self.conf.download and self.downloadWait < 1:
# Download new grib
## Build download url
params = self.params;
dir = 'dir=%%2Fgfs.%s' % (datecycle) # Patch by qwerty2k2
params.append(dir)
params.append('file=' + filename)
# add variables
for level in self.levels:
params.append('lev_' + level + '=1')
for var in self.variables:
params.append('var_' + var + '=1')
url = self.baseurl + '&'.join(params)
#print 'XPGFS: downloading %s' % (filename)
self.downloading = True
self.download = AsyncDownload(self.conf, url, cachefile)
return False
def parseGribData(self, filepath, lat, lon):
'''
Executes wgrib2 and parses its output
'''
args = ['-s',
'-lon',
'%f' % (lon),
'%f' % (lat),
self.conf.cachepath + self.conf.dirsep + filepath
]
if self.conf.spinfo:
p = subprocess.Popen([self.conf.wgrib2bin] + args, stdout=subprocess.PIPE, startupinfo=self.conf.spinfo)
else:
p = subprocess.Popen([self.conf.wgrib2bin] + args, stdout=subprocess.PIPE)
it = iter(p.stdout)
data = {}
clouds = {}
for line in it:
r = line[:-1].split(':')
# Level, variable, value
level, variable, value = [r[4].split(' '), r[3], r[7].split(',')[2].split('=')[1]]
if len(level) > 1:
if level[1] == 'cloud':
#cloud layer
clouds.setdefault(level[0], {})
if len(level) > 3 and variable == 'PRES':
clouds[level[0]][level[2]] = value
else:
#level coverage/temperature
clouds[level[0]][variable] = value
elif level[1] == 'mb':
# wind levels
data.setdefault(level[0], {})
data[level[0]][variable] = value
elif level[0] == 'surface':
#surface layer
pass
windlevels = []
cloudlevels = []
# Let data ready to push on datarefs.
# Convert wind levels
for level in data:
wind = data[level]
if 'UGRD' in wind and 'VGRD' in wind:
hdg, vel = c.c2p(float(wind['UGRD']), float(wind['VGRD']))
#print wind['UGRD'], wind['VGRD'], float(wind['UGRD']), float(wind['VGRD']), hdg, vel
alt = c.mb2alt(float(level))
# Optional varialbes
temp, vis = False, False
# Temperature
if 'TMP' in wind:
temp = c.oat2msltemp(float(wind['TMP']), alt)
# Relative Humidity
#if 'RH' in wind:
# vis = c.rh2visibility(float(wind['RH']))*1000
# if vis > 40000:
# vis = 40000
else:
temp = False
windlevels.append((alt, hdg, c.ms2knots(vel), {'temp': temp, 'vis': vis}))
#print 'alt: %i rh: %i vis: %i' % (alt, float(wind['RH']), vis)
# Convert cloud level
for level in clouds:
level = clouds[level]
if 'top' in level and 'bottom' in level and 'TCDC' in level:
top, bottom, cover = float(level['top']), float(level['bottom']), float(level['TCDC'])
#print "XPGFS: top: %.0fmbar %.0fm, bottom: %.0fmbar %.0fm %d%%" % (top * 0.01, c.mb2alt(top * 0.01), bottom * 0.01, c.mb2alt(bottom * 0.01), cover)
cloudlevels.append((c.mb2alt(bottom * 0.01) * 0.3048, c.mb2alt(top * 0.01) * 0.3048, int(Weather.cc2xp(cover))))
#XP10 cloudlevels.append((c.mb2alt(bottom * 0.01) * 0.3048, c.mb2alt(top * 0.01) * 0.3048, cover/10))
windlevels.sort()
cloudlevels.sort(reverse=True)
#del data
#del clouds
self.lock.acquire()
self.winds = windlevels
self.clouds = cloudlevels
self.nwinds = len(windlevels)
self.nclouds = len(cloudlevels)
self.parsed_latlon = (lat, lon)
self.lock.release()
def reparse(self):
self.lastlat = False
self.lastlon = False
self.newGrib = True
class WAFS:
'''
World Area Forecast System - Upper Air Forecast
Download and parse functions
'''
cycles = [0, 6, 12, 18]
forecasts = [6, 9, 12, 15, 18, 21, 24]
baseurl = 'http://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod'
current_datecycle = False
downloading = False
lastgrib = False
lastlat, lastlon = False, False
turbulence = {}
nturbulence = 0
downloadWait = 0
def __init__(self, conf, lock):
self.conf = conf
self.downloading = False
self.lock = lock
# Use last grib stored in config if still avaliable
if self.conf.lastwafsgrib and os.path.exists(self.conf.cachepath + '/' + self.conf.lastwafsgrib):
self.lastgrib = self.conf.lastwafsgrib
self.current_datecycle = self.conf.lastwafsgrib.split('/')[0]
def run(self, lat, lon, rate):
# Worker thread
# Parse grib if required
lat, lon = round(lat), round(lon)
if self.lastgrib and (lat != self.lastlat or lon != self.lastlon):
self.parseGribData(self.lastgrib, lat, lon)
self.lastlat, self.lastlon = lat, lon
self.newGrib = False
datecycle, cycle, forecast = self.getCycleDate()
# Use new grib if dowloaded
if self.downloading == True:
if not self.download.q.empty():
lastgrib = self.download.q.get()
#print "Downloaded grib: " + lastgrib
self.downloading = False
if lastgrib:
self.lock.acquire()
self.lastgrib = lastgrib
self.conf.lastwafsgrib = lastgrib
self.current_datecycle = self.conf.lastwafsgrib.split('/')[0]
self.lock.release()
else:
# Download fail
self.downloadWait = 60
if self.downloadWait > 0:
self.downloadWait -= rate
# Download new grib if required
if self.current_datecycle != datecycle and self.conf.download and not self.downloading and self.downloadWait < 1:
self.downloadCycle(datecycle, cycle, forecast)
def getCycleDate(self):
'''
Returns last cycle date avaliable
'''
now = datetime.utcnow()
# cycle is published with 3 hours delay
cnow = now - timedelta(hours=6, minutes=0)
# Get last cycle
for cycle in self.cycles:
if cnow.hour >= cycle:
lcycle = cycle
# Forecast
adjs = 0
if cnow.day != now.day:
adjs = +24
# Elapsed from cycle
forecast = (adjs + now.hour - lcycle)
# Get current forecast
for fcast in self.forecasts:
if forecast <= fcast:
forecast = fcast
break
return ( '%d%02d%02d%02d' % (cnow.year, cnow.month, cnow.day, lcycle), lcycle, forecast)
def parseGribData(self, filepath, lat, lon):
'''
Executes wgrib2 and parses its output
'''
args = ['-s',
'-lon',
'%f' % (lon),
'%f' % (lat),
self.conf.cachepath + self.conf.dirsep + filepath
]
if self.conf.spinfo:
p = subprocess.Popen([self.conf.wgrib2bin] + args, stdout=subprocess.PIPE, startupinfo=self.conf.spinfo)
else:
p = subprocess.Popen([self.conf.wgrib2bin] + args, stdout=subprocess.PIPE)
it = iter(p.stdout)
cat = {}
for line in it:
r = line[:-1].split(':')
# Level, variable, value
level, variable, value = [r[4].split(' '), r[3], r[7].split(',')[2].split('=')[1]]
if len(level) > 1 and level[1] == 'mb':
#print level[1], variable, value
alt = c.mb2alt(float(level[0]))
value = float(value)
if value < 0:
value = 0
if variable == 'CTP':
cat[alt] = value
if variable == 'CAT':
cat[alt] = value
turbulence = []
for key, value in cat.iteritems():
turbulence.append([key, value/10])
turbulence.sort()
self.lock.acquire()
self.turbulence = turbulence
self.nturbulence = len(turbulence)
self.lock.release()
def downloadCycle(self, datecycle, cycle, forecast):
self.downloading = True
file = "WAFS_blended_%sf%02d.grib2" % (datecycle, forecast )
url = "%s/gfs.%s/%s" % (self.baseurl, datecycle, file)
cachefile = self.conf.dirsep.join([datecycle, file])
path = self.conf.cachepath + '/' + datecycle
if not os.path.exists(path):
os.makedirs(path)
#print cachefile, url
self.download = AsyncDownload(self.conf, url, cachefile)
class PythonInterface:
'''
Xplane plugin
'''
def XPluginStart(self):
self.Name = "noaWeather - " + __VERSION__
self.Sig = "noaWeather.joanpc.PI"
self.Desc = "NOA GFS in x-plane"
self.latdr = EasyDref('sim/flightmodel/position/latitude', 'double')
self.londr = EasyDref('sim/flightmodel/position/longitude', 'double')
self.altdr = EasyDref('sim/flightmodel/position/elevation', 'double')
self.conf = Conf()
self.weather = Weather(self.conf)
self.gfs = False
# floop
self.floop = self.floopCallback
XPLMRegisterFlightLoopCallback(self, self.floop, -1, 0)
# Menu / About
self.Mmenu = self.mainMenuCB
self.aboutWindow = False
self.mPluginItem = XPLMAppendMenuItem(XPLMFindPluginsMenu(), 'XP NOAA Weather', 0, 1)
self.mMain = XPLMCreateMenu(self, 'XP NOAA Weather', XPLMFindPluginsMenu(), self.mPluginItem, self.Mmenu, 0)
# Menu Items
self.mReFuel = XPLMAppendMenuItem(self.mMain, 'Configuration', 1, 1)
return self.Name, self.Sig, self.Desc
def mainMenuCB(self, menuRef, menuItem):
'''
Main menu Callback
'''
if menuItem == 1:
if (not self.aboutWindow):
self.CreateAboutWindow(221, 640)
self.aboutWindow = True
elif (not XPIsWidgetVisible(self.aboutWindowWidget)):
XPShowWidget(self.aboutWindowWidget)
def CreateAboutWindow(self, x, y):
x2 = x + 450
y2 = y - 85 - 20 * 10
Buffer = "X-Plane NOAA GFS Weather - %s" % (__VERSION__)
top = y
# Create the Main Widget window
self.aboutWindowWidget = XPCreateWidget(x, y, x2, y2, 1, Buffer, 1,0 , xpWidgetClass_MainWindow)
window = self.aboutWindowWidget
## MAIN CONFIGURATION ##
# Config Sub Window, style
subw = XPCreateWidget(x+10, y-30, x+180 + 10, y2+40 -25, 1, "" , 0,window, xpWidgetClass_SubWindow)
XPSetWidgetProperty(subw, xpProperty_SubWindowType, xpSubWindowStyle_SubWindow)
x += 25
# Main enalbe
XPCreateWidget(x, y-40, x+20, y-60, 1, 'Enable XPGFS', 0, window, xpWidgetClass_Caption)
self.enableCheck = XPCreateWidget(x+110, y-40, x+120, y-60, 1, '', 0, window, xpWidgetClass_Button)
XPSetWidgetProperty(self.enableCheck, xpProperty_ButtonType, xpRadioButton)
XPSetWidgetProperty(self.enableCheck, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox)
XPSetWidgetProperty(self.enableCheck, xpProperty_ButtonState, self.conf.enabled)
y -=25
# Winds enalbe
XPCreateWidget(x+5, y-40, x+20, y-60, 1, 'Wind levels', 0, window, xpWidgetClass_Caption)
self.windsCheck = XPCreateWidget(x+110, y-40, x+120, y-60, 1, '', 0, window, xpWidgetClass_Button)
XPSetWidgetProperty(self.windsCheck, xpProperty_ButtonType, xpRadioButton)
XPSetWidgetProperty(self.windsCheck, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox)
XPSetWidgetProperty(self.windsCheck, xpProperty_ButtonState, self.conf.set_wind)
y -= 20
# Clouds enalbe
XPCreateWidget(x+5, y-40, x+20, y-60, 1, 'Cloud levels', 0, window, xpWidgetClass_Caption)
self.cloudsCheck = XPCreateWidget(x+110, y-40, x+120, y-60, 1, '', 0, window, xpWidgetClass_Button)
XPSetWidgetProperty(self.cloudsCheck, xpProperty_ButtonType, xpRadioButton)
XPSetWidgetProperty(self.cloudsCheck, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox)
XPSetWidgetProperty(self.cloudsCheck, xpProperty_ButtonState, self.conf.set_clouds)
y -= 20
# Temperature enalbe
XPCreateWidget(x+5, y-40, x+20, y-60, 1, 'Temperature', 0, window, xpWidgetClass_Caption)
self.tempCheck = XPCreateWidget(x+110, y-40, x+120, y-60, 1, '', 0, window, xpWidgetClass_Button)
XPSetWidgetProperty(self.tempCheck, xpProperty_ButtonType, xpRadioButton)
XPSetWidgetProperty(self.tempCheck, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox)
XPSetWidgetProperty(self.tempCheck, xpProperty_ButtonState, self.conf.set_temp)
y -= 20
# Turbulence enable
XPCreateWidget(x+5, y-40, x+20, y-60, 1, 'Turbulence', 0, window, xpWidgetClass_Caption)
self.turbCheck = XPCreateWidget(x+110, y-40, x+120, y-60, 1, '', 0, window, xpWidgetClass_Button)
XPSetWidgetProperty(self.turbCheck, xpProperty_ButtonType, xpRadioButton)