Maintenance (sensor.currencylayer, sensor.fixer) (#4103)

* Add new const (base)

* Use constant

* Remove second error message, use const, add attribution, add link
to docs, remove unused vars, and a little simplification

* Add quote

* Use const

* Add attribution, simplify the code, and use consts
This commit is contained in:
Fabian Affolter 2016-10-29 22:27:02 +02:00 committed by Paulus Schoutsen
parent 892f455aee
commit 54d19e3c53
4 changed files with 74 additions and 58 deletions

View File

@ -1,24 +1,34 @@
"""Support for currencylayer.com exchange rates service.""" """
Support for currencylayer.com exchange rates service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.currencylayer/
"""
from datetime import timedelta from datetime import timedelta
import logging import logging
import requests import requests
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 (
CONF_API_KEY, CONF_NAME, CONF_BASE, CONF_QUOTE, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
from homeassistant.const import (CONF_API_KEY, CONF_NAME, CONF_PAYLOAD) import homeassistant.helpers.config_validation as cv
_RESOURCE = 'http://apilayer.net/api/live'
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago. _RESOURCE = 'http://apilayer.net/api/live'
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2)
CONF_BASE = 'base' CONF_ATTRIBUTION = "Data provided by currencylayer.com"
CONF_QUOTE = 'quote'
DEFAULT_BASE = 'USD' DEFAULT_BASE = 'USD'
DEFAULT_NAME = 'CurrencyLayer Sensor' DEFAULT_NAME = 'CurrencyLayer Sensor'
ICON = 'mdi:currency' ICON = 'mdi:currency'
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_QUOTE): vol.All(cv.ensure_list, [cv.string]), vol.Required(CONF_QUOTE): vol.All(cv.ensure_list, [cv.string]),
@ -29,24 +39,21 @@ 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):
"""Set up the Currencylayer sensor.""" """Set up the Currencylayer sensor."""
payload = config.get(CONF_PAYLOAD) base = config.get(CONF_BASE)
rest = CurrencylayerData( api_key = config.get(CONF_API_KEY)
_RESOURCE, parameters = {
config.get(CONF_API_KEY), 'source': base,
config.get(CONF_BASE, 'USD'), 'access_key': api_key,
payload 'format': 1,
) }
response = requests.get(_RESOURCE, params={'source':
config.get(CONF_BASE, 'USD'), rest = CurrencylayerData(_RESOURCE, parameters)
'access_key':
config.get(CONF_API_KEY), response = requests.get(_RESOURCE, params=parameters, timeout=10)
'format': 1}, timeout=10)
sensors = [] sensors = []
for variable in config['quote']: for variable in config['quote']:
sensors.append(CurrencylayerSensor(rest, config.get(CONF_BASE, 'USD'), sensors.append(CurrencylayerSensor(rest, base, variable))
variable)) if 'error' in response.json():
if "error" in response.json():
_LOGGER.error("Check your Currencylayer API")
return False return False
else: else:
add_devices(sensors) add_devices(sensors)
@ -66,7 +73,7 @@ class CurrencylayerSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return str(self._base) + str(self._quote) return '{} {}'.format(self._base, self._quote)
@property @property
def icon(self): def icon(self):
@ -78,12 +85,20 @@ class CurrencylayerSensor(Entity):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self._state return self._state
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
def update(self): def update(self):
"""Update current conditions.""" """Update current date."""
self.rest.update() self.rest.update()
value = self.rest.data value = self.rest.data
if value is not None: if value is not None:
self._state = round(value[str(self._base) + str(self._quote)], 4) self._state = round(
value['{}{}'.format(self._base, self._quote)], 4)
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
@ -91,24 +106,20 @@ class CurrencylayerData(object):
"""Get data from Currencylayer.org.""" """Get data from Currencylayer.org."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, resource, api_key, base, data): def __init__(self, resource, parameters):
"""Initialize the data object.""" """Initialize the data object."""
self._resource = resource self._resource = resource
self._api_key = api_key self._parameters = parameters
self._base = base
self.data = None self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
"""Get the latest data from Currencylayer.""" """Get the latest data from Currencylayer."""
try: try:
result = requests.get(self._resource, params={'source': self._base, result = requests.get(
'access_key': self._resource, params=self._parameters, timeout=10)
self._api_key, if 'error' in result.json():
'format': 1}, raise ValueError(result.json()['error']['info'])
timeout=10)
if "error" in result.json():
raise ValueError(result.json()["error"]["info"])
else: else:
self.data = result.json()['quotes'] self.data = result.json()['quotes']
_LOGGER.debug("Currencylayer data updated: %s", _LOGGER.debug("Currencylayer data updated: %s",

View File

@ -10,7 +10,7 @@ from datetime import timedelta
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION, CONF_BASE)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -24,7 +24,6 @@ ATTR_EXCHANGE_RATE = 'Exchange rate'
ATTR_TARGET = 'Target currency' ATTR_TARGET = 'Target currency'
CONF_ATTRIBUTION = "Data provided by the European Central Bank (ECB)" CONF_ATTRIBUTION = "Data provided by the European Central Bank (ECB)"
CONF_BASE = 'base'
CONF_TARGET = 'target' CONF_TARGET = 'target'
DEFAULT_BASE = 'USD' DEFAULT_BASE = 'USD'

View File

@ -11,7 +11,8 @@ import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_API_KEY, CONF_NAME, CONF_PAYLOAD) from homeassistant.const import (
CONF_API_KEY, CONF_NAME, CONF_BASE, CONF_QUOTE, ATTR_ATTRIBUTION)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
@ -19,8 +20,7 @@ from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_RESOURCE = 'https://openexchangerates.org/api/latest.json' _RESOURCE = 'https://openexchangerates.org/api/latest.json'
CONF_BASE = 'base' CONF_ATTRIBUTION = "Data provided by openexchangerates.org"
CONF_QUOTE = 'quote'
DEFAULT_BASE = 'USD' DEFAULT_BASE = 'USD'
DEFAULT_NAME = 'Exchange Rate Sensor' DEFAULT_NAME = 'Exchange Rate Sensor'
@ -41,15 +41,19 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
api_key = config.get(CONF_API_KEY) api_key = config.get(CONF_API_KEY)
base = config.get(CONF_BASE) base = config.get(CONF_BASE)
quote = config.get(CONF_QUOTE) quote = config.get(CONF_QUOTE)
payload = config.get(CONF_PAYLOAD)
rest = OpenexchangeratesData(_RESOURCE, api_key, base, quote, payload) parameters = {
response = requests.get(_RESOURCE, params={'base': base, 'base': base,
'app_id': api_key}, 'app_id': api_key,
timeout=10) }
rest = OpenexchangeratesData(_RESOURCE, parameters, quote)
response = requests.get(_RESOURCE, params=parameters, timeout=10)
if response.status_code != 200: if response.status_code != 200:
_LOGGER.error("Check your OpenExchangeRates API key") _LOGGER.error("Check your OpenExchangeRates API key")
return False return False
rest.update() rest.update()
add_devices([OpenexchangeratesSensor(rest, name, quote)]) add_devices([OpenexchangeratesSensor(rest, name, quote)])
@ -77,7 +81,10 @@ class OpenexchangeratesSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return other attributes of the sensor.""" """Return other attributes of the sensor."""
return self.rest.data attr = self.rest.data
attr[ATTR_ATTRIBUTION] = CONF_ATTRIBUTION
return attr
def update(self): def update(self):
"""Update current conditions.""" """Update current conditions."""
@ -91,11 +98,10 @@ class OpenexchangeratesData(object):
"""Get data from Openexchangerates.org.""" """Get data from Openexchangerates.org."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, resource, api_key, base, quote, data): def __init__(self, resource, parameters, quote):
"""Initialize the data object.""" """Initialize the data object."""
self._resource = resource self._resource = resource
self._api_key = api_key self._parameters = parameters
self._base = base
self._quote = quote self._quote = quote
self.data = None self.data = None
@ -103,12 +109,10 @@ class OpenexchangeratesData(object):
def update(self): def update(self):
"""Get the latest data from openexchangerates.org.""" """Get the latest data from openexchangerates.org."""
try: try:
result = requests.get(self._resource, params={'base': self._base, result = requests.get(
'app_id': self._resource, params=self._parameters, timeout=10)
self._api_key},
timeout=10)
self.data = result.json()['rates'] self.data = result.json()['rates']
except requests.exceptions.HTTPError: except requests.exceptions.HTTPError:
_LOGGER.error("Check the Openexchangerates API Key") _LOGGER.error("Check the Openexchangerates API key")
self.data = None self.data = None
return False return False

View File

@ -58,6 +58,7 @@ CONF_AFTER = 'after'
CONF_ALIAS = 'alias' CONF_ALIAS = 'alias'
CONF_API_KEY = 'api_key' CONF_API_KEY = 'api_key'
CONF_AUTHENTICATION = 'authentication' CONF_AUTHENTICATION = 'authentication'
CONF_BASE = 'base'
CONF_BEFORE = 'before' CONF_BEFORE = 'before'
CONF_BELOW = 'below' CONF_BELOW = 'below'
CONF_BLACKLIST = 'blacklist' CONF_BLACKLIST = 'blacklist'
@ -113,6 +114,7 @@ CONF_PIN = 'pin'
CONF_PLATFORM = 'platform' CONF_PLATFORM = 'platform'
CONF_PORT = 'port' CONF_PORT = 'port'
CONF_PREFIX = 'prefix' CONF_PREFIX = 'prefix'
CONF_QUOTE = 'quote'
CONF_RECIPIENT = 'recipient' CONF_RECIPIENT = 'recipient'
CONF_RESOURCE = 'resource' CONF_RESOURCE = 'resource'
CONF_RESOURCES = 'resources' CONF_RESOURCES = 'resources'