Sync crypto-currency platforms (#7906)

This commit is contained in:
Fabian Affolter 2017-06-05 13:36:39 +02:00 committed by GitHub
parent 12f731b32c
commit f8cfa15152
5 changed files with 79 additions and 37 deletions

View File

@ -10,23 +10,22 @@ 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_DISPLAY_OPTIONS, ATTR_ATTRIBUTION) from homeassistant.const import (
CONF_DISPLAY_OPTIONS, ATTR_ATTRIBUTION, CONF_CURRENCY)
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
REQUIREMENTS = ['blockchain==1.3.3'] REQUIREMENTS = ['blockchain==1.3.3']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CONF_ATTRIBUTION = "Data provided by blockchain.info" CONF_ATTRIBUTION = "Data provided by blockchain.info"
CONF_CURRENCY = 'currency'
DEFAULT_CURRENCY = 'USD' DEFAULT_CURRENCY = 'USD'
ICON = 'mdi:currency-btc' ICON = 'mdi:currency-btc'
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) SCAN_INTERVAL = timedelta(minutes=5)
OPTION_TYPES = { OPTION_TYPES = {
'exchangerate': ['Exchange rate (1 BTC)', None], 'exchangerate': ['Exchange rate (1 BTC)', None],
@ -74,7 +73,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
for variable in config[CONF_DISPLAY_OPTIONS]: for variable in config[CONF_DISPLAY_OPTIONS]:
dev.append(BitcoinSensor(data, variable, currency)) dev.append(BitcoinSensor(data, variable, currency))
add_devices(dev) add_devices(dev, True)
class BitcoinSensor(Entity): class BitcoinSensor(Entity):
@ -88,7 +87,6 @@ class BitcoinSensor(Entity):
self._currency = currency self._currency = currency
self.type = option_type self.type = option_type
self._state = None self._state = None
self.update()
@property @property
def name(self): def name(self):
@ -154,8 +152,8 @@ class BitcoinSensor(Entity):
elif self.type == 'total_btc_sent': elif self.type == 'total_btc_sent':
self._state = '{0:.2f}'.format(stats.total_btc_sent * 0.00000001) self._state = '{0:.2f}'.format(stats.total_btc_sent * 0.00000001)
elif self.type == 'estimated_btc_sent': elif self.type == 'estimated_btc_sent':
self._state = '{0:.2f}'.format(stats.estimated_btc_sent * self._state = '{0:.2f}'.format(
0.00000001) stats.estimated_btc_sent * 0.00000001)
elif self.type == 'total_btc': elif self.type == 'total_btc':
self._state = '{0:.2f}'.format(stats.total_btc * 0.00000001) self._state = '{0:.2f}'.format(stats.total_btc * 0.00000001)
elif self.type == 'total_blocks': elif self.type == 'total_blocks':
@ -166,8 +164,8 @@ class BitcoinSensor(Entity):
self._state = '{0:.2f}'.format( self._state = '{0:.2f}'.format(
stats.estimated_transaction_volume_usd) stats.estimated_transaction_volume_usd)
elif self.type == 'miners_revenue_btc': elif self.type == 'miners_revenue_btc':
self._state = '{0:.1f}'.format(stats.miners_revenue_btc * self._state = '{0:.1f}'.format(
0.00000001) stats.miners_revenue_btc * 0.00000001)
elif self.type == 'market_price_usd': elif self.type == 'market_price_usd':
self._state = '{0:.2f}'.format(stats.market_price_usd) self._state = '{0:.2f}'.format(stats.market_price_usd)
@ -180,7 +178,6 @@ class BitcoinData(object):
self.stats = None self.stats = None
self.ticker = None self.ticker = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
"""Get the latest data from blockchain.info.""" """Get the latest data from blockchain.info."""
from blockchain import statistics, exchangerates from blockchain import statistics, exchangerates

View File

@ -5,33 +5,51 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.blockchain/ https://home-assistant.io/components/sensor.blockchain/
""" """
import logging import logging
from homeassistant.components.sensor import PLATFORM_SCHEMA from datetime import timedelta
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['python-blockchain-api==0.0.2'] REQUIREMENTS = ['python-blockchain-api==0.0.2']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CONF_ADDRESSES = 'addresses' CONF_ADDRESSES = 'addresses'
CONF_ATTRIBUTION = "Data provided by blockchain.info"
DEFAULT_NAME = 'Bitcoin Balance'
ICON = 'mdi:currency-btc'
SCAN_INTERVAL = timedelta(minutes=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ADDRESSES): [cv.string] vol.Required(CONF_ADDRESSES): [cv.string],
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}) })
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the blockchain sensors.""" """Set up the Blockchain.info sensors."""
from pyblockchain import validate_address from pyblockchain import validate_address
addresses = config.get(CONF_ADDRESSES) addresses = config.get(CONF_ADDRESSES)
name = config.get(CONF_NAME)
for address in addresses: for address in addresses:
if not validate_address(address): if not validate_address(address):
_LOGGER.error("Bitcoin address is not valid: " + address) _LOGGER.error("Bitcoin address is not valid: %s", address)
return False return False
add_devices([BlockchainSensor('Bitcoin Balance', addresses)])
add_devices([BlockchainSensor(name, addresses)], True)
class BlockchainSensor(Entity): class BlockchainSensor(Entity):
"""Representation of a blockchain.info sensor.""" """Representation of a Blockchain.info sensor."""
def __init__(self, name, addresses): def __init__(self, name, addresses):
"""Initialize the sensor.""" """Initialize the sensor."""
@ -39,7 +57,6 @@ class BlockchainSensor(Entity):
self.addresses = addresses self.addresses = addresses
self._state = None self._state = None
self._unit_of_measurement = 'BTC' self._unit_of_measurement = 'BTC'
self.update()
@property @property
def name(self): def name(self):
@ -56,6 +73,18 @@ class BlockchainSensor(Entity):
"""Return the unit of measurement this sensor expresses itself in.""" """Return the unit of measurement this sensor expresses itself in."""
return self._unit_of_measurement return self._unit_of_measurement
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
def update(self): def update(self):
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
from pyblockchain import get_balance from pyblockchain import get_balance

View File

@ -11,11 +11,10 @@ from urllib.error import HTTPError
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['coinmarketcap==2.0.1'] REQUIREMENTS = ['coinmarketcap==2.0.1']
@ -32,13 +31,12 @@ ATTR_SYMBOL = 'symbol'
ATTR_TOTAL_SUPPLY = 'total_supply' ATTR_TOTAL_SUPPLY = 'total_supply'
CONF_ATTRIBUTION = "Data provided by CoinMarketCap" CONF_ATTRIBUTION = "Data provided by CoinMarketCap"
CONF_CURRENCY = 'currency'
DEFAULT_CURRENCY = 'bitcoin' DEFAULT_CURRENCY = 'bitcoin'
ICON = 'mdi:currency-usd' ICON = 'mdi:currency-usd'
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) SCAN_INTERVAL = timedelta(minutes=15)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_CURRENCY, default=DEFAULT_CURRENCY): cv.string, vol.Optional(CONF_CURRENCY, default=DEFAULT_CURRENCY): cv.string,
@ -56,7 +54,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
currency) currency)
currency = DEFAULT_CURRENCY currency = DEFAULT_CURRENCY
add_devices([CoinMarketCapSensor(CoinMarketCapData(currency))]) add_devices([CoinMarketCapSensor(CoinMarketCapData(currency))], True)
class CoinMarketCapSensor(Entity): class CoinMarketCapSensor(Entity):
@ -67,7 +65,6 @@ class CoinMarketCapSensor(Entity):
self.data = data self.data = data
self._ticker = None self._ticker = None
self._unit_of_measurement = 'USD' self._unit_of_measurement = 'USD'
self.update()
@property @property
def name(self): def name(self):
@ -118,7 +115,6 @@ class CoinMarketCapData(object):
self.currency = currency self.currency = currency
self.ticker = None self.ticker = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
"""Get the latest data from blockchain.info.""" """Get the latest data from blockchain.info."""
from coinmarketcap import Market from coinmarketcap import Market

View File

@ -4,23 +4,36 @@ Support for Etherscan sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.etherscan/ https://home-assistant.io/components/sensor.etherscan/
""" """
from homeassistant.components.sensor import PLATFORM_SCHEMA from datetime import timedelta
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['python-etherscan-api==0.0.1'] REQUIREMENTS = ['python-etherscan-api==0.0.1']
CONF_ADDRESS = 'address' CONF_ADDRESS = 'address'
CONF_ATTRIBUTION = "Data provided by etherscan.io"
DEFAULT_NAME = 'Ethereum Balance'
SCAN_INTERVAL = timedelta(minutes=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ADDRESS): cv.string vol.Required(CONF_ADDRESS): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}) })
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the etherscan sensors.""" """Set up the Etherscan.io sensors."""
add_devices([EtherscanSensor('Ethereum Balance', address = config.get(CONF_ADDRESS)
config.get(CONF_ADDRESS))]) name = config.get(CONF_NAME)
add_devices([EtherscanSensor(name, address)], True)
class EtherscanSensor(Entity): class EtherscanSensor(Entity):
@ -32,7 +45,6 @@ class EtherscanSensor(Entity):
self.address = address self.address = address
self._state = None self._state = None
self._unit_of_measurement = 'ETH' self._unit_of_measurement = 'ETH'
self.update()
@property @property
def name(self): def name(self):
@ -49,6 +61,13 @@ class EtherscanSensor(Entity):
"""Return the unit of measurement this sensor expresses itself in.""" """Return the unit of measurement this sensor expresses itself in."""
return self._unit_of_measurement return self._unit_of_measurement
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
def update(self): def update(self):
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
from pyetherscan import get_balance from pyetherscan import get_balance

View File

@ -78,6 +78,7 @@ CONF_COMMAND_STATE = 'command_state'
CONF_COMMAND_STOP = 'command_stop' CONF_COMMAND_STOP = 'command_stop'
CONF_CONDITION = 'condition' CONF_CONDITION = 'condition'
CONF_COVERS = 'covers' CONF_COVERS = 'covers'
CONF_CURRENCY = 'currency'
CONF_CUSTOMIZE = 'customize' CONF_CUSTOMIZE = 'customize'
CONF_CUSTOMIZE_DOMAIN = 'customize_domain' CONF_CUSTOMIZE_DOMAIN = 'customize_domain'
CONF_CUSTOMIZE_GLOB = 'customize_glob' CONF_CUSTOMIZE_GLOB = 'customize_glob'