hass-core/homeassistant/components/sensor/wunderground.py

162 lines
5.3 KiB
Python
Raw Normal View History

2016-08-18 10:37:00 -06:00
"""
2016-08-18 10:46:04 -06:00
Support for WUnderground weather service.
2016-08-18 10:37:00 -06:00
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.wunderground/
"""
from datetime import timedelta
import logging
import requests
2016-08-17 22:18:37 -06:00
import voluptuous as vol
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
2016-08-18 10:47:52 -06:00
from homeassistant.components.sensor import PLATFORM_SCHEMA
2016-08-17 22:18:37 -06:00
from homeassistant.const import (CONF_PLATFORM, CONF_MONITORED_CONDITIONS,
CONF_API_KEY, TEMP_FAHRENHEIT, TEMP_CELSIUS,
STATE_UNKNOWN)
CONF_PWS_ID = 'pws_id'
2016-08-18 09:59:41 -04:00
_RESOURCE = 'http://api.wunderground.com/api/{}/conditions/q/'
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)
# Sensor types are defined like: Name, units
SENSOR_TYPES = {
'weather': ['Weather Summary', None],
'station_id': ['Station ID', None],
'feelslike_c': ['Feels Like (°C)', TEMP_CELSIUS],
'feelslike_f': ['Feels Like (°F)', TEMP_FAHRENHEIT],
'feelslike_string': ['Feels Like', None],
'heat_index_c': ['Dewpoint (°C)', TEMP_CELSIUS],
'heat_index_f': ['Dewpoint (°F)', TEMP_FAHRENHEIT],
'heat_index_string': ['Heat Index Summary', None],
'dewpoint_c': ['Dewpoint (°C)', TEMP_CELSIUS],
'dewpoint_f': ['Dewpoint (°F)', TEMP_FAHRENHEIT],
'dewpoint_string': ['Dewpoint Summary', None],
'wind_kph': ['Wind Speed', 'kpH'],
'wind_mph': ['Wind Speed', 'mpH'],
'UV': ['UV', None],
'pressure_in': ['Pressure', 'in'],
'pressure_mb': ['Pressure', 'mbar'],
'wind_dir': ['Wind Direction', None],
'wind_string': ['Wind Summary', None],
'temp_c': ['Temperature (°C)', TEMP_CELSIUS],
'temp_f': ['Temperature (°F)', TEMP_FAHRENHEIT],
'relative_humidity': ['Relative Humidity', '%'],
'visibility_mi': ['Visibility (miles)', 'mi'],
'visibility_km': ['Visibility (km)', 'km'],
'precip_today_in': ['Precipation Today', 'in'],
2016-08-17 16:50:32 -04:00
'precip_today_metric': ['Precipitation Today', 'mm'],
'precip_today_string': ['Precipitation today', None],
'solarradiation': ['Solar Radiation', None]
}
2016-08-18 10:47:52 -06:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
2016-08-17 22:19:13 -06:00
vol.Required(CONF_PLATFORM): "wunderground",
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_PWS_ID): cv.string,
2016-08-18 09:59:41 -04:00
vol.Required(CONF_MONITORED_CONDITIONS,
default=[]): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
2016-08-17 22:19:13 -06:00
})
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-08-18 10:46:04 -06:00
"""Setup the WUnderground sensor."""
2016-08-17 22:29:00 -06:00
rest = WUndergroundData(hass,
config.get(CONF_API_KEY),
2016-08-17 22:29:00 -06:00
config.get(CONF_PWS_ID, None))
sensors = []
2016-08-18 10:38:34 -06:00
for variable in config[CONF_MONITORED_CONDITIONS]:
2016-08-18 10:32:19 -06:00
sensors.append(WUndergroundSensor(rest, variable))
try:
rest.update()
except ValueError as err:
_LOGGER.error("Received error from WUnderground: %s", err)
return False
add_devices(sensors)
return True
class WUndergroundSensor(Entity):
2016-08-18 10:46:04 -06:00
"""Implementing the WUnderground sensor."""
def __init__(self, rest, condition):
"""Initialize the sensor."""
self.rest = rest
self._condition = condition
@property
def name(self):
"""Return the name of the sensor."""
2016-08-17 22:29:49 -06:00
return "PWS_" + self._condition
@property
def state(self):
"""Return the state of the sensor."""
2016-08-17 22:30:23 -06:00
if self.rest.data and self._condition in self.rest.data:
return self.rest.data[self._condition]
else:
return STATE_UNKNOWN
@property
def entity_picture(self):
"""Return the entity picture."""
if self._condition == 'weather':
2016-08-17 22:31:28 -06:00
return self.rest.data['icon_url']
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return SENSOR_TYPES[self._condition][1]
def update(self):
"""Update current conditions."""
self.rest.update()
# pylint: disable=too-few-public-methods
class WUndergroundData(object):
2016-08-18 10:46:04 -06:00
"""Get data from WUnderground."""
2016-08-17 22:28:05 -06:00
def __init__(self, hass, api_key, pws_id=None):
"""Initialize the data object."""
2016-08-17 22:28:05 -06:00
self._hass = hass
self._api_key = api_key
self._pws_id = pws_id
2016-08-17 22:28:05 -06:00
self._latitude = hass.config.latitude
self._longitude = hass.config.longitude
self.data = None
2016-08-17 22:22:11 -06:00
def _build_url(self):
2016-08-18 09:59:41 -04:00
url = _RESOURCE.format(self._api_key)
2016-08-17 22:22:11 -06:00
if self._pws_id:
2016-08-18 10:46:24 -06:00
url = url + 'pws:{}'.format(self._pws_id)
2016-08-17 22:22:11 -06:00
else:
url = url + '{},{}'.format(self._latitude, self._longitude)
return url + '.json'
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
2016-08-18 10:46:04 -06:00
"""Get the latest data from WUnderground."""
try:
2016-08-17 22:32:19 -06:00
result = requests.get(self._build_url(), timeout=10).json()
2016-08-17 22:32:42 -06:00
if "error" in result['response']:
raise ValueError(result['response']["error"]
["description"])
else:
2016-08-17 22:32:42 -06:00
self.data = result["current_observation"]
except ValueError as err:
2016-08-18 10:46:04 -06:00
_LOGGER.error("Check WUnderground API %s", err.args)
self.data = None
2016-08-17 22:31:58 -06:00
raise