forked from pbuckner/XplaneNoaaWeather
/
conf.py
356 lines (302 loc) · 11.9 KB
/
conf.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
"""
X-plane NOAA GFS weather plugin.
Copyright (C) 2012-2020 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.
"""
import os
try:
import cPickle
except ImportError:
import pickle as cPickle
import sys
import subprocess
import json
try:
from c import c
except ImportError:
from . import c
class Conf:
"""Loads and saves configuration variables"""
syspath, dirsep = '', os.sep
printableChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '
__VERSION__ = '2.7.2'
GFS_JSON_HELP = '''Here you can edit which wind levels will be downloaded from NOAA without hacking the code.
Keep the list short to optimize the download size and parsing times.
If you mess-up just remove this file, a new one will be created with default values.
For a full list of levels check:
https://www.nco.ncep.noaa.gov/pmb/products/gfs/gfs.t00z.pgrb2.0p50.f003.shtml
Remove the current cycle from the cache/gfs to trigger a download with new values.
Refer to the following list for millibar Flight Level conversion:'''
def __init__(self, xplane_path=False):
if xplane_path:
self.syspath = xplane_path
self.respath = os.sep.join([xplane_path, 'Resources', 'plugins', 'PythonPlugins', 'noaweather'])
else:
self.respath = os.path.dirname(os.path.abspath(__file__))
self.settingsfile = os.sep.join([self.respath, 'settings.pkl'])
self.serverSettingsFile = os.sep.join([self.respath, 'weatherServer.pkl'])
self.gfsLevelsFile = os.sep.join([self.respath, 'gfs_levels_config.json'])
self.cachepath = os.sep.join([self.respath, 'cache'])
if not os.path.exists(self.cachepath):
os.makedirs(self.cachepath)
self.setDefaults()
self.pluginLoad()
self.serverLoad()
# Config Overrides
self.parserate = 1
# self.metar_agl_limit = 10
# Selects the apropiate wgrib binary
platform = sys.platform
self.spinfo = False
self.win32 = 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':
self.win32 = True
# Set environ for cygwin
os.environ['CYGWIN'] = 'nodosfilewarning'
wgbin = 'WIN32wgrib2.exe'
# Hide wgrib window for windows users
self.spinfo = subprocess.STARTUPINFO()
self.spinfo.dwFlags |= 1 # STARTF_USESHOWWINDOW
self.spinfo.wShowWindow = 0 # 0 or SW_HIDE 0
else:
# Linux?
wgbin = 'linux-glib2.5-i686-wgrib2'
self.wgrib2bin = os.sep.join([self.respath, 'bin', wgbin])
# Enforce execution rights
try:
os.chmod(self.wgrib2bin, 0o775)
except:
pass
def setDefaults(self):
"""Default settings"""
# User settings
self.enabled = True
self.set_wind = True
self.set_tropo = True
self.set_clouds = True
self.set_temp = True
self.set_visibility = False
self.set_turb = True
self.set_pressure = True
self.set_thermals = True
self.set_surface_layer = True
self.turbulence_probability = 1
self.inputbug = False
# From this AGL level METAR values are interpolated to GFS ones.
self.metar_agl_limit = 20 # In meters
# From this distance from the airport gfs data is used for temp, dew, pressure and clouds
self.metar_distance_limit = 100000 # In meters
# keep a surface wind layer with current METAR to get correct ATIS info
self.surface_wind_layer_limit = 600 # In meters over first GFS layer for smooth transition
self.parserate = 1
self.updaterate = 1
self.download = True
self.keepOldFiles = False
# Performance tweaks
self.max_visibility = False # in SM
self.max_cloud_height = False # in feet
# Weather server configuration
self.server_updaterate = 10 # Run the weather loop each #seconds
self.server_address = '127.0.0.1'
self.server_port = 8950
# Weather server variables
self.lastgrib = False
self.lastwafsgrib = False
self.ms_update = 0
self.weatherServerPid = False
# Surface wind random variability range
self.maxRandomWindHdg = 5 # degrees
self.maxRandomWindGust = 5 # kt
# Max Turbulence (4 = severe turbulence)
self.max_turbulence = 4
# Transitions
self.windTransSpeed = 0.5 # kt/s
self.windGustTransSpeed = 1 # kt/s
self.windHdgTransSpeed = 1 # degrees/s
self.metar_source = 'NOAA'
self.metar_updaterate = 5 # minutes
self.tracker_uid = False
self.tracker_enabled = True
self.ignore_metar_stations = []
self.updateMetarRWX = True
def saveSettings(self, filepath, settings):
print("Saving Settings to {}".format(filepath))
f = open(filepath, 'wb')
cPickle.dump(settings, f)
f.close()
def loadSettings(self, filepath):
if os.path.exists(filepath):
f = open(filepath, 'rb')
try:
conf = cPickle.load(f)
f.close()
except:
# Corrupted settings, remove file
os.remove(filepath)
return
# Reset settings on different versions.
if not 'version' in conf or conf['version'] < '2.0':
return
# may be "dangerous" if someone messes our config file
for var in conf:
if var in self.__dict__:
self.__dict__[var] = conf[var]
# Versions config overrides
if 'version' in conf:
if conf['version'] < '2.3.1':
# Enforce metar station update
self.ms_update = 0
if conf['version'] < '2.4.0':
# Clean ignore stations
self.ignore_metar_stations = []
if conf['version'] < '2.4.3':
self.inputbug = True
def pluginSave(self):
"""Save plugin settings"""
conf = {
'version': self.__VERSION__,
'set_temp': self.set_temp,
'set_clouds': self.set_clouds,
'set_wind': self.set_wind,
'set_turb': self.set_turb,
'set_pressure': self.set_pressure,
'set_tropo': self.set_tropo,
'set_thermals': self.set_thermals,
'set_surface_layer': self.set_surface_layer,
'enabled': self.enabled,
'updaterate': self.updaterate,
'metar_source': self.metar_source,
'download': self.download,
'metar_agl_limit': self.metar_agl_limit,
'metar_distance_limit': self.metar_distance_limit,
'max_visibility': self.max_visibility,
'max_cloud_height': self.max_cloud_height,
'turbulence_probability': self.turbulence_probability,
'inputbug': self.inputbug,
'metar_updaterate': self.metar_updaterate,
'tracker_uid': self.tracker_uid,
'tracker_enabled': self.tracker_enabled,
'ignore_metar_stations': self.ignore_metar_stations
}
self.saveSettings(self.settingsfile, conf)
def pluginLoad(self):
self.loadSettings(self.settingsfile)
if self.metar_source == 'NOAA':
self.metar_updaterate = 5
else:
self.metar_updaterate = 10
def serverSave(self):
"""Save weather server settings"""
server_conf = {
'version': self.__VERSION__,
'lastgrib': self.lastgrib,
'lastwafsgrib': self.lastwafsgrib,
'ms_update': self.ms_update,
'weatherServerPid': self.weatherServerPid,
}
self.saveSettings(self.serverSettingsFile, server_conf)
def serverLoad(self):
self.pluginLoad()
self.loadSettings(self.serverSettingsFile)
# Load the GFS levels file or create a new one.
if os.path.isfile(self.gfsLevelsFile):
self.gfs_variable_list = self.load_gfs_levels(self.gfsLevelsFile)
else:
self.gfs_variable_list = self.gfs_levels_defaults()
self.save_gfs_levels(self.gfs_variable_list)
@staticmethod
def gfs_levels_defaults():
"""GFS Levels default config"""
d = [
{
"vars": [
"TMP",
"UGRD",
"VGRD"
],
"levels": [
"850 mb",
"700 mb",
"600 mb",
"500 mb",
"400 mb",
"300 mb",
"200 mb",
"150 mb"
]
},
{
"vars": "PRES",
"levels": [
"low cloud bottom level",
"low cloud top level",
"middle cloud bottom level",
"middle cloud top level",
"high cloud bottom level",
"high cloud top level"
]
},
{
"vars": "LCDC",
"levels": "low cloud layer"
},
{
"vars": "MCDC",
"levels": "middle cloud layer"
},
{
"vars": "HCDC",
"levels": "high cloud layer"
},
{
"vars": "PRMSL",
"levels": "mean sea level"
},
{
"vars": [
"PRES",
"TMP"
],
"levels": "tropopause"
}
]
return d
def save_gfs_levels(self, levels):
"""Save gfs levels settings to a json file"""
with open(self.gfsLevelsFile, 'w') as f:
config = {'comment': [line.strip() for line in iter(self.GFS_JSON_HELP.splitlines())],
'config': levels,
}
level = c.gfs_levels_help_list()
config['comment'] += [' | '.join(level[i:i + 5]) for i in range(0, len(level), 5)]
json.dump(config, f, indent=2)
def load_gfs_levels(self, json_file):
"""Load gfs levels configuration from a json file"""
print("Trying to loca gfs jsonfile {}".format(json_file))
with open(json_file, 'r') as f:
try:
return json.load(f)['config']
except (KeyError, Exception) as err:
print("Format ERROR parsing gfs levels file: %s" % str(err))
return self.gfs_levels_defaults()
@staticmethod
def can_exec(file_path):
return os.path.isfile(file_path) and os.access(file_path, os.X_OK)
@staticmethod
def find_in_path(filename, path_separator=':'):
if 'PATH' in os.environ:
for path in os.environ['PATH'].split(path_separator):
full_path = os.path.sep.join([path, filename])
if Conf.can_exec(full_path):
return full_path
return False