core/homeassistant/components/sensor/forecast.py

247 lines
8.9 KiB
Python
Raw Normal View History

2015-06-17 19:59:38 +00:00
"""
2016-02-23 05:21:49 +00:00
Support for Forecast.io weather service.
2015-06-17 19:59:38 +00:00
2015-10-24 07:10:31 +00:00
For more details about this platform, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/sensor.forecast/
2015-06-17 19:59:38 +00:00
"""
import logging
from datetime import timedelta
from requests.exceptions import ConnectionError as ConnectError, \
HTTPError, Timeout
2015-06-17 19:59:38 +00:00
from homeassistant.components.sensor import DOMAIN
Add unit system support Add unit symbol constants Initial unit system object Import more constants Pydoc for unit system file Import constants for configuration validation Unit system validation method Typing for constants Inches are valid lengths too Typings Change base class to dict - needed for remote api call serialization Validation Use dictionary keys Defined unit systems Update location util to use metric instead of us fahrenheit Update constant imports Import defined unit systems Update configuration to use unit system Update schema to use unit system Update constants Add imports to core for unit system and distance Type for config Default unit system Convert distance from HASS instance Update temperature conversion to use unit system Update temperature conversion Set unit system based on configuration Set info unit system Return unit system dictionary with config dictionary Auto discover unit system Update location test for use metric Update forecast unit system Update mold indicator unit system Update thermostat unit system Update thermostat demo test Unit tests around unit system Update test common hass configuration Update configuration unit tests There should always be a unit system! Update core unit tests Constants typing Linting issues Remove unused import Update fitbit sensor to use application unit system Update google travel time to use application unit system Update configuration example Update dht sensor Update DHT temperature conversion to use the utility function Update swagger config Update my sensors metric flag Update hvac component temperature conversion HVAC conversion for temperature Pull unit from sensor type map Pull unit from sensor type map Update the temper sensor unit Update yWeather sensor unit Update hvac demo unit test Set unit test config unit system to metric Use hass unit system length for default in proximity Use the name of the system instead of temperature Use constants from const Unused import Forecasted temperature Fix calculation in case furthest distance is greater than 1000000 units Remove unneeded constants Set default length to km or miles Use constants Linting doesn't like importing just for typing Fix reference Test is expecting meters - set config to meters Use constant Use constant PyDoc for unit test Should be not in Rename to units Change unit system to be an object - not a dictionary Return tuple in conversion Move convert to temperature util Temperature conversion is now in unit system Update imports Rename to units Units is now an object Use temperature util conversion Unit system is now an object Validate and convert unit system config Return the scalar value in template distance Test is expecting meters Update unit tests around unit system Distance util returns tuple Fix location info test Set units Update unit tests Convert distance DOH Pull out the scalar from the vector Linting I really hate python linting Linting again BLARG Unit test documentation Unit test around is metric flag Break ternary statement into if/else blocks Don't use dictionary - use members is metric flag Rename constants Use is metric flag Move constants to CONST file Move to const file Raise error if unit is not expected Typing No need to return unit since only performing conversion if it can work Use constants Line wrapping Raise error if invalid value Remove subscripts from conversion as they are no longer returned as tuples No longer tuples No longer tuples Check for numeric type Fix string format to use correct variable Typing Assert errors raised Remove subscript Only convert temperature if we know the unit If no unit of measurement set - default to HASS config Convert only if we know the unit Remove subscription Fix not in clause Linting fixes Wants a boolean Clearer if-block Check if the key is in the config first Missed a couple expecting tuples Backwards compatibility No like-y ternary! Error handling around state setting Pretty unit system configuration validation More tuple crap Use is metric flag Error handling around min/max temp Explode if no unit Pull unit from config Celsius has a decimal Unused import Check if it's a temperature before we try to convert it to a temperature Linting says too many statements - combine lat/long in a fairly reasonable manner Backwards compatibility unit test Better doc
2016-07-31 20:24:49 +00:00
from homeassistant.const import CONF_API_KEY
from homeassistant.helpers import validate_config
2015-06-17 19:59:38 +00:00
from homeassistant.helpers.entity import Entity
2016-02-19 05:27:50 +00:00
from homeassistant.util import Throttle
2015-06-17 19:59:38 +00:00
2016-03-24 15:42:25 +00:00
REQUIREMENTS = ['python-forecastio==1.3.4']
2015-06-17 19:59:38 +00:00
_LOGGER = logging.getLogger(__name__)
# Sensor types are defined like so:
# Name, si unit, us unit, ca unit, uk unit, uk2 unit
2015-06-17 19:59:38 +00:00
SENSOR_TYPES = {
2016-01-18 01:50:20 +00:00
'summary': ['Summary', None, None, None, None, None],
'minutely_summary': ['Minutely Summary', None, None, None, None, None],
'hourly_summary': ['Hourly Summary', None, None, None, None, None],
'daily_summary': ['Daily Summary', None, None, None, None, None],
2016-01-18 01:50:20 +00:00
'icon': ['Icon', None, None, None, None, None],
'nearest_storm_distance': ['Nearest Storm Distance',
'km', 'm', 'km', 'km', 'm'],
'nearest_storm_bearing': ['Nearest Storm Bearing',
'°', '°', '°', '°', '°'],
2016-01-18 01:50:20 +00:00
'precip_type': ['Precip', None, None, None, None, None],
'precip_intensity': ['Precip Intensity', 'mm', 'in', 'mm', 'mm', 'mm'],
'precip_probability': ['Precip Probability', '%', '%', '%', '%', '%'],
'temperature': ['Temperature', '°C', '°F', '°C', '°C', '°C'],
'apparent_temperature': ['Apparent Temperature',
'°C', '°F', '°C', '°C', '°C'],
'dew_point': ['Dew point', '°C', '°F', '°C', '°C', '°C'],
'wind_speed': ['Wind Speed', 'm/s', 'mph', 'km/h', 'mph', 'mph'],
'wind_bearing': ['Wind Bearing', '°', '°', '°', '°', '°'],
'cloud_cover': ['Cloud Coverage', '%', '%', '%', '%', '%'],
'humidity': ['Humidity', '%', '%', '%', '%', '%'],
'pressure': ['Pressure', 'mbar', 'mbar', 'mbar', 'mbar', 'mbar'],
'visibility': ['Visibility', 'km', 'm', 'km', 'km', 'm'],
'ozone': ['Ozone', 'DU', 'DU', 'DU', 'DU', 'DU'],
2015-06-17 19:59:38 +00:00
}
2016-02-23 05:21:49 +00:00
# Return cached results if last scan was less then this time ago.
2015-06-17 19:59:38 +00:00
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-03-08 15:46:34 +00:00
"""Setup the Forecast.io sensor."""
# Validate the configuration
2015-06-17 19:59:38 +00:00
if None in (hass.config.latitude, hass.config.longitude):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
return False
elif not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY]}, _LOGGER):
2015-06-17 19:59:38 +00:00
return False
if 'units' in config:
units = config['units']
Add unit system support Add unit symbol constants Initial unit system object Import more constants Pydoc for unit system file Import constants for configuration validation Unit system validation method Typing for constants Inches are valid lengths too Typings Change base class to dict - needed for remote api call serialization Validation Use dictionary keys Defined unit systems Update location util to use metric instead of us fahrenheit Update constant imports Import defined unit systems Update configuration to use unit system Update schema to use unit system Update constants Add imports to core for unit system and distance Type for config Default unit system Convert distance from HASS instance Update temperature conversion to use unit system Update temperature conversion Set unit system based on configuration Set info unit system Return unit system dictionary with config dictionary Auto discover unit system Update location test for use metric Update forecast unit system Update mold indicator unit system Update thermostat unit system Update thermostat demo test Unit tests around unit system Update test common hass configuration Update configuration unit tests There should always be a unit system! Update core unit tests Constants typing Linting issues Remove unused import Update fitbit sensor to use application unit system Update google travel time to use application unit system Update configuration example Update dht sensor Update DHT temperature conversion to use the utility function Update swagger config Update my sensors metric flag Update hvac component temperature conversion HVAC conversion for temperature Pull unit from sensor type map Pull unit from sensor type map Update the temper sensor unit Update yWeather sensor unit Update hvac demo unit test Set unit test config unit system to metric Use hass unit system length for default in proximity Use the name of the system instead of temperature Use constants from const Unused import Forecasted temperature Fix calculation in case furthest distance is greater than 1000000 units Remove unneeded constants Set default length to km or miles Use constants Linting doesn't like importing just for typing Fix reference Test is expecting meters - set config to meters Use constant Use constant PyDoc for unit test Should be not in Rename to units Change unit system to be an object - not a dictionary Return tuple in conversion Move convert to temperature util Temperature conversion is now in unit system Update imports Rename to units Units is now an object Use temperature util conversion Unit system is now an object Validate and convert unit system config Return the scalar value in template distance Test is expecting meters Update unit tests around unit system Distance util returns tuple Fix location info test Set units Update unit tests Convert distance DOH Pull out the scalar from the vector Linting I really hate python linting Linting again BLARG Unit test documentation Unit test around is metric flag Break ternary statement into if/else blocks Don't use dictionary - use members is metric flag Rename constants Use is metric flag Move constants to CONST file Move to const file Raise error if unit is not expected Typing No need to return unit since only performing conversion if it can work Use constants Line wrapping Raise error if invalid value Remove subscripts from conversion as they are no longer returned as tuples No longer tuples No longer tuples Check for numeric type Fix string format to use correct variable Typing Assert errors raised Remove subscript Only convert temperature if we know the unit If no unit of measurement set - default to HASS config Convert only if we know the unit Remove subscription Fix not in clause Linting fixes Wants a boolean Clearer if-block Check if the key is in the config first Missed a couple expecting tuples Backwards compatibility No like-y ternary! Error handling around state setting Pretty unit system configuration validation More tuple crap Use is metric flag Error handling around min/max temp Explode if no unit Pull unit from config Celsius has a decimal Unused import Check if it's a temperature before we try to convert it to a temperature Linting says too many statements - combine lat/long in a fairly reasonable manner Backwards compatibility unit test Better doc
2016-07-31 20:24:49 +00:00
elif hass.config.units.is_metric:
units = 'si'
else:
units = 'us'
# Create a data fetcher to support all of the configured sensors. Then make
# the first call to init the data and confirm we can connect.
try:
forecast_data = ForeCastData(
config.get(CONF_API_KEY, None), hass.config.latitude,
hass.config.longitude, units)
forecast_data.update_currently()
except ValueError as error:
_LOGGER.error(error)
return False
2015-06-17 19:59:38 +00:00
# Initialize and add all of the sensors.
sensors = []
2015-06-17 19:59:38 +00:00
for variable in config['monitored_conditions']:
if variable in SENSOR_TYPES:
sensors.append(ForeCastSensor(forecast_data, variable))
2015-06-17 19:59:38 +00:00
else:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
2015-06-17 19:59:38 +00:00
add_devices(sensors)
2015-06-17 19:59:38 +00:00
# pylint: disable=too-few-public-methods
class ForeCastSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Implementation of a Forecast.io sensor."""
2015-06-17 19:59:38 +00:00
def __init__(self, forecast_data, sensor_type):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
self.client_name = 'Weather'
2015-06-17 19:59:38 +00:00
self._name = SENSOR_TYPES[sensor_type][0]
self.forecast_data = forecast_data
2015-06-17 19:59:38 +00:00
self.type = sensor_type
self._state = None
self._unit_of_measurement = None
2015-06-17 19:59:38 +00:00
self.update()
@property
def name(self):
2016-03-08 15:46:34 +00:00
"""Return the name of the sensor."""
return '{} {}'.format(self.client_name, self._name)
2015-06-17 19:59:38 +00:00
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the sensor."""
2015-06-17 19:59:38 +00:00
return self._state
@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-06-17 19:59:38 +00:00
return self._unit_of_measurement
@property
def unit_system(self):
2016-03-08 15:46:34 +00:00
"""Return the unit system of this entity."""
return self.forecast_data.unit_system
def update_unit_of_measurement(self):
"""Update units based on unit system."""
unit_index = {
'si': 1,
'us': 2,
'ca': 3,
'uk': 4,
'uk2': 5
}.get(self.unit_system, 1)
self._unit_of_measurement = SENSOR_TYPES[self.type][unit_index]
2015-06-17 19:59:38 +00:00
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from Forecast.io and updates the states."""
# Call the API for new forecast data. Each sensor will re-trigger this
# same exact call, but thats fine. We cache results for a short period
# of time to prevent hitting API limits. Note that forecast.io will
# charge users for too many calls in 1 day, so take care when updating.
self.forecast_data.update()
self.update_unit_of_measurement()
if self.type == 'minutely_summary':
self.forecast_data.update_minutely()
minutely = self.forecast_data.data_minutely
self._state = getattr(minutely, 'summary', '')
elif self.type == 'hourly_summary':
self.forecast_data.update_hourly()
hourly = self.forecast_data.data_hourly
self._state = getattr(hourly, 'summary', '')
elif self.type == 'daily_summary':
self.forecast_data.update_daily()
daily = self.forecast_data.data_daily
self._state = getattr(daily, 'summary', '')
else:
self.forecast_data.update_currently()
currently = self.forecast_data.data_currently
self._state = self.get_currently_state(currently)
2015-06-17 19:59:38 +00:00
def get_currently_state(self, data):
"""
Helper function that returns a new state based on the type.
2015-06-17 19:59:38 +00:00
If the sensor type is unknown, the current state is returned.
"""
lookup_type = convert_to_camel(self.type)
state = getattr(data, lookup_type, 0)
2016-06-01 16:17:15 +00:00
# Some state data needs to be rounded to whole values or converted to
# percentages
if self.type in ['precip_probability', 'cloud_cover', 'humidity']:
return round(state * 100, 1)
elif (self.type in ['dew_point', 'temperature', 'apparent_temperature',
'pressure', 'ozone']):
return round(state, 1)
return state
2016-06-01 16:17:15 +00:00
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
2016-06-01 16:17:15 +00:00
This is not pythonic, but needed for certain situations
"""
components = data.split('_')
return components[0] + "".join(x.title() for x in components[1:])
2015-06-17 19:59:38 +00:00
class ForeCastData(object):
2016-02-23 05:21:49 +00:00
"""Gets the latest data from Forecast.io."""
2015-06-17 19:59:38 +00:00
2016-06-01 16:17:15 +00:00
# pylint: disable=too-many-instance-attributes
def __init__(self, api_key, latitude, longitude, units):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
2015-06-17 19:59:38 +00:00
self._api_key = api_key
self.latitude = latitude
self.longitude = longitude
2016-06-01 16:17:15 +00:00
self.units = units
2015-06-17 19:59:38 +00:00
self.data = None
self.unit_system = None
2016-06-01 16:17:15 +00:00
self.data_currently = None
self.data_minutely = None
self.data_hourly = None
self.data_daily = None
self.update()
2015-06-17 19:59:38 +00:00
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from Forecast.io."""
2015-11-29 21:49:05 +00:00
import forecastio
2015-06-17 19:59:38 +00:00
try:
self.data = forecastio.load_forecast(self._api_key,
self.latitude,
self.longitude,
units=self.units)
except (ConnectError, HTTPError, Timeout, ValueError) as error:
raise ValueError("Unable to init Forecast.io. - %s", error)
2016-06-01 16:17:15 +00:00
self.unit_system = self.data.json['flags']['units']
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update_currently(self):
"""Update currently data."""
self.data_currently = self.data.currently()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update_minutely(self):
"""Update minutely data."""
self.data_minutely = self.data.minutely()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update_hourly(self):
"""Update hourly data."""
self.data_hourly = self.data.hourly()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update_daily(self):
"""Update daily data."""
self.data_daily = self.data.daily()