2015-11-30 16:00:28 +00:00
|
|
|
"""
|
2016-02-23 05:21:49 +00:00
|
|
|
Support for Yr.no weather service.
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2016-01-04 15:26:11 +00:00
|
|
|
For more details about this platform, please refer to the documentation at
|
|
|
|
https://home-assistant.io/components/sensor.yr/
|
2015-11-30 16:00:28 +00:00
|
|
|
"""
|
2016-11-03 02:34:12 +00:00
|
|
|
import asyncio
|
|
|
|
from datetime import timedelta
|
2015-11-30 16:00:28 +00:00
|
|
|
import logging
|
2016-12-21 07:42:23 +00:00
|
|
|
from random import randrange
|
2016-11-03 02:34:12 +00:00
|
|
|
from xml.parsers.expat import ExpatError
|
2016-10-11 07:28:19 +00:00
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
import async_timeout
|
2016-11-11 05:28:22 +00:00
|
|
|
import aiohttp
|
2016-04-10 17:43:05 +00:00
|
|
|
import voluptuous as vol
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2016-04-10 17:43:05 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2016-08-20 22:40:16 +00:00
|
|
|
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
2016-04-12 04:44:39 +00:00
|
|
|
from homeassistant.const import (
|
2016-10-11 07:28:19 +00:00
|
|
|
CONF_LATITUDE, CONF_LONGITUDE, CONF_ELEVATION, CONF_MONITORED_CONDITIONS,
|
|
|
|
ATTR_ATTRIBUTION)
|
2016-11-28 00:26:46 +00:00
|
|
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
2015-11-30 16:00:28 +00:00
|
|
|
from homeassistant.helpers.entity import Entity
|
2016-11-23 03:28:31 +00:00
|
|
|
from homeassistant.helpers.event import (
|
|
|
|
async_track_point_in_utc_time, async_track_utc_time_change)
|
2016-02-19 05:27:50 +00:00
|
|
|
from homeassistant.util import dt as dt_util
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2017-04-29 21:59:38 +00:00
|
|
|
REQUIREMENTS = ['xmltodict==0.11.0']
|
2015-12-01 12:24:32 +00:00
|
|
|
|
2016-08-20 22:40:16 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2016-10-11 07:28:19 +00:00
|
|
|
CONF_ATTRIBUTION = "Weather forecast from yr.no, delivered by the Norwegian " \
|
|
|
|
"Meteorological Institute and the NRK."
|
|
|
|
|
2015-11-30 16:00:28 +00:00
|
|
|
# Sensor types are defined like so:
|
|
|
|
SENSOR_TYPES = {
|
2016-01-18 01:50:20 +00:00
|
|
|
'symbol': ['Symbol', None],
|
2016-10-16 16:07:34 +00:00
|
|
|
'precipitation': ['Precipitation', 'mm'],
|
2015-11-30 16:00:28 +00:00
|
|
|
'temperature': ['Temperature', '°C'],
|
|
|
|
'windSpeed': ['Wind speed', 'm/s'],
|
2016-01-21 21:04:18 +00:00
|
|
|
'windGust': ['Wind gust', 'm/s'],
|
2016-02-01 14:50:17 +00:00
|
|
|
'pressure': ['Pressure', 'hPa'],
|
2015-11-30 16:00:28 +00:00
|
|
|
'windDirection': ['Wind direction', '°'],
|
2015-12-01 12:31:55 +00:00
|
|
|
'humidity': ['Humidity', '%'],
|
2015-11-30 16:00:28 +00:00
|
|
|
'fog': ['Fog', '%'],
|
|
|
|
'cloudiness': ['Cloudiness', '%'],
|
|
|
|
'lowClouds': ['Low clouds', '%'],
|
|
|
|
'mediumClouds': ['Medium clouds', '%'],
|
|
|
|
'highClouds': ['High clouds', '%'],
|
|
|
|
'dewpointTemperature': ['Dewpoint temperature', '°C'],
|
|
|
|
}
|
|
|
|
|
2016-08-20 22:40:16 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
2016-11-03 02:34:12 +00:00
|
|
|
vol.Optional(CONF_MONITORED_CONDITIONS, default=['symbol']): vol.All(
|
|
|
|
cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES.keys())]),
|
2016-04-12 04:44:39 +00:00
|
|
|
vol.Optional(CONF_LATITUDE): cv.latitude,
|
|
|
|
vol.Optional(CONF_LONGITUDE): cv.longitude,
|
2016-04-12 14:54:03 +00:00
|
|
|
vol.Optional(CONF_ELEVATION): vol.Coerce(int),
|
2016-04-10 17:43:05 +00:00
|
|
|
})
|
|
|
|
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2016-11-03 09:09:03 +00:00
|
|
|
@asyncio.coroutine
|
2016-11-03 02:34:12 +00:00
|
|
|
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Set up the Yr.no sensor."""
|
2016-01-28 16:16:02 +00:00
|
|
|
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
|
|
|
|
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
|
2016-06-27 16:02:45 +00:00
|
|
|
elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)
|
2016-01-28 16:16:02 +00:00
|
|
|
|
|
|
|
if None in (latitude, longitude):
|
2015-11-30 16:00:28 +00:00
|
|
|
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
|
|
|
|
return False
|
|
|
|
|
2016-12-01 06:20:21 +00:00
|
|
|
coordinates = {'lat': str(latitude),
|
|
|
|
'lon': str(longitude),
|
|
|
|
'msl': str(elevation)}
|
2015-11-30 16:00:28 +00:00
|
|
|
|
|
|
|
dev = []
|
2016-04-10 17:43:05 +00:00
|
|
|
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
|
2016-11-03 02:34:12 +00:00
|
|
|
dev.append(YrSensor(sensor_type))
|
2017-03-01 04:33:19 +00:00
|
|
|
async_add_devices(dev)
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
weather = YrData(hass, coordinates, dev)
|
2016-12-21 07:42:23 +00:00
|
|
|
# Update weather on the hour, spread seconds
|
2017-05-02 16:18:47 +00:00
|
|
|
async_track_utc_time_change(
|
|
|
|
hass, weather.async_update, minute=randrange(1, 10),
|
|
|
|
second=randrange(0, 59))
|
2016-11-03 02:34:12 +00:00
|
|
|
yield from weather.async_update()
|
2015-11-30 16:00:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
class YrSensor(Entity):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Representation of an Yr.no sensor."""
|
2015-11-30 16:00:28 +00:00
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
def __init__(self, sensor_type):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the sensor."""
|
2015-12-21 09:42:42 +00:00
|
|
|
self.client_name = 'yr'
|
2015-11-30 16:00:28 +00:00
|
|
|
self._name = SENSOR_TYPES[sensor_type][0]
|
|
|
|
self.type = sensor_type
|
|
|
|
self._state = None
|
|
|
|
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the name of the sensor."""
|
2015-12-21 09:42:42 +00:00
|
|
|
return '{} {}'.format(self.client_name, self._name)
|
2015-11-30 16:00:28 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def state(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the state of the device."""
|
2015-11-30 16:00:28 +00:00
|
|
|
return self._state
|
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
@property
|
|
|
|
def should_poll(self): # pylint: disable=no-self-use
|
|
|
|
"""No polling needed."""
|
|
|
|
return False
|
|
|
|
|
2016-02-24 06:41:24 +00:00
|
|
|
@property
|
|
|
|
def entity_picture(self):
|
|
|
|
"""Weather symbol if type is symbol."""
|
|
|
|
if self.type != 'symbol':
|
|
|
|
return None
|
2016-04-24 02:09:39 +00:00
|
|
|
return "//api.met.no/weatherapi/weathericon/1.1/" \
|
2016-02-24 06:41:24 +00:00
|
|
|
"?symbol={0};content_type=image/png".format(self._state)
|
|
|
|
|
2015-11-30 16:00:28 +00:00
|
|
|
@property
|
2016-02-07 06:28:29 +00:00
|
|
|
def device_state_attributes(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the state attributes."""
|
2016-02-24 06:41:24 +00:00
|
|
|
return {
|
2016-10-11 07:28:19 +00:00
|
|
|
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
|
2015-12-27 19:07:25 +00:00
|
|
|
}
|
2015-11-30 16:00:28 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def unit_of_measurement(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the unit of measurement of this entity, if any."""
|
2015-11-30 16:00:28 +00:00
|
|
|
return self._unit_of_measurement
|
|
|
|
|
2015-12-04 14:05:23 +00:00
|
|
|
|
|
|
|
class YrData(object):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Get the latest data and updates the states."""
|
2015-12-04 14:05:23 +00:00
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
def __init__(self, hass, coordinates, devices):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the data object."""
|
2017-01-04 22:20:30 +00:00
|
|
|
self._url = 'https://aa015h6buqvih86i1.api.met.no/'\
|
|
|
|
'weatherapi/locationforecast/1.9/'
|
2016-12-01 06:20:21 +00:00
|
|
|
self._urlparams = coordinates
|
2015-12-27 19:07:25 +00:00
|
|
|
self._nextrun = None
|
2016-11-03 02:34:12 +00:00
|
|
|
self.devices = devices
|
2015-12-27 19:07:25 +00:00
|
|
|
self.data = {}
|
2016-11-03 02:34:12 +00:00
|
|
|
self.hass = hass
|
2015-12-04 14:05:23 +00:00
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
@asyncio.coroutine
|
2016-11-23 03:28:31 +00:00
|
|
|
def async_update(self, *_):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Get the latest data from yr.no."""
|
2017-03-30 07:50:53 +00:00
|
|
|
import xmltodict
|
|
|
|
|
2016-11-03 02:34:12 +00:00
|
|
|
def try_again(err: str):
|
2016-11-23 03:28:31 +00:00
|
|
|
"""Retry in 15 minutes."""
|
2016-11-03 02:34:12 +00:00
|
|
|
_LOGGER.warning('Retrying in 15 minutes: %s', err)
|
2016-11-23 03:28:31 +00:00
|
|
|
self._nextrun = None
|
2016-11-03 02:34:12 +00:00
|
|
|
nxt = dt_util.utcnow() + timedelta(minutes=15)
|
2016-11-23 03:28:31 +00:00
|
|
|
if nxt.minute >= 15:
|
|
|
|
async_track_point_in_utc_time(self.hass, self.async_update,
|
|
|
|
nxt)
|
|
|
|
|
|
|
|
if self._nextrun is None or dt_util.utcnow() >= self._nextrun:
|
|
|
|
try:
|
2016-11-28 00:26:46 +00:00
|
|
|
websession = async_get_clientsession(self.hass)
|
2016-11-23 03:28:31 +00:00
|
|
|
with async_timeout.timeout(10, loop=self.hass.loop):
|
2017-05-02 16:18:47 +00:00
|
|
|
resp = yield from websession.get(
|
|
|
|
self._url, params=self._urlparams)
|
2016-11-23 03:28:31 +00:00
|
|
|
if resp.status != 200:
|
2016-12-01 06:20:21 +00:00
|
|
|
try_again('{} returned {}'.format(resp.url, resp.status))
|
2016-11-23 03:28:31 +00:00
|
|
|
return
|
|
|
|
text = yield from resp.text()
|
2016-11-30 21:05:58 +00:00
|
|
|
|
2017-03-30 07:50:53 +00:00
|
|
|
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
|
2016-11-23 03:28:31 +00:00
|
|
|
try_again(err)
|
|
|
|
return
|
2016-11-03 02:34:12 +00:00
|
|
|
|
2016-11-23 03:28:31 +00:00
|
|
|
try:
|
|
|
|
self.data = xmltodict.parse(text)['weatherdata']
|
|
|
|
model = self.data['meta']['model']
|
|
|
|
if '@nextrun' not in model:
|
|
|
|
model = model[0]
|
|
|
|
self._nextrun = dt_util.parse_datetime(model['@nextrun'])
|
|
|
|
except (ExpatError, IndexError) as err:
|
|
|
|
try_again(err)
|
2016-11-03 02:34:12 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
now = dt_util.utcnow()
|
|
|
|
|
|
|
|
tasks = []
|
|
|
|
# Update all devices
|
|
|
|
for dev in self.devices:
|
|
|
|
# Find sensor
|
|
|
|
for time_entry in self.data['product']['time']:
|
|
|
|
valid_from = dt_util.parse_datetime(time_entry['@from'])
|
|
|
|
valid_to = dt_util.parse_datetime(time_entry['@to'])
|
2017-01-20 07:58:15 +00:00
|
|
|
new_state = None
|
2016-11-03 02:34:12 +00:00
|
|
|
|
|
|
|
loc_data = time_entry['location']
|
|
|
|
|
|
|
|
if dev.type not in loc_data or now >= valid_to:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if dev.type == 'precipitation' and valid_from < now:
|
|
|
|
new_state = loc_data[dev.type]['@value']
|
|
|
|
break
|
|
|
|
elif dev.type == 'symbol' and valid_from < now:
|
|
|
|
new_state = loc_data[dev.type]['@number']
|
|
|
|
break
|
|
|
|
elif dev.type in ('temperature', 'pressure', 'humidity',
|
|
|
|
'dewpointTemperature'):
|
|
|
|
new_state = loc_data[dev.type]['@value']
|
|
|
|
break
|
|
|
|
elif dev.type in ('windSpeed', 'windGust'):
|
|
|
|
new_state = loc_data[dev.type]['@mps']
|
|
|
|
break
|
|
|
|
elif dev.type == 'windDirection':
|
|
|
|
new_state = float(loc_data[dev.type]['@deg'])
|
|
|
|
break
|
|
|
|
elif dev.type in ('fog', 'cloudiness', 'lowClouds',
|
|
|
|
'mediumClouds', 'highClouds'):
|
|
|
|
new_state = loc_data[dev.type]['@percent']
|
|
|
|
break
|
|
|
|
|
|
|
|
# pylint: disable=protected-access
|
|
|
|
if new_state != dev._state:
|
|
|
|
dev._state = new_state
|
|
|
|
tasks.append(dev.async_update_ha_state())
|
|
|
|
|
2016-11-06 17:26:40 +00:00
|
|
|
if tasks:
|
|
|
|
yield from asyncio.wait(tasks, loop=self.hass.loop)
|