Convert MetOffice to use UI for configuration (#34900)
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
parent
9a867cbb75
commit
c96458c7e4
19 changed files with 2602 additions and 227 deletions
|
@ -1,27 +1,31 @@
|
|||
"""Support for UK Met Office weather service."""
|
||||
from datetime import timedelta
|
||||
|
||||
import logging
|
||||
|
||||
import datapoint as dp
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (
|
||||
ATTR_ATTRIBUTION,
|
||||
CONF_API_KEY,
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_MONITORED_CONDITIONS,
|
||||
CONF_NAME,
|
||||
DEVICE_CLASS_HUMIDITY,
|
||||
DEVICE_CLASS_TEMPERATURE,
|
||||
LENGTH_KILOMETERS,
|
||||
SPEED_MILES_PER_HOUR,
|
||||
TEMP_CELSIUS,
|
||||
UNIT_PERCENTAGE,
|
||||
UV_INDEX,
|
||||
)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
|
||||
|
||||
from .const import (
|
||||
ATTRIBUTION,
|
||||
CONDITION_CLASSES,
|
||||
DOMAIN,
|
||||
METOFFICE_COORDINATOR,
|
||||
METOFFICE_DATA,
|
||||
METOFFICE_NAME,
|
||||
VISIBILITY_CLASSES,
|
||||
VISIBILITY_DISTANCE_CLASSES,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
@ -30,175 +34,190 @@ ATTR_SENSOR_ID = "sensor_id"
|
|||
ATTR_SITE_ID = "site_id"
|
||||
ATTR_SITE_NAME = "site_name"
|
||||
|
||||
ATTRIBUTION = "Data provided by the Met Office"
|
||||
|
||||
CONDITION_CLASSES = {
|
||||
"cloudy": ["7", "8"],
|
||||
"fog": ["5", "6"],
|
||||
"hail": ["19", "20", "21"],
|
||||
"lightning": ["30"],
|
||||
"lightning-rainy": ["28", "29"],
|
||||
"partlycloudy": ["2", "3"],
|
||||
"pouring": ["13", "14", "15"],
|
||||
"rainy": ["9", "10", "11", "12"],
|
||||
"snowy": ["22", "23", "24", "25", "26", "27"],
|
||||
"snowy-rainy": ["16", "17", "18"],
|
||||
"sunny": ["0", "1"],
|
||||
"windy": [],
|
||||
"windy-variant": [],
|
||||
"exceptional": [],
|
||||
}
|
||||
|
||||
DEFAULT_NAME = "Met Office"
|
||||
|
||||
VISIBILITY_CLASSES = {
|
||||
"VP": "<1",
|
||||
"PO": "1-4",
|
||||
"MO": "4-10",
|
||||
"GO": "10-20",
|
||||
"VG": "20-40",
|
||||
"EX": ">40",
|
||||
}
|
||||
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=35)
|
||||
|
||||
# Sensor types are defined like: Name, units
|
||||
# Sensor types are defined as:
|
||||
# variable -> [0]title, [1]device_class, [2]units, [3]icon, [4]enabled_by_default
|
||||
SENSOR_TYPES = {
|
||||
"name": ["Station Name", None],
|
||||
"weather": ["Weather", None],
|
||||
"temperature": ["Temperature", TEMP_CELSIUS],
|
||||
"feels_like_temperature": ["Feels Like Temperature", TEMP_CELSIUS],
|
||||
"wind_speed": ["Wind Speed", SPEED_MILES_PER_HOUR],
|
||||
"wind_direction": ["Wind Direction", None],
|
||||
"wind_gust": ["Wind Gust", SPEED_MILES_PER_HOUR],
|
||||
"visibility": ["Visibility", None],
|
||||
"visibility_distance": ["Visibility Distance", LENGTH_KILOMETERS],
|
||||
"uv": ["UV", UV_INDEX],
|
||||
"precipitation": ["Probability of Precipitation", UNIT_PERCENTAGE],
|
||||
"humidity": ["Humidity", UNIT_PERCENTAGE],
|
||||
"name": ["Station Name", None, None, "mdi:label-outline", False],
|
||||
"weather": [
|
||||
"Weather",
|
||||
None,
|
||||
None,
|
||||
"mdi:weather-sunny", # but will adapt to current conditions
|
||||
True,
|
||||
],
|
||||
"temperature": ["Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None, True],
|
||||
"feels_like_temperature": [
|
||||
"Feels Like Temperature",
|
||||
DEVICE_CLASS_TEMPERATURE,
|
||||
TEMP_CELSIUS,
|
||||
None,
|
||||
False,
|
||||
],
|
||||
"wind_speed": [
|
||||
"Wind Speed",
|
||||
None,
|
||||
SPEED_MILES_PER_HOUR,
|
||||
"mdi:weather-windy",
|
||||
True,
|
||||
],
|
||||
"wind_direction": ["Wind Direction", None, None, "mdi:compass-outline", False],
|
||||
"wind_gust": ["Wind Gust", None, SPEED_MILES_PER_HOUR, "mdi:weather-windy", False],
|
||||
"visibility": ["Visibility", None, None, "mdi:eye", False],
|
||||
"visibility_distance": [
|
||||
"Visibility Distance",
|
||||
None,
|
||||
LENGTH_KILOMETERS,
|
||||
"mdi:eye",
|
||||
False,
|
||||
],
|
||||
"uv": ["UV Index", None, UV_INDEX, "mdi:weather-sunny-alert", True],
|
||||
"precipitation": [
|
||||
"Probability of Precipitation",
|
||||
None,
|
||||
UNIT_PERCENTAGE,
|
||||
"mdi:weather-rainy",
|
||||
True,
|
||||
],
|
||||
"humidity": ["Humidity", DEVICE_CLASS_HUMIDITY, UNIT_PERCENTAGE, None, False],
|
||||
}
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(
|
||||
cv.ensure_list, [vol.In(SENSOR_TYPES)]
|
||||
),
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Inclusive(
|
||||
CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together"
|
||||
): cv.latitude,
|
||||
vol.Inclusive(
|
||||
CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together"
|
||||
): cv.longitude,
|
||||
}
|
||||
)
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistantType, entry: ConfigType, async_add_entities
|
||||
) -> None:
|
||||
"""Set up the Met Office weather sensor platform."""
|
||||
hass_data = hass.data[DOMAIN][entry.entry_id]
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the Met Office sensor platform."""
|
||||
api_key = config.get(CONF_API_KEY)
|
||||
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
|
||||
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
|
||||
name = config.get(CONF_NAME)
|
||||
|
||||
datapoint = dp.connection(api_key=api_key)
|
||||
|
||||
if None in (latitude, longitude):
|
||||
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
|
||||
return
|
||||
|
||||
try:
|
||||
site = datapoint.get_nearest_site(latitude=latitude, longitude=longitude)
|
||||
except dp.exceptions.APIException as err:
|
||||
_LOGGER.error("Received error from Met Office Datapoint: %s", err)
|
||||
return
|
||||
|
||||
if not site:
|
||||
_LOGGER.error("Unable to get nearest Met Office forecast site")
|
||||
return
|
||||
|
||||
data = MetOfficeCurrentData(hass, datapoint, site)
|
||||
data.update()
|
||||
if data.data is None:
|
||||
return
|
||||
|
||||
sensors = []
|
||||
for variable in config[CONF_MONITORED_CONDITIONS]:
|
||||
sensors.append(MetOfficeCurrentSensor(site, data, variable, name))
|
||||
|
||||
add_entities(sensors, True)
|
||||
async_add_entities(
|
||||
[
|
||||
MetOfficeCurrentSensor(entry.data, hass_data, sensor_type)
|
||||
for sensor_type in SENSOR_TYPES
|
||||
],
|
||||
False,
|
||||
)
|
||||
|
||||
|
||||
class MetOfficeCurrentSensor(Entity):
|
||||
"""Implementation of a Met Office current sensor."""
|
||||
"""Implementation of a Met Office current weather condition sensor."""
|
||||
|
||||
def __init__(self, site, data, condition, name):
|
||||
def __init__(self, entry_data, hass_data, sensor_type):
|
||||
"""Initialize the sensor."""
|
||||
self._condition = condition
|
||||
self.data = data
|
||||
self._name = name
|
||||
self.site = site
|
||||
self._data = hass_data[METOFFICE_DATA]
|
||||
self._coordinator = hass_data[METOFFICE_COORDINATOR]
|
||||
|
||||
self._type = sensor_type
|
||||
self._name = f"{hass_data[METOFFICE_NAME]} {SENSOR_TYPES[self._type][0]}"
|
||||
self._unique_id = f"{SENSOR_TYPES[self._type][0]}_{self._data.latitude}_{self._data.longitude}"
|
||||
|
||||
self.metoffice_site_id = None
|
||||
self.metoffice_site_name = None
|
||||
self.metoffice_now = None
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return f"{self._name} {SENSOR_TYPES[self._condition][0]}"
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique of the sensor."""
|
||||
return self._unique_id
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
if self._condition == "visibility_distance" and hasattr(
|
||||
self.data.data, "visibility"
|
||||
value = None
|
||||
|
||||
if self._type == "visibility_distance" and hasattr(
|
||||
self.metoffice_now, "visibility"
|
||||
):
|
||||
return VISIBILITY_CLASSES.get(self.data.data.visibility.value)
|
||||
if hasattr(self.data.data, self._condition):
|
||||
variable = getattr(self.data.data, self._condition)
|
||||
if self._condition == "weather":
|
||||
return [
|
||||
k
|
||||
for k, v in CONDITION_CLASSES.items()
|
||||
if self.data.data.weather.value in v
|
||||
][0]
|
||||
return variable.value
|
||||
return None
|
||||
value = VISIBILITY_DISTANCE_CLASSES.get(self.metoffice_now.visibility.value)
|
||||
|
||||
if self._type == "visibility" and hasattr(self.metoffice_now, "visibility"):
|
||||
value = VISIBILITY_CLASSES.get(self.metoffice_now.visibility.value)
|
||||
|
||||
elif self._type == "weather" and hasattr(self.metoffice_now, self._type):
|
||||
value = [
|
||||
k
|
||||
for k, v in CONDITION_CLASSES.items()
|
||||
if self.metoffice_now.weather.value in v
|
||||
][0]
|
||||
|
||||
elif hasattr(self.metoffice_now, self._type):
|
||||
value = getattr(self.metoffice_now, self._type)
|
||||
|
||||
if not isinstance(value, int):
|
||||
value = value.value
|
||||
|
||||
return value
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return SENSOR_TYPES[self._condition][1]
|
||||
return SENSOR_TYPES[self._type][2]
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon for the entity card."""
|
||||
value = SENSOR_TYPES[self._type][3]
|
||||
if self._type == "weather":
|
||||
value = self.state
|
||||
if value is None:
|
||||
value = "sunny"
|
||||
elif value == "partlycloudy":
|
||||
value = "partly-cloudy"
|
||||
value = f"mdi:weather-{value}"
|
||||
|
||||
return value
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the device class of the sensor."""
|
||||
return SENSOR_TYPES[self._type][1]
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes of the device."""
|
||||
attr = {}
|
||||
attr[ATTR_ATTRIBUTION] = ATTRIBUTION
|
||||
attr[ATTR_LAST_UPDATE] = self.data.data.date
|
||||
attr[ATTR_SENSOR_ID] = self._condition
|
||||
attr[ATTR_SITE_ID] = self.site.id
|
||||
attr[ATTR_SITE_NAME] = self.site.name
|
||||
return attr
|
||||
return {
|
||||
ATTR_ATTRIBUTION: ATTRIBUTION,
|
||||
ATTR_LAST_UPDATE: self.metoffice_now.date if self.metoffice_now else None,
|
||||
ATTR_SENSOR_ID: self._type,
|
||||
ATTR_SITE_ID: self.metoffice_site_id if self.metoffice_site_id else None,
|
||||
ATTR_SITE_NAME: self.metoffice_site_name
|
||||
if self.metoffice_site_name
|
||||
else None,
|
||||
}
|
||||
|
||||
def update(self):
|
||||
"""Update current conditions."""
|
||||
self.data.update()
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Set up a listener and load data."""
|
||||
self.async_on_remove(
|
||||
self._coordinator.async_add_listener(self._update_callback)
|
||||
)
|
||||
self._update_callback()
|
||||
|
||||
async def async_update(self):
|
||||
"""Schedule a custom update via the common entity update service."""
|
||||
await self._coordinator.async_request_refresh()
|
||||
|
||||
class MetOfficeCurrentData:
|
||||
"""Get data from Datapoint."""
|
||||
@callback
|
||||
def _update_callback(self) -> None:
|
||||
"""Load data from integration."""
|
||||
self.metoffice_site_id = self._data.site_id
|
||||
self.metoffice_site_name = self._data.site_name
|
||||
self.metoffice_now = self._data.now
|
||||
self.async_write_ha_state()
|
||||
|
||||
def __init__(self, hass, datapoint, site):
|
||||
"""Initialize the data object."""
|
||||
self._datapoint = datapoint
|
||||
self._site = site
|
||||
self.data = None
|
||||
@property
|
||||
def should_poll(self) -> bool:
|
||||
"""Entities do not individually poll."""
|
||||
return False
|
||||
|
||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||
def update(self):
|
||||
"""Get the latest data from Datapoint."""
|
||||
try:
|
||||
forecast = self._datapoint.get_forecast_for_site(self._site.id, "3hourly")
|
||||
self.data = forecast.now()
|
||||
except (ValueError, dp.exceptions.APIException) as err:
|
||||
_LOGGER.error("Check Met Office %s", err.args)
|
||||
self.data = None
|
||||
@property
|
||||
def entity_registry_enabled_default(self) -> bool:
|
||||
"""Return if the entity should be enabled when first added to the entity registry."""
|
||||
return SENSOR_TYPES[self._type][4]
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
"""Return if state is available."""
|
||||
return self.metoffice_site_id is not None and self.metoffice_now is not None
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue