Skip to content

Commit

Permalink
wind managing improved, version bump
Browse files Browse the repository at this point in the history
  • Loading branch information
biuti committed Dec 14, 2021
1 parent ece3375 commit 79238f4
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 139 deletions.
14 changes: 3 additions & 11 deletions PI_noaaWeather.py
Expand Up @@ -35,8 +35,6 @@
from XPLMUtilities import *
from XPLMPlanes import *
from XPLMNavigation import *
# from SandyBarbourUtilities import *
# from PythonScriptMessaging import *
from XPLMPlugin import *
from XPLMMenus import *
from XPWidgetDefs import *
Expand Down Expand Up @@ -90,7 +88,6 @@ def __init__(self, conf, data):
'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 = []
Expand Down Expand Up @@ -1347,14 +1344,9 @@ def weatherInfo(self):
t = wdata['thermals']
sysinfo += [f"THERMALS: h {round(t['alt'])}m, p {t['prob']*100}%, r {round(t['rate']*0.00508)}m/s"]

# dev info
winds = self.weather.winds
sysinfo += [f"DEV Info:"]
s = 'NOT ACTIVE' if not self.weather.surface_wind else 'ACTIVE'
sysinfo += [f"Surface wind layer: {s}"]
sysinfo += [f"Alt: {round(self.weather.alt)} m. (F{round(c.m2ft(self.weather.alt)/100):03d})"]
w = ' '.join([f"{i}) {round(el['alt'].value)}|{round(el['hdg'].value)}/{round(el['speed'].value)}" for i, el in enumerate(winds)])
sysinfo += [f"Wind layers: {w}"]
if self.conf.set_surface_layer:
s = 'NOT ACTIVE' if not self.weather.surface_wind else 'ACTIVE'
sysinfo += [f"Surface wind layer: {s}"]

sysinfo += ['--'] * (self.aboutlines - len(sysinfo))

Expand Down
2 changes: 1 addition & 1 deletion noaweather/conf.py
Expand Up @@ -27,7 +27,7 @@ class Conf:
syspath, dirsep = '', os.sep
printableChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '

__VERSION__ = '2.7.2 beta'
__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.
Expand Down
80 changes: 0 additions & 80 deletions noaweather/gfs.py
Expand Up @@ -26,7 +26,6 @@ class GFS(GribWeatherSource):
"""NOAA GFS weather source"""

base_url = 'https://nomads.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/gfs.'
# base_url = 'https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p50.pl'

download = False
download_wait = 0
Expand All @@ -43,33 +42,6 @@ def get_download_url(cls, datecycle, cycle, forecast):

return url

# @classmethod
# def get_download_url(cls, datecycle, cycle, forecast, variable_list):
# """Returns the GRIB download url add .idx or .grib to the end"""
# filename = 'gfs.t%02dz.pgrb2full.0p50.f0%02d' % (cycle, forecast)
# # url = '%s%s/%02d/atmos/%s' % (cls.base_url, datecycle, cycle, filename)
# url = '%s?file=%s' % (cls.base_url, filename)
#
# # get levels and vars
# levels = []
# vars = []
# for el in variable_list:
# if isinstance(el['levels'], list):
# levels.extend(el['levels'])
# else:
# levels.append(el['levels'])
# if isinstance(el['vars'], list):
# vars.extend(el['vars'])
# else:
# vars.append(el['vars'])
# levels = [f"lev_{el.replace(' ', '_')}=on" for el in set(levels)]
# vars = [f"var_{el.replace(' ', '_')}=on" for el in set(vars)]
#
# url += '&' + '&'.join(levels+vars)
# url += '&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=/gfs.%s/%02d/atmos' % (datecycle, cycle)
#
# return url

@classmethod
def get_cache_filename(cls, datecycle, cycle, forecast):
"""Returns the proper filename for the cache"""
Expand Down Expand Up @@ -194,55 +166,3 @@ def parse_grib_data(self, filepath, lat, lon):
}

return data


def test(file=None):
from .conf import Conf
if not file:
file = 'noaweather/cache/gfs/20211122_gfs.t06z.pgrb2full.0p50.f006'
# file2 = 'noaweather/cache/gfs/gfs.t06z.pgrb2full.0p50.f003'
lat = 44.5 # LIMZ
lon = 7.6 # LIMZ
conf = Conf(False)
gfs = GFS(conf=conf)

args = ['-s',
'-lon',
'%f' % (lon),
'%f' % (lat),
file
]
kwargs = {'stdout': subprocess.PIPE}

# subprocess.Popen([gfs.conf.wgrib2bin] + ['-h'])

# p = subprocess.Popen([gfs.conf.wgrib2bin] + ['-s', '-lon', str(lon), str(lat), file], **kwargs).communicate()
t = 'https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p50.pl?file=gfs.t06z.pgrb2full.0p50.f006&lev_150_mb=on&lev_200_mb=on&lev_300_mb=on&lev_400_mb=on&lev_500_mb=on&lev_600_mb=on&lev_700_mb=on&lev_850_mb=on&lev_high_cloud_bottom_level=on&lev_high_cloud_layer=on&lev_high_cloud_top_level=on&lev_low_cloud_bottom_level=on&lev_low_cloud_layer=on&lev_low_cloud_top_level=on&lev_mean_sea_level=on&lev_middle_cloud_bottom_level=on&lev_middle_cloud_layer=on&lev_middle_cloud_top_level=on&lev_tropopause=on&var_HCDC=on&var_LCDC=on&var_MCDC=on&var_PRES=on&var_PRMSL=on&var_TCDC=on&var_TMP=on&var_UGRD=on&var_VGRD=on&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=%2Fgfs.20211120%2F06%2Fatmos'
p = subprocess.Popen([gfs.conf.wgrib2bin] + args, **kwargs)

it = iter(p.stdout)
data = []
for line in it:
if sys.version_info.major == 2:
r = line[:-1].split(':')
else:
r = line.decode('utf-8')[:-1].split(':')
# Level, variable, value
level, variable, value = [r[4].split(' '), r[3], r[7].split(',')[2].split('=')[1]]

data.append(dict(level=level, variable=variable, value=value))
return data


def test2(file=None):
from .conf import Conf
if not file:
file = 'noaweather/cache/gfs/20211122_gfs.t06z.pgrb2full.0p50.f006'
# lat = -22.8 # Rio
# lon = -43.2 # Rio
lat = 44.5 # LIMZ
lon = 7.6 # LIMZ
conf = Conf(False)
gfs = GFS(conf=conf)

return gfs.parse_grib_data(file, lat, lon)
47 changes: 0 additions & 47 deletions noaweather/weathersource.py
Expand Up @@ -15,7 +15,6 @@
from urllib2 import Request, urlopen, URLError
except ImportError:
from urllib.request import Request, urlopen, URLError
# from urllib.request import urlretrieve
import zlib
import os
import subprocess
Expand Down Expand Up @@ -114,7 +113,6 @@ def run(self, elapsed):
else:
# Trigger new download
url = self.get_download_url(datecycle, cycle, forecast)
# url = self.get_download_url(datecycle, cycle, forecast, self.variable_list)
print('Downloading: %s' % cache_file)
self.download = AsyncTask(GribDownloader.download,
url,
Expand Down Expand Up @@ -430,51 +428,6 @@ def download(cls, url, file_path, binary=False, **kwargs):

return file_path

# @classmethod
# def download_2(cls, url, file_path, binary=False, **kwargs):
# """Download grib for the specified variable_lists
#
# Args:
# url (str): URL to the grib file excluding the extension
# file_path (str): Path to the output file
# binary (bool): Set to True for binary files or files will get corrupted on Windows.
#
# Kwargs:
# cancel_event (threading.Event): Set the flat to cancel the download at any time
# variable_list (list): List of variables dicts ex: [{'level': ['500mb', ], 'vars': 'TMP'}, ]
# decompress (str): Path to the wgrib2 to decompress the file.
#
# Returns:
# str: the path to the final file on success
#
# Raises:
# GribDownloaderError: on fail.
# GribDownloaderCancel: on cancel.
# """
#
# cancel = kwargs.pop('cancel_event', False)
# while True:
# if cancel and cancel.isSet():
# raise GribDownloaderCancel("Download canceled by user.")
# try:
# urlretrieve(url, file_path)
# break
# except URLError as err:
# raise GribDownloaderError('Unable to open url: %s\n\t%s' % (url, str(err)))
#
# wgrib2 = kwargs.pop('decompress', False)
# spinfo = kwargs.pop('spinfo', False)
#
# if wgrib2:
# tmp_file = "%s.tmp" % file_path
# try:
# os.rename(file_path, tmp_file)
# cls.decompress_grib(tmp_file, file_path, wgrib2, spinfo)
# util.remove(tmp_file)
# except OSError as err:
# raise GribDownloaderError('Unable to decompress: %s \n\t%s' % (file_path, str(err)))
# return file_path


class GribDownloaderError(Exception):
"""Raised on a download error"""
Expand Down

0 comments on commit 79238f4

Please sign in to comment.