Do not call update() in constructor (#7931)

This commit is contained in:
Fabian Affolter 2017-06-06 19:15:03 +02:00 committed by GitHub
parent cbbb15fa48
commit 5c96936eb4

View File

@ -9,15 +9,14 @@ from datetime import timedelta
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ( from homeassistant.const import (
TEMP_CELSIUS, CONF_MONITORED_CONDITIONS, CONF_NAME, STATE_UNKNOWN, TEMP_CELSIUS, CONF_MONITORED_CONDITIONS, CONF_NAME, STATE_UNKNOWN,
ATTR_ATTRIBUTION) ATTR_ATTRIBUTION)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = ["yahooweather==0.8"] REQUIREMENTS = ['yahooweather==0.8']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -27,18 +26,18 @@ CONF_WOEID = 'woeid'
DEFAULT_NAME = 'Yweather' DEFAULT_NAME = 'Yweather'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600) SCAN_INTERVAL = timedelta(minutes=10)
SENSOR_TYPES = { SENSOR_TYPES = {
'weather_current': ['Current', None], 'weather_current': ['Current', None],
'weather': ['Condition', None], 'weather': ['Condition', None],
'temperature': ['Temperature', "temperature"], 'temperature': ['Temperature', 'temperature'],
'temp_min': ['Temperature min', "temperature"], 'temp_min': ['Temperature min', 'temperature'],
'temp_max': ['Temperature max', "temperature"], 'temp_max': ['Temperature max', 'temperature'],
'wind_speed': ['Wind speed', "speed"], 'wind_speed': ['Wind speed', 'speed'],
'humidity': ['Humidity', "%"], 'humidity': ['Humidity', '%'],
'pressure': ['Pressure', "pressure"], 'pressure': ['Pressure', 'pressure'],
'visibility': ['Visibility', "distance"], 'visibility': ['Visibility', 'distance'],
} }
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@ -52,7 +51,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setnup the Yahoo! weather sensor.""" """Set up the Yahoo! weather sensor."""
from yahooweather import get_woeid, UNIT_C, UNIT_F from yahooweather import get_woeid, UNIT_C, UNIT_F
unit = hass.config.units.temperature_unit unit = hass.config.units.temperature_unit
@ -62,14 +61,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
yunit = UNIT_C if unit == TEMP_CELSIUS else UNIT_F yunit = UNIT_C if unit == TEMP_CELSIUS else UNIT_F
SENSOR_TYPES["temperature"][1] = unit SENSOR_TYPES['temperature'][1] = unit
SENSOR_TYPES["temp_min"][1] = unit SENSOR_TYPES['temp_min'][1] = unit
SENSOR_TYPES["temp_max"][1] = unit SENSOR_TYPES['temp_max'][1] = unit
# If not exists a customer woeid / calc from HA # If not exists a customer WOEID/calculation from Home Assistant
if woeid is None: if woeid is None:
woeid = get_woeid(hass.config.latitude, hass.config.longitude) woeid = get_woeid(hass.config.latitude, hass.config.longitude)
# receive a error?
if woeid is None: if woeid is None:
_LOGGER.critical("Can't retrieve WOEID from yahoo!") _LOGGER.critical("Can't retrieve WOEID from yahoo!")
return False return False
@ -77,11 +75,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
yahoo_api = YahooWeatherData(woeid, yunit) yahoo_api = YahooWeatherData(woeid, yunit)
if not yahoo_api.update(): if not yahoo_api.update():
_LOGGER.critical("Can't retrieve weather data from yahoo!") _LOGGER.critical("Can't retrieve weather data from Yahoo!")
return False return False
if forecast >= len(yahoo_api.yahoo.Forecast): if forecast >= len(yahoo_api.yahoo.Forecast):
_LOGGER.error("Yahoo! only support %d days forcast!", _LOGGER.error("Yahoo! only support %d days forecast!",
len(yahoo_api.yahoo.Forecast)) len(yahoo_api.yahoo.Forecast))
return False return False
@ -89,11 +87,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
for variable in config[CONF_MONITORED_CONDITIONS]: for variable in config[CONF_MONITORED_CONDITIONS]:
dev.append(YahooWeatherSensor(yahoo_api, name, forecast, variable)) dev.append(YahooWeatherSensor(yahoo_api, name, forecast, variable))
add_devices(dev) add_devices(dev, True)
class YahooWeatherSensor(Entity): class YahooWeatherSensor(Entity):
"""Implementation of an Yahoo! weather sensor.""" """Implementation of the Yahoo! weather sensor."""
def __init__(self, weather_data, name, forecast, sensor_type): def __init__(self, weather_data, name, forecast, sensor_type):
"""Initialize the sensor.""" """Initialize the sensor."""
@ -106,9 +104,6 @@ class YahooWeatherSensor(Entity):
self._forecast = forecast self._forecast = forecast
self._code = None self._code = None
# update data
self.update()
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
@ -143,13 +138,13 @@ class YahooWeatherSensor(Entity):
"""Get the latest data from Yahoo! and updates the states.""" """Get the latest data from Yahoo! and updates the states."""
self._data.update() self._data.update()
if not self._data.yahoo.RawData: if not self._data.yahoo.RawData:
_LOGGER.info("Don't receive weather data from yahoo!") _LOGGER.info("Don't receive weather data from Yahoo!")
return return
# default code for weather image # Default code for weather image
self._code = self._data.yahoo.Now['code'] self._code = self._data.yahoo.Now['code']
# read data # Read data
if self._type == 'weather_current': if self._type == 'weather_current':
self._state = self._data.yahoo.Now['text'] self._state = self._data.yahoo.Now['text']
elif self._type == 'weather': elif self._type == 'weather':
@ -174,21 +169,18 @@ class YahooWeatherSensor(Entity):
class YahooWeatherData(object): class YahooWeatherData(object):
"""Handle yahoo api object and limit updates.""" """Handle Yahoo! API object and limit updates."""
def __init__(self, woeid, temp_unit): def __init__(self, woeid, temp_unit):
"""Initialize the data object.""" """Initialize the data object."""
from yahooweather import YahooWeather from yahooweather import YahooWeather
# init yahoo api object
self._yahoo = YahooWeather(woeid, temp_unit) self._yahoo = YahooWeather(woeid, temp_unit)
@property @property
def yahoo(self): def yahoo(self):
"""Return yahoo api object.""" """Return Yahoo! API object."""
return self._yahoo return self._yahoo
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
"""Get the latest data from yahoo. True is success.""" """Get the latest data from Yahoo!."""
return self._yahoo.updateWeather() return self._yahoo.updateWeather()