core/homeassistant/components/sensor/yr.py

198 lines
6.3 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
2015-12-27 19:07:25 +00:00
import requests
2016-02-19 05:27:50 +00:00
from homeassistant.const import (
ATTR_ENTITY_PICTURE, CONF_LATITUDE, CONF_LONGITUDE)
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'],
}
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-02-23 05:21:49 +00:00
"""Get the Yr.no sensor."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
elevation = config.get('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 = []
if 'monitored_conditions' in config:
for variable in config['monitored_conditions']:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
2015-12-04 14:05:23 +00:00
dev.append(YrSensor(variable, 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-02-23 05:21:49 +00:00
"""Implements an Yr.no sensor."""
2015-12-04 14:05:23 +00:00
def __init__(self, sensor_type, weather):
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-02-23 05:21:49 +00:00
"""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-02-23 05:21:49 +00:00
"""Returns the state of the device."""
return self._state
@property
def device_state_attributes(self):
2016-02-23 05:21:49 +00:00
"""Returns state attributes. """
2015-12-27 19:07:25 +00:00
data = {
'about': "Weather forecast from yr.no, delivered by the"
" Norwegian Meteorological Institute and the NRK"
}
if self.type == 'symbol':
symbol_nr = self._state
2015-12-27 19:07:25 +00:00
data[ATTR_ENTITY_PICTURE] = \
"http://api.met.no/weatherapi/weathericon/1.1/" \
"?symbol={0};content_type=image/png".format(symbol_nr)
2015-12-04 14:10:26 +00:00
return data
@property
def unit_of_measurement(self):
2016-02-23 05:21:49 +00:00
""" Unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
2016-02-23 05:21:49 +00:00
"""Gets 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']:
valid_from = dt_util.str_to_datetime(
time_entry['@from'], "%Y-%m-%dT%H:%M:%SZ")
valid_to = dt_util.str_to_datetime(
time_entry['@to'], "%Y-%m-%dT%H:%M:%SZ")
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-02-23 05:21:49 +00:00
"""Gets the latest data and updates the states."""
2015-12-04 14:05:23 +00:00
def __init__(self, coordinates):
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-02-23 05:21:49 +00:00
"""Gets the latest data from yr.no."""
# 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]
2015-12-27 19:07:25 +00:00
self._nextrun = dt_util.str_to_datetime(model['@nextrun'],
"%Y-%m-%dT%H:%M:%SZ")