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
pull/4121/head
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
import logging
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_NAME, CONF_BASE, CONF_QUOTE, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity
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__)
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2)
CONF_BASE = 'base'
CONF_QUOTE = 'quote'
_RESOURCE = 'http://apilayer.net/api/live'
CONF_ATTRIBUTION = "Data provided by currencylayer.com"
DEFAULT_BASE = 'USD'
DEFAULT_NAME = 'CurrencyLayer Sensor'
ICON = 'mdi:currency'
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_QUOTE): vol.All(cv.ensure_list, [cv.string]),
@ -28,25 +38,22 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Currencylayer sensor."""
payload = config.get(CONF_PAYLOAD)
rest = CurrencylayerData(
_RESOURCE,
config.get(CONF_API_KEY),
config.get(CONF_BASE, 'USD'),
payload
)
response = requests.get(_RESOURCE, params={'source':
config.get(CONF_BASE, 'USD'),
'access_key':
config.get(CONF_API_KEY),
'format': 1}, timeout=10)
"""Set up the Currencylayer sensor."""
base = config.get(CONF_BASE)
api_key = config.get(CONF_API_KEY)
parameters = {
'source': base,
'access_key': api_key,
'format': 1,
}
rest = CurrencylayerData(_RESOURCE, parameters)
response = requests.get(_RESOURCE, params=parameters, timeout=10)
sensors = []
for variable in config['quote']:
sensors.append(CurrencylayerSensor(rest, config.get(CONF_BASE, 'USD'),
variable))
if "error" in response.json():
_LOGGER.error("Check your Currencylayer API")
sensors.append(CurrencylayerSensor(rest, base, variable))
if 'error' in response.json():
return False
else:
add_devices(sensors)
@ -66,7 +73,7 @@ class CurrencylayerSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return str(self._base) + str(self._quote)
return '{} {}'.format(self._base, self._quote)
@property
def icon(self):
@ -78,12 +85,20 @@ class CurrencylayerSensor(Entity):
"""Return the state of the sensor."""
return self._state
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
def update(self):
"""Update current conditions."""
"""Update current date."""
self.rest.update()
value = self.rest.data
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
@ -91,24 +106,20 @@ class CurrencylayerData(object):
"""Get data from Currencylayer.org."""
# pylint: disable=too-many-arguments
def __init__(self, resource, api_key, base, data):
def __init__(self, resource, parameters):
"""Initialize the data object."""
self._resource = resource
self._api_key = api_key
self._base = base
self._parameters = parameters
self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from Currencylayer."""
try:
result = requests.get(self._resource, params={'source': self._base,
'access_key':
self._api_key,
'format': 1},
timeout=10)
if "error" in result.json():
raise ValueError(result.json()["error"]["info"])
result = requests.get(
self._resource, params=self._parameters, timeout=10)
if 'error' in result.json():
raise ValueError(result.json()['error']['info'])
else:
self.data = result.json()['quotes']
_LOGGER.debug("Currencylayer data updated: %s",

View File

@ -10,7 +10,7 @@ from datetime import timedelta
import voluptuous as vol
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.util import Throttle
import homeassistant.helpers.config_validation as cv
@ -24,7 +24,6 @@ ATTR_EXCHANGE_RATE = 'Exchange rate'
ATTR_TARGET = 'Target currency'
CONF_ATTRIBUTION = "Data provided by the European Central Bank (ECB)"
CONF_BASE = 'base'
CONF_TARGET = 'target'
DEFAULT_BASE = 'USD'

View File

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

View File

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