From 10a2ecd1d61ae3d2355301096ba096dcf3e065ab Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Tue, 14 Aug 2018 12:29:31 +0200 Subject: [PATCH] Make setup fail if location is not available (#15967) * Make setup fail if location is not available * Lint --- .../components/sensor/worldtidesinfo.py | 55 +++++++++++-------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/homeassistant/components/sensor/worldtidesinfo.py b/homeassistant/components/sensor/worldtidesinfo.py index 597a971e208..adaa327d39a 100644 --- a/homeassistant/components/sensor/worldtidesinfo.py +++ b/homeassistant/components/sensor/worldtidesinfo.py @@ -1,24 +1,26 @@ """ -This component provides HA sensor support for the worldtides.info API. +Support for the worldtides.info API. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.worldtidesinfo/ """ +from datetime import timedelta import logging import time -from datetime import timedelta import requests import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import (CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, - CONF_NAME, STATE_UNKNOWN) +from homeassistant.const import ( + ATTR_ATTRIBUTION, CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME) +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) +CONF_ATTRIBUTION = "Data provided by WorldTides" + DEFAULT_NAME = 'WorldTidesInfo' SCAN_INTERVAL = timedelta(seconds=3600) @@ -42,7 +44,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if None in (lat, lon): _LOGGER.error("Latitude or longitude not set in Home Assistant config") - add_devices([WorldTidesInfoSensor(name, lat, lon, key)], True) + tides = WorldTidesInfoSensor(name, lat, lon, key) + tides.update() + if tides.data.get('error') == 'No location found': + _LOGGER.error("Location not available") + return + + add_devices([tides]) class WorldTidesInfoSensor(Entity): @@ -64,13 +72,14 @@ class WorldTidesInfoSensor(Entity): @property def device_state_attributes(self): """Return the state attributes of this device.""" - attr = {} - if "High" in str(self.data['extremes'][0]['type']): + attr = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION} + + if 'High' in str(self.data['extremes'][0]['type']): attr['high_tide_time_utc'] = self.data['extremes'][0]['date'] attr['high_tide_height'] = self.data['extremes'][0]['height'] attr['low_tide_time_utc'] = self.data['extremes'][1]['date'] attr['low_tide_height'] = self.data['extremes'][1]['height'] - elif "Low" in str(self.data['extremes'][0]['type']): + elif 'Low' in str(self.data['extremes'][0]['type']): attr['high_tide_time_utc'] = self.data['extremes'][1]['date'] attr['high_tide_height'] = self.data['extremes'][1]['height'] attr['low_tide_time_utc'] = self.data['extremes'][0]['date'] @@ -81,30 +90,30 @@ class WorldTidesInfoSensor(Entity): def state(self): """Return the state of the device.""" if self.data: - if "High" in str(self.data['extremes'][0]['type']): + if 'High' in str(self.data['extremes'][0]['type']): tidetime = time.strftime('%I:%M %p', time.localtime( self.data['extremes'][0]['dt'])) - return "High tide at %s" % (tidetime) - if "Low" in str(self.data['extremes'][0]['type']): + return "High tide at {}".format(tidetime) + if 'Low' in str(self.data['extremes'][0]['type']): tidetime = time.strftime('%I:%M %p', time.localtime( self.data['extremes'][0]['dt'])) - return "Low tide at %s" % (tidetime) - return STATE_UNKNOWN - return STATE_UNKNOWN + return "Low tide at {}".format(tidetime) + return None + return None def update(self): """Get the latest data from WorldTidesInfo API.""" start = int(time.time()) - resource = 'https://www.worldtides.info/api?extremes&length=86400' \ - '&key=%s&lat=%s&lon=%s&start=%s' % (self._key, self._lat, - self._lon, start) + resource = ('https://www.worldtides.info/api?extremes&length=86400' + '&key={}&lat={}&lon={}&start={}').format( + self._key, self._lat, self._lon, start) try: self.data = requests.get(resource, timeout=10).json() - _LOGGER.debug("Data = %s", self.data) - _LOGGER.info("Tide data queried with start time set to: %s", - (start)) + _LOGGER.debug("Data: %s", self.data) + _LOGGER.debug( + "Tide data queried with start time set to: %s", start) except ValueError as err: - _LOGGER.error("Check WorldTidesInfo %s", err.args) + _LOGGER.error( + "Error retrieving data from WorldTidesInfo: %s", err.args) self.data = None - raise