mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 13:17:32 +00:00
Use voluptuous for exchange sensors (#2801)
* Use voluptuous for exchange sensors * Remove additional checks
This commit is contained in:
parent
dab5a78f88
commit
822b7f8770
@ -7,11 +7,16 @@ https://home-assistant.io/components/sensor.bitcoin/
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_DISPLAY_OPTIONS
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
|
||||
REQUIREMENTS = ['blockchain==1.3.3']
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
OPTION_TYPES = {
|
||||
'exchangerate': ['Exchange rate (1 BTC)', None],
|
||||
'trade_volume_btc': ['Trade volume', 'BTC'],
|
||||
@ -35,17 +40,27 @@ OPTION_TYPES = {
|
||||
'miners_revenue_btc': ['Miners revenue', 'BTC'],
|
||||
'market_price_usd': ['Market price', 'USD']
|
||||
}
|
||||
|
||||
ICON = 'mdi:currency-btc'
|
||||
CONF_CURRENCY = 'currency'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_DISPLAY_OPTIONS, default=[]):
|
||||
[vol.In(OPTION_TYPES)],
|
||||
vol.Optional(CONF_CURRENCY, default='USD'): cv.string,
|
||||
})
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Return cached results if last scan was less then this time ago.
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Setup the Bitcoin sensors."""
|
||||
from blockchain import exchangerates
|
||||
|
||||
currency = config.get('currency', 'USD')
|
||||
currency = config.get(CONF_CURRENCY)
|
||||
|
||||
if currency not in exchangerates.get_ticker():
|
||||
_LOGGER.error('Currency "%s" is not available. Using "USD"', currency)
|
||||
@ -53,11 +68,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
|
||||
data = BitcoinData()
|
||||
dev = []
|
||||
for variable in config['display_options']:
|
||||
if variable not in OPTION_TYPES:
|
||||
_LOGGER.error('Option type: "%s" does not exist', variable)
|
||||
else:
|
||||
dev.append(BitcoinSensor(data, variable, currency))
|
||||
for variable in config[CONF_DISPLAY_OPTIONS]:
|
||||
dev.append(BitcoinSensor(data, variable, currency))
|
||||
|
||||
add_devices(dev)
|
||||
|
||||
|
@ -6,47 +6,57 @@ https://home-assistant.io/components/sensor.openexchangerates/
|
||||
"""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import requests
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_API_KEY, CONF_NAME, CONF_PAYLOAD)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
|
||||
_RESOURCE = 'https://openexchangerates.org/api/latest.json'
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
# Return cached results if last scan was less then this time ago.
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=100)
|
||||
|
||||
CONF_BASE = 'base'
|
||||
CONF_QUOTE = 'quote'
|
||||
CONF_NAME = 'name'
|
||||
|
||||
DEFAULT_NAME = 'Exchange Rate Sensor'
|
||||
DEFAULT_BASE = 'USD'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_QUOTE): cv.string,
|
||||
vol.Optional(CONF_BASE, default=DEFAULT_BASE): cv.string,
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
})
|
||||
|
||||
# Return cached results if last scan was less then this time ago.
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Setup the Openexchangerates sensor."""
|
||||
payload = config.get('payload', None)
|
||||
rest = OpenexchangeratesData(
|
||||
_RESOURCE,
|
||||
config.get(CONF_API_KEY),
|
||||
config.get(CONF_BASE, 'USD'),
|
||||
config.get(CONF_QUOTE),
|
||||
payload
|
||||
)
|
||||
response = requests.get(_RESOURCE, params={'base': config.get(CONF_BASE,
|
||||
'USD'),
|
||||
'app_id':
|
||||
config.get(CONF_API_KEY)},
|
||||
"""Setup 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)
|
||||
if response.status_code != 200:
|
||||
_LOGGER.error("Check your OpenExchangeRates API")
|
||||
_LOGGER.error("Check your OpenExchangeRates API key")
|
||||
return False
|
||||
rest.update()
|
||||
add_devices([OpenexchangeratesSensor(rest, config.get(CONF_NAME,
|
||||
DEFAULT_NAME),
|
||||
config.get(CONF_QUOTE))])
|
||||
add_devices([OpenexchangeratesSensor(rest, name, quote)])
|
||||
|
||||
|
||||
class OpenexchangeratesSensor(Entity):
|
||||
"""Representation of an Openexchangerates sensor."""
|
||||
"""Representation of an Open Exchange Rates sensor."""
|
||||
|
||||
def __init__(self, rest, name, quote):
|
||||
"""Initialize the sensor."""
|
||||
@ -100,6 +110,6 @@ class OpenexchangeratesData(object):
|
||||
timeout=10)
|
||||
self.data = result.json()['rates']
|
||||
except requests.exceptions.HTTPError:
|
||||
_LOGGER.error("Check Openexchangerates API Key")
|
||||
_LOGGER.error("Check the Openexchangerates API Key")
|
||||
self.data = None
|
||||
return False
|
||||
|
@ -46,6 +46,7 @@ CONF_NAME = 'name'
|
||||
CONF_OFFSET = 'offset'
|
||||
CONF_OPTIMISTIC = 'optimistic'
|
||||
CONF_PASSWORD = 'password'
|
||||
CONF_PAYLOAD = 'payload'
|
||||
CONF_PENDING_TIME = 'pending_time'
|
||||
CONF_PLATFORM = 'platform'
|
||||
CONF_PORT = 'port'
|
||||
|
Loading…
x
Reference in New Issue
Block a user