core/homeassistant/components/sensor/yr.py

206 lines
6.6 KiB
Python
Raw Normal View History

"""
2016-02-23 05:21:49 +00:00
Support for Yr.no weather service.
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/
"""
import logging
import requests
2016-04-10 17:43:05 +00:00
import voluptuous as vol
2016-04-10 17:43:05 +00:00
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_PLATFORM, CONF_LATITUDE, CONF_LONGITUDE, CONF_ELEVATION,
CONF_MONITORED_CONDITIONS
)
from homeassistant.helpers.entity import Entity
2016-02-19 05:27:50 +00:00
from homeassistant.util import dt as dt_util
from homeassistant.util import location
_LOGGER = logging.getLogger(__name__)
2015-12-01 11:57:08 +00:00
2015-12-27 19:07:25 +00:00
REQUIREMENTS = ['xmltodict']
2015-12-01 12:24:32 +00:00
# Sensor types are defined like so:
SENSOR_TYPES = {
2016-01-18 01:50:20 +00:00
'symbol': ['Symbol', None],
2015-12-01 12:31:55 +00:00
'precipitation': ['Condition', 'mm'],
'temperature': ['Temperature', '°C'],
'windSpeed': ['Wind speed', 'm/s'],
'windGust': ['Wind gust', 'm/s'],
2016-02-01 14:50:17 +00:00
'pressure': ['Pressure', 'hPa'],
'windDirection': ['Wind direction', '°'],
2015-12-01 12:31:55 +00:00
'humidity': ['Humidity', '%'],
'fog': ['Fog', '%'],
'cloudiness': ['Cloudiness', '%'],
'lowClouds': ['Low clouds', '%'],
'mediumClouds': ['Medium clouds', '%'],
'highClouds': ['High clouds', '%'],
'dewpointTemperature': ['Dewpoint temperature', '°C'],
}
2016-04-10 17:43:05 +00:00
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): 'yr',
2016-04-10 17:43:05 +00:00
vol.Optional(CONF_MONITORED_CONDITIONS, default=[]):
[vol.In(SENSOR_TYPES.keys())],
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
})
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-03-08 15:46:34 +00:00
"""Setup the Yr.no sensor."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
elevation = config.get(CONF_ELEVATION)
if None in (latitude, longitude):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
return False
2015-12-27 19:07:25 +00:00
if elevation is None:
elevation = location.elevation(latitude,
longitude)
coordinates = dict(lat=latitude,
lon=longitude,
msl=elevation)
2015-12-04 14:05:23 +00:00
weather = YrData(coordinates)
dev = []
2016-04-10 17:43:05 +00:00
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
dev.append(YrSensor(sensor_type, weather))
2015-12-02 12:04:23 +00:00
# add symbol as default sensor
if len(dev) == 0:
2015-12-04 14:05:23 +00:00
dev.append(YrSensor("symbol", weather))
add_devices(dev)
# pylint: disable=too-many-instance-attributes
class YrSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Representation of an Yr.no sensor."""
2015-12-04 14:05:23 +00:00
def __init__(self, sensor_type, weather):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
2015-12-21 09:42:42 +00:00
self.client_name = 'yr'
self._name = SENSOR_TYPES[sensor_type][0]
self.type = sensor_type
self._state = None
2015-12-04 14:05:23 +00:00
self._weather = weather
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
2015-12-27 19:07:25 +00:00
self._update = None
self.update()
@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)
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the device."""
return self._state
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
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)
@property
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 {
2015-12-27 19:07:25 +00:00
'about': "Weather forecast from yr.no, delivered by the"
" Norwegian Meteorological Institute and the NRK"
}
@property
def unit_of_measurement(self):
2016-03-08 15:46:34 +00:00
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from yr.no and updates the states."""
2015-12-27 19:07:25 +00:00
now = dt_util.utcnow()
2016-02-23 05:21:49 +00:00
# Check if data should be updated
2015-12-27 19:07:25 +00:00
if self._update is not None and now <= self._update:
return
2015-12-27 19:07:25 +00:00
self._weather.update()
2016-02-23 05:21:49 +00:00
# Find sensor
2015-12-27 19:07:25 +00:00
for time_entry in self._weather.data['product']['time']:
2016-04-16 07:55:35 +00:00
valid_from = dt_util.parse_datetime(time_entry['@from'])
valid_to = dt_util.parse_datetime(time_entry['@to'])
2015-12-27 19:07:25 +00:00
loc_data = time_entry['location']
2015-12-27 19:07:25 +00:00
if self.type not in loc_data or now >= valid_to:
continue
2015-12-27 19:07:25 +00:00
self._update = valid_to
if self.type == 'precipitation' and valid_from < now:
2015-12-27 19:07:25 +00:00
self._state = loc_data[self.type]['@value']
break
elif self.type == 'symbol' and valid_from < now:
2015-12-27 19:07:25 +00:00
self._state = loc_data[self.type]['@number']
break
elif self.type in ('temperature', 'pressure', 'humidity',
2015-12-27 19:07:25 +00:00
'dewpointTemperature'):
self._state = loc_data[self.type]['@value']
break
elif self.type in ('windSpeed', 'windGust'):
2015-12-27 19:07:25 +00:00
self._state = loc_data[self.type]['@mps']
break
elif self.type == 'windDirection':
2015-12-27 19:07:25 +00:00
self._state = float(loc_data[self.type]['@deg'])
break
elif self.type in ('fog', 'cloudiness', 'lowClouds',
'mediumClouds', 'highClouds'):
self._state = loc_data[self.type]['@percent']
break
2015-12-04 14:05:23 +00:00
# pylint: disable=too-few-public-methods
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
def __init__(self, coordinates):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
2015-12-04 14:05:23 +00:00
self._url = 'http://api.yr.no/weatherapi/locationforecast/1.9/?' \
'lat={lat};lon={lon};msl={msl}'.format(**coordinates)
2015-12-27 19:07:25 +00:00
self._nextrun = None
self.data = {}
2015-12-04 14:05:23 +00:00
self.update()
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from yr.no."""
2016-02-23 05:21:49 +00:00
# Check if new will be available
2015-12-27 19:07:25 +00:00
if self._nextrun is not None and dt_util.utcnow() <= self._nextrun:
return
try:
2015-12-28 01:37:32 +00:00
with requests.Session() as sess:
response = sess.get(self._url)
except requests.RequestException:
return
if response.status_code != 200:
return
data = response.text
import xmltodict
self.data = xmltodict.parse(data)['weatherdata']
model = self.data['meta']['model']
if '@nextrun' not in model:
model = model[0]
2016-04-16 07:55:35 +00:00
self._nextrun = dt_util.parse_datetime(model['@nextrun'])