mirror of
https://github.com/home-assistant/core.git
synced 2025-07-24 21:57:51 +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
|
import logging
|
||||||
from datetime import timedelta
|
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.helpers.entity import Entity
|
||||||
from homeassistant.util import Throttle
|
from homeassistant.util import Throttle
|
||||||
|
|
||||||
REQUIREMENTS = ['blockchain==1.3.3']
|
REQUIREMENTS = ['blockchain==1.3.3']
|
||||||
_LOGGER = logging.getLogger(__name__)
|
|
||||||
OPTION_TYPES = {
|
OPTION_TYPES = {
|
||||||
'exchangerate': ['Exchange rate (1 BTC)', None],
|
'exchangerate': ['Exchange rate (1 BTC)', None],
|
||||||
'trade_volume_btc': ['Trade volume', 'BTC'],
|
'trade_volume_btc': ['Trade volume', 'BTC'],
|
||||||
@ -35,17 +40,27 @@ OPTION_TYPES = {
|
|||||||
'miners_revenue_btc': ['Miners revenue', 'BTC'],
|
'miners_revenue_btc': ['Miners revenue', 'BTC'],
|
||||||
'market_price_usd': ['Market price', 'USD']
|
'market_price_usd': ['Market price', 'USD']
|
||||||
}
|
}
|
||||||
|
|
||||||
ICON = 'mdi:currency-btc'
|
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.
|
# 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):
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
"""Setup the Bitcoin sensors."""
|
"""Setup the Bitcoin sensors."""
|
||||||
from blockchain import exchangerates
|
from blockchain import exchangerates
|
||||||
|
|
||||||
currency = config.get('currency', 'USD')
|
currency = config.get(CONF_CURRENCY)
|
||||||
|
|
||||||
if currency not in exchangerates.get_ticker():
|
if currency not in exchangerates.get_ticker():
|
||||||
_LOGGER.error('Currency "%s" is not available. Using "USD"', currency)
|
_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()
|
data = BitcoinData()
|
||||||
dev = []
|
dev = []
|
||||||
for variable in config['display_options']:
|
for variable in config[CONF_DISPLAY_OPTIONS]:
|
||||||
if variable not in OPTION_TYPES:
|
dev.append(BitcoinSensor(data, variable, currency))
|
||||||
_LOGGER.error('Option type: "%s" does not exist', variable)
|
|
||||||
else:
|
|
||||||
dev.append(BitcoinSensor(data, variable, currency))
|
|
||||||
|
|
||||||
add_devices(dev)
|
add_devices(dev)
|
||||||
|
|
||||||
|
@ -6,47 +6,57 @@ https://home-assistant.io/components/sensor.openexchangerates/
|
|||||||
"""
|
"""
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import requests
|
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.helpers.entity import Entity
|
||||||
from homeassistant.util import Throttle
|
from homeassistant.util import Throttle
|
||||||
from homeassistant.const import CONF_API_KEY
|
|
||||||
|
|
||||||
_RESOURCE = 'https://openexchangerates.org/api/latest.json'
|
_RESOURCE = 'https://openexchangerates.org/api/latest.json'
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_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_BASE = 'base'
|
||||||
CONF_QUOTE = 'quote'
|
CONF_QUOTE = 'quote'
|
||||||
CONF_NAME = 'name'
|
|
||||||
DEFAULT_NAME = 'Exchange Rate Sensor'
|
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):
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
"""Setup the Openexchangerates sensor."""
|
"""Setup the Open Exchange Rates sensor."""
|
||||||
payload = config.get('payload', None)
|
name = config.get(CONF_NAME)
|
||||||
rest = OpenexchangeratesData(
|
api_key = config.get(CONF_API_KEY)
|
||||||
_RESOURCE,
|
base = config.get(CONF_BASE)
|
||||||
config.get(CONF_API_KEY),
|
quote = config.get(CONF_QUOTE)
|
||||||
config.get(CONF_BASE, 'USD'),
|
payload = config.get(CONF_PAYLOAD)
|
||||||
config.get(CONF_QUOTE),
|
|
||||||
payload
|
rest = OpenexchangeratesData(_RESOURCE, api_key, base, quote, payload)
|
||||||
)
|
response = requests.get(_RESOURCE, params={'base': base,
|
||||||
response = requests.get(_RESOURCE, params={'base': config.get(CONF_BASE,
|
'app_id': api_key},
|
||||||
'USD'),
|
|
||||||
'app_id':
|
|
||||||
config.get(CONF_API_KEY)},
|
|
||||||
timeout=10)
|
timeout=10)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
_LOGGER.error("Check your OpenExchangeRates API")
|
_LOGGER.error("Check your OpenExchangeRates API key")
|
||||||
return False
|
return False
|
||||||
rest.update()
|
rest.update()
|
||||||
add_devices([OpenexchangeratesSensor(rest, config.get(CONF_NAME,
|
add_devices([OpenexchangeratesSensor(rest, name, quote)])
|
||||||
DEFAULT_NAME),
|
|
||||||
config.get(CONF_QUOTE))])
|
|
||||||
|
|
||||||
|
|
||||||
class OpenexchangeratesSensor(Entity):
|
class OpenexchangeratesSensor(Entity):
|
||||||
"""Representation of an Openexchangerates sensor."""
|
"""Representation of an Open Exchange Rates sensor."""
|
||||||
|
|
||||||
def __init__(self, rest, name, quote):
|
def __init__(self, rest, name, quote):
|
||||||
"""Initialize the sensor."""
|
"""Initialize the sensor."""
|
||||||
@ -100,6 +110,6 @@ class OpenexchangeratesData(object):
|
|||||||
timeout=10)
|
timeout=10)
|
||||||
self.data = result.json()['rates']
|
self.data = result.json()['rates']
|
||||||
except requests.exceptions.HTTPError:
|
except requests.exceptions.HTTPError:
|
||||||
_LOGGER.error("Check Openexchangerates API Key")
|
_LOGGER.error("Check the Openexchangerates API Key")
|
||||||
self.data = None
|
self.data = None
|
||||||
return False
|
return False
|
||||||
|
@ -46,6 +46,7 @@ CONF_NAME = 'name'
|
|||||||
CONF_OFFSET = 'offset'
|
CONF_OFFSET = 'offset'
|
||||||
CONF_OPTIMISTIC = 'optimistic'
|
CONF_OPTIMISTIC = 'optimistic'
|
||||||
CONF_PASSWORD = 'password'
|
CONF_PASSWORD = 'password'
|
||||||
|
CONF_PAYLOAD = 'payload'
|
||||||
CONF_PENDING_TIME = 'pending_time'
|
CONF_PENDING_TIME = 'pending_time'
|
||||||
CONF_PLATFORM = 'platform'
|
CONF_PLATFORM = 'platform'
|
||||||
CONF_PORT = 'port'
|
CONF_PORT = 'port'
|
||||||
|
Loading…
x
Reference in New Issue
Block a user