Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -15,63 +15,68 @@ import voluptuous as vol
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (
|
||||
CONF_MONITORED_CONDITIONS, TEMP_CELSIUS, CONF_NAME, ATTR_ATTRIBUTION,
|
||||
CONF_LATITUDE, CONF_LONGITUDE)
|
||||
CONF_MONITORED_CONDITIONS,
|
||||
TEMP_CELSIUS,
|
||||
CONF_NAME,
|
||||
ATTR_ATTRIBUTION,
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
)
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
|
||||
_RESOURCE = 'http://www.bom.gov.au/fwo/{}/{}.{}.json'
|
||||
_RESOURCE = "http://www.bom.gov.au/fwo/{}/{}.{}.json"
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_LAST_UPDATE = 'last_update'
|
||||
ATTR_SENSOR_ID = 'sensor_id'
|
||||
ATTR_STATION_ID = 'station_id'
|
||||
ATTR_STATION_NAME = 'station_name'
|
||||
ATTR_ZONE_ID = 'zone_id'
|
||||
ATTR_LAST_UPDATE = "last_update"
|
||||
ATTR_SENSOR_ID = "sensor_id"
|
||||
ATTR_STATION_ID = "station_id"
|
||||
ATTR_STATION_NAME = "station_name"
|
||||
ATTR_ZONE_ID = "zone_id"
|
||||
|
||||
ATTRIBUTION = "Data provided by the Australian Bureau of Meteorology"
|
||||
|
||||
CONF_STATION = 'station'
|
||||
CONF_ZONE_ID = 'zone_id'
|
||||
CONF_WMO_ID = 'wmo_id'
|
||||
CONF_STATION = "station"
|
||||
CONF_ZONE_ID = "zone_id"
|
||||
CONF_WMO_ID = "wmo_id"
|
||||
|
||||
MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=60)
|
||||
|
||||
SENSOR_TYPES = {
|
||||
'wmo': ['wmo', None],
|
||||
'name': ['Station Name', None],
|
||||
'history_product': ['Zone', None],
|
||||
'local_date_time': ['Local Time', None],
|
||||
'local_date_time_full': ['Local Time Full', None],
|
||||
'aifstime_utc': ['UTC Time Full', None],
|
||||
'lat': ['Lat', None],
|
||||
'lon': ['Long', None],
|
||||
'apparent_t': ['Feels Like C', TEMP_CELSIUS],
|
||||
'cloud': ['Cloud', None],
|
||||
'cloud_base_m': ['Cloud Base', None],
|
||||
'cloud_oktas': ['Cloud Oktas', None],
|
||||
'cloud_type_id': ['Cloud Type ID', None],
|
||||
'cloud_type': ['Cloud Type', None],
|
||||
'delta_t': ['Delta Temp C', TEMP_CELSIUS],
|
||||
'gust_kmh': ['Wind Gust kmh', 'km/h'],
|
||||
'gust_kt': ['Wind Gust kt', 'kt'],
|
||||
'air_temp': ['Air Temp C', TEMP_CELSIUS],
|
||||
'dewpt': ['Dew Point C', TEMP_CELSIUS],
|
||||
'press': ['Pressure mb', 'mbar'],
|
||||
'press_qnh': ['Pressure qnh', 'qnh'],
|
||||
'press_msl': ['Pressure msl', 'msl'],
|
||||
'press_tend': ['Pressure Tend', None],
|
||||
'rain_trace': ['Rain Today', 'mm'],
|
||||
'rel_hum': ['Relative Humidity', '%'],
|
||||
'sea_state': ['Sea State', None],
|
||||
'swell_dir_worded': ['Swell Direction', None],
|
||||
'swell_height': ['Swell Height', 'm'],
|
||||
'swell_period': ['Swell Period', None],
|
||||
'vis_km': ['Visability km', 'km'],
|
||||
'weather': ['Weather', None],
|
||||
'wind_dir': ['Wind Direction', None],
|
||||
'wind_spd_kmh': ['Wind Speed kmh', 'km/h'],
|
||||
'wind_spd_kt': ['Wind Speed kt', 'kt']
|
||||
"wmo": ["wmo", None],
|
||||
"name": ["Station Name", None],
|
||||
"history_product": ["Zone", None],
|
||||
"local_date_time": ["Local Time", None],
|
||||
"local_date_time_full": ["Local Time Full", None],
|
||||
"aifstime_utc": ["UTC Time Full", None],
|
||||
"lat": ["Lat", None],
|
||||
"lon": ["Long", None],
|
||||
"apparent_t": ["Feels Like C", TEMP_CELSIUS],
|
||||
"cloud": ["Cloud", None],
|
||||
"cloud_base_m": ["Cloud Base", None],
|
||||
"cloud_oktas": ["Cloud Oktas", None],
|
||||
"cloud_type_id": ["Cloud Type ID", None],
|
||||
"cloud_type": ["Cloud Type", None],
|
||||
"delta_t": ["Delta Temp C", TEMP_CELSIUS],
|
||||
"gust_kmh": ["Wind Gust kmh", "km/h"],
|
||||
"gust_kt": ["Wind Gust kt", "kt"],
|
||||
"air_temp": ["Air Temp C", TEMP_CELSIUS],
|
||||
"dewpt": ["Dew Point C", TEMP_CELSIUS],
|
||||
"press": ["Pressure mb", "mbar"],
|
||||
"press_qnh": ["Pressure qnh", "qnh"],
|
||||
"press_msl": ["Pressure msl", "msl"],
|
||||
"press_tend": ["Pressure Tend", None],
|
||||
"rain_trace": ["Rain Today", "mm"],
|
||||
"rel_hum": ["Relative Humidity", "%"],
|
||||
"sea_state": ["Sea State", None],
|
||||
"swell_dir_worded": ["Swell Direction", None],
|
||||
"swell_height": ["Swell Height", "m"],
|
||||
"swell_period": ["Swell Period", None],
|
||||
"vis_km": ["Visability km", "km"],
|
||||
"weather": ["Weather", None],
|
||||
"wind_dir": ["Wind Direction", None],
|
||||
"wind_spd_kmh": ["Wind Speed kmh", "km/h"],
|
||||
"wind_spd_kt": ["Wind Speed kt", "kt"],
|
||||
}
|
||||
|
||||
|
||||
@@ -79,20 +84,23 @@ def validate_station(station):
|
||||
"""Check that the station ID is well-formed."""
|
||||
if station is None:
|
||||
return
|
||||
station = station.replace('.shtml', '')
|
||||
if not re.fullmatch(r'ID[A-Z]\d\d\d\d\d\.\d\d\d\d\d', station):
|
||||
raise vol.error.Invalid('Malformed station ID')
|
||||
station = station.replace(".shtml", "")
|
||||
if not re.fullmatch(r"ID[A-Z]\d\d\d\d\d\.\d\d\d\d\d", station):
|
||||
raise vol.error.Invalid("Malformed station ID")
|
||||
return station
|
||||
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Inclusive(CONF_ZONE_ID, 'Deprecated partial station ID'): cv.string,
|
||||
vol.Inclusive(CONF_WMO_ID, 'Deprecated partial station ID'): cv.string,
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_STATION): validate_station,
|
||||
vol.Required(CONF_MONITORED_CONDITIONS, default=[]):
|
||||
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
|
||||
})
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Inclusive(CONF_ZONE_ID, "Deprecated partial station ID"): cv.string,
|
||||
vol.Inclusive(CONF_WMO_ID, "Deprecated partial station ID"): cv.string,
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_STATION): validate_station,
|
||||
vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(
|
||||
cv.ensure_list, [vol.In(SENSOR_TYPES)]
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
@@ -104,13 +112,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
if zone_id and wmo_id:
|
||||
_LOGGER.warning(
|
||||
"Using config %s, not %s and %s for BOM sensor",
|
||||
CONF_STATION, CONF_ZONE_ID, CONF_WMO_ID)
|
||||
CONF_STATION,
|
||||
CONF_ZONE_ID,
|
||||
CONF_WMO_ID,
|
||||
)
|
||||
elif zone_id and wmo_id:
|
||||
station = '{}.{}'.format(zone_id, wmo_id)
|
||||
station = "{}.{}".format(zone_id, wmo_id)
|
||||
else:
|
||||
station = closest_station(
|
||||
config.get(CONF_LATITUDE), config.get(CONF_LONGITUDE),
|
||||
hass.config.config_dir)
|
||||
config.get(CONF_LATITUDE),
|
||||
config.get(CONF_LONGITUDE),
|
||||
hass.config.config_dir,
|
||||
)
|
||||
if station is None:
|
||||
_LOGGER.error("Could not get BOM weather station from lat/lon")
|
||||
return
|
||||
@@ -123,8 +136,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
_LOGGER.error("Received error from BOM Current: %s", err)
|
||||
return
|
||||
|
||||
add_entities([BOMCurrentSensor(bom_data, variable, config.get(CONF_NAME))
|
||||
for variable in config[CONF_MONITORED_CONDITIONS]])
|
||||
add_entities(
|
||||
[
|
||||
BOMCurrentSensor(bom_data, variable, config.get(CONF_NAME))
|
||||
for variable in config[CONF_MONITORED_CONDITIONS]
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class BOMCurrentSensor(Entity):
|
||||
@@ -140,10 +157,9 @@ class BOMCurrentSensor(Entity):
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
if self.stationname is None:
|
||||
return 'BOM {}'.format(SENSOR_TYPES[self._condition][0])
|
||||
return "BOM {}".format(SENSOR_TYPES[self._condition][0])
|
||||
|
||||
return 'BOM {} {}'.format(
|
||||
self.stationname, SENSOR_TYPES[self._condition][0])
|
||||
return "BOM {} {}".format(self.stationname, SENSOR_TYPES[self._condition][0])
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -157,9 +173,9 @@ class BOMCurrentSensor(Entity):
|
||||
ATTR_ATTRIBUTION: ATTRIBUTION,
|
||||
ATTR_LAST_UPDATE: self.bom_data.last_updated,
|
||||
ATTR_SENSOR_ID: self._condition,
|
||||
ATTR_STATION_ID: self.bom_data.latest_data['wmo'],
|
||||
ATTR_STATION_NAME: self.bom_data.latest_data['name'],
|
||||
ATTR_ZONE_ID: self.bom_data.latest_data['history_product'],
|
||||
ATTR_STATION_ID: self.bom_data.latest_data["wmo"],
|
||||
ATTR_STATION_NAME: self.bom_data.latest_data["name"],
|
||||
ATTR_ZONE_ID: self.bom_data.latest_data["history_product"],
|
||||
}
|
||||
|
||||
return attr
|
||||
@@ -179,7 +195,7 @@ class BOMCurrentData:
|
||||
|
||||
def __init__(self, station_id):
|
||||
"""Initialize the data object."""
|
||||
self._zone_id, self._wmo_id = station_id.split('.')
|
||||
self._zone_id, self._wmo_id = station_id.split(".")
|
||||
self._data = None
|
||||
self.last_updated = None
|
||||
|
||||
@@ -208,7 +224,7 @@ class BOMCurrentData:
|
||||
through the entire BOM provided dataset.
|
||||
"""
|
||||
condition_readings = (entry[condition] for entry in self._data)
|
||||
return next((x for x in condition_readings if x != '-'), None)
|
||||
return next((x for x in condition_readings if x != "-"), None)
|
||||
|
||||
def should_update(self):
|
||||
"""Determine whether an update should occur.
|
||||
@@ -236,17 +252,20 @@ class BOMCurrentData:
|
||||
"BOM was updated %s minutes ago, skipping update as"
|
||||
" < 35 minutes, Now: %s, LastUpdate: %s",
|
||||
(datetime.datetime.now() - self.last_updated),
|
||||
datetime.datetime.now(), self.last_updated)
|
||||
datetime.datetime.now(),
|
||||
self.last_updated,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
result = requests.get(self._build_url(), timeout=10).json()
|
||||
self._data = result['observations']['data']
|
||||
self._data = result["observations"]["data"]
|
||||
|
||||
# set lastupdate using self._data[0] as the first element in the
|
||||
# array is the latest date in the json
|
||||
self.last_updated = datetime.datetime.strptime(
|
||||
str(self._data[0]['local_date_time_full']), '%Y%m%d%H%M%S')
|
||||
str(self._data[0]["local_date_time_full"]), "%Y%m%d%H%M%S"
|
||||
)
|
||||
return
|
||||
|
||||
except ValueError as err:
|
||||
@@ -263,33 +282,34 @@ def _get_bom_stations():
|
||||
"""
|
||||
latlon = {}
|
||||
with io.BytesIO() as file_obj:
|
||||
with ftplib.FTP('ftp.bom.gov.au') as ftp:
|
||||
with ftplib.FTP("ftp.bom.gov.au") as ftp:
|
||||
ftp.login()
|
||||
ftp.cwd('anon2/home/ncc/metadata/sitelists')
|
||||
ftp.retrbinary('RETR stations.zip', file_obj.write)
|
||||
ftp.cwd("anon2/home/ncc/metadata/sitelists")
|
||||
ftp.retrbinary("RETR stations.zip", file_obj.write)
|
||||
file_obj.seek(0)
|
||||
with zipfile.ZipFile(file_obj) as zipped:
|
||||
with zipped.open('stations.txt') as station_txt:
|
||||
with zipped.open("stations.txt") as station_txt:
|
||||
for _ in range(4):
|
||||
station_txt.readline() # skip header
|
||||
while True:
|
||||
line = station_txt.readline().decode().strip()
|
||||
if len(line) < 120:
|
||||
break # end while loop, ignoring any footer text
|
||||
wmo, lat, lon = (line[a:b].strip() for a, b in
|
||||
[(128, 134), (70, 78), (79, 88)])
|
||||
if wmo != '..':
|
||||
wmo, lat, lon = (
|
||||
line[a:b].strip() for a, b in [(128, 134), (70, 78), (79, 88)]
|
||||
)
|
||||
if wmo != "..":
|
||||
latlon[wmo] = (float(lat), float(lon))
|
||||
zones = {}
|
||||
pattern = (r'<a href="/products/(?P<zone>ID[A-Z]\d\d\d\d\d)/'
|
||||
r'(?P=zone)\.(?P<wmo>\d\d\d\d\d).shtml">')
|
||||
for state in ('nsw', 'vic', 'qld', 'wa', 'tas', 'nt'):
|
||||
url = 'http://www.bom.gov.au/{0}/observations/{0}all.shtml'.format(
|
||||
state)
|
||||
pattern = (
|
||||
r'<a href="/products/(?P<zone>ID[A-Z]\d\d\d\d\d)/'
|
||||
r'(?P=zone)\.(?P<wmo>\d\d\d\d\d).shtml">'
|
||||
)
|
||||
for state in ("nsw", "vic", "qld", "wa", "tas", "nt"):
|
||||
url = "http://www.bom.gov.au/{0}/observations/{0}all.shtml".format(state)
|
||||
for zone_id, wmo_id in re.findall(pattern, requests.get(url).text):
|
||||
zones[wmo_id] = zone_id
|
||||
return {'{}.{}'.format(zones[k], k): latlon[k]
|
||||
for k in set(latlon) & set(zones)}
|
||||
return {"{}.{}".format(zones[k], k): latlon[k] for k in set(latlon) & set(zones)}
|
||||
|
||||
|
||||
def bom_stations(cache_dir):
|
||||
@@ -298,13 +318,13 @@ def bom_stations(cache_dir):
|
||||
Results from internet requests are cached as compressed JSON, making
|
||||
subsequent calls very much faster.
|
||||
"""
|
||||
cache_file = os.path.join(cache_dir, '.bom-stations.json.gz')
|
||||
cache_file = os.path.join(cache_dir, ".bom-stations.json.gz")
|
||||
if not os.path.isfile(cache_file):
|
||||
stations = _get_bom_stations()
|
||||
with gzip.open(cache_file, 'wt') as cache:
|
||||
with gzip.open(cache_file, "wt") as cache:
|
||||
json.dump(stations, cache, sort_keys=True)
|
||||
return stations
|
||||
with gzip.open(cache_file, 'rt') as cache:
|
||||
with gzip.open(cache_file, "rt") as cache:
|
||||
return {k: tuple(v) for k, v in json.load(cache).items()}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user