core/homeassistant/components/sensor/bitcoin.py

185 lines
6.6 KiB
Python
Raw Normal View History

2015-05-15 13:19:49 +00:00
"""
2016-03-24 11:37:40 +00:00
Bitcoin information service that uses blockchain.info.
2015-05-15 13:19:49 +00:00
2015-10-13 21:49:28 +00:00
For more details about this platform, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/sensor.bitcoin/
2015-05-15 13:19:49 +00:00
"""
import logging
from datetime import timedelta
2015-05-15 13:19:49 +00:00
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
2015-05-15 13:19:49 +00:00
from homeassistant.helpers.entity import Entity
2016-02-19 05:27:50 +00:00
from homeassistant.util import Throttle
2015-05-15 13:19:49 +00:00
2016-06-04 10:55:46 +00:00
REQUIREMENTS = ['blockchain==1.3.3']
_LOGGER = logging.getLogger(__name__)
CONF_CURRENCY = 'currency'
DEFAULT_CURRENCY = 'USD'
ICON = 'mdi:currency-btc'
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
2015-05-15 13:19:49 +00:00
OPTION_TYPES = {
2016-01-18 01:50:20 +00:00
'exchangerate': ['Exchange rate (1 BTC)', None],
2015-05-15 13:19:49 +00:00
'trade_volume_btc': ['Trade volume', 'BTC'],
'miners_revenue_usd': ['Miners revenue', 'USD'],
'btc_mined': ['Mined', 'BTC'],
'trade_volume_usd': ['Trade volume', 'USD'],
2016-01-18 01:50:20 +00:00
'difficulty': ['Difficulty', None],
2015-05-15 13:19:49 +00:00
'minutes_between_blocks': ['Time between Blocks', 'min'],
2016-01-18 01:50:20 +00:00
'number_of_transactions': ['No. of Transactions', None],
2015-05-15 13:19:49 +00:00
'hash_rate': ['Hash rate', 'PH/s'],
2016-01-18 01:50:20 +00:00
'timestamp': ['Timestamp', None],
'mined_blocks': ['Minded Blocks', None],
'blocks_size': ['Block size', None],
2015-05-15 13:19:49 +00:00
'total_fees_btc': ['Total fees', 'BTC'],
'total_btc_sent': ['Total sent', 'BTC'],
'estimated_btc_sent': ['Estimated sent', 'BTC'],
'total_btc': ['Total', 'BTC'],
2016-01-18 01:50:20 +00:00
'total_blocks': ['Total Blocks', None],
'next_retarget': ['Next retarget', None],
2015-05-15 13:19:49 +00:00
'estimated_transaction_volume_usd': ['Est. Transaction volume', 'USD'],
'miners_revenue_btc': ['Miners revenue', 'BTC'],
'market_price_usd': ['Market price', 'USD']
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DISPLAY_OPTIONS, default=[]):
vol.All(cv.ensure_list, [vol.In(OPTION_TYPES)]),
vol.Optional(CONF_CURRENCY, default=DEFAULT_CURRENCY): cv.string,
})
2015-05-15 13:19:49 +00:00
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-03-24 11:37:40 +00:00
"""Setup the Bitcoin sensors."""
from blockchain import exchangerates
2015-05-15 13:19:49 +00:00
currency = config.get(CONF_CURRENCY)
2015-05-15 13:19:49 +00:00
if currency not in exchangerates.get_ticker():
_LOGGER.warning('Currency "%s" is not available. Using "USD"',
currency)
currency = DEFAULT_CURRENCY
2015-05-15 13:19:49 +00:00
2015-05-18 21:38:46 +00:00
data = BitcoinData()
2015-05-15 13:19:49 +00:00
dev = []
for variable in config[CONF_DISPLAY_OPTIONS]:
dev.append(BitcoinSensor(data, variable, currency))
2015-05-15 13:19:49 +00:00
add_devices(dev)
# pylint: disable=too-few-public-methods
class BitcoinSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Representation of a Bitcoin sensor."""
2016-03-24 11:37:40 +00:00
def __init__(self, data, option_type, currency):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
2015-05-18 21:38:46 +00:00
self.data = data
2015-05-15 13:19:49 +00:00
self._name = OPTION_TYPES[option_type][0]
self._unit_of_measurement = OPTION_TYPES[option_type][1]
self._currency = currency
self.type = option_type
self._state = None
self.update()
@property
def name(self):
2016-03-08 15:46:34 +00:00
"""Return the name of the sensor."""
2015-05-15 13:19:49 +00:00
return self._name
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the sensor."""
2015-05-15 13:19:49 +00:00
return self._state
@property
def unit_of_measurement(self):
2016-03-08 15:46:34 +00:00
"""Return the unit the value is expressed in."""
2015-05-15 13:19:49 +00:00
return self._unit_of_measurement
2016-02-05 12:13:37 +00:00
@property
def icon(self):
2016-03-08 15:46:34 +00:00
"""Return the icon to use in the frontend, if any."""
2016-02-05 12:13:37 +00:00
return ICON
2015-05-15 13:19:49 +00:00
# pylint: disable=too-many-branches
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data and updates the states."""
2015-05-18 21:38:46 +00:00
self.data.update()
stats = self.data.stats
ticker = self.data.ticker
2015-05-15 13:19:49 +00:00
# pylint: disable=no-member
2016-03-24 11:37:40 +00:00
if self.type == 'exchangerate':
2015-05-15 13:19:49 +00:00
self._state = ticker[self._currency].p15min
self._unit_of_measurement = self._currency
elif self.type == 'trade_volume_btc':
self._state = '{0:.1f}'.format(stats.trade_volume_btc)
elif self.type == 'miners_revenue_usd':
self._state = '{0:.0f}'.format(stats.miners_revenue_usd)
elif self.type == 'btc_mined':
self._state = '{}'.format(stats.btc_mined * 0.00000001)
elif self.type == 'trade_volume_usd':
self._state = '{0:.1f}'.format(stats.trade_volume_usd)
elif self.type == 'difficulty':
self._state = '{0:.0f}'.format(stats.difficulty)
elif self.type == 'minutes_between_blocks':
self._state = '{0:.2f}'.format(stats.minutes_between_blocks)
elif self.type == 'number_of_transactions':
self._state = '{}'.format(stats.number_of_transactions)
elif self.type == 'hash_rate':
self._state = '{0:.1f}'.format(stats.hash_rate * 0.000001)
elif self.type == 'timestamp':
self._state = stats.timestamp
elif self.type == 'mined_blocks':
self._state = '{}'.format(stats.mined_blocks)
elif self.type == 'blocks_size':
self._state = '{0:.1f}'.format(stats.blocks_size)
elif self.type == 'total_fees_btc':
self._state = '{0:.2f}'.format(stats.total_fees_btc * 0.00000001)
elif self.type == 'total_btc_sent':
self._state = '{0:.2f}'.format(stats.total_btc_sent * 0.00000001)
elif self.type == 'estimated_btc_sent':
self._state = '{0:.2f}'.format(stats.estimated_btc_sent *
0.00000001)
elif self.type == 'total_btc':
self._state = '{0:.2f}'.format(stats.total_btc * 0.00000001)
elif self.type == 'total_blocks':
self._state = '{0:.2f}'.format(stats.total_blocks)
elif self.type == 'next_retarget':
self._state = '{0:.2f}'.format(stats.next_retarget)
elif self.type == 'estimated_transaction_volume_usd':
self._state = '{0:.2f}'.format(
stats.estimated_transaction_volume_usd)
elif self.type == 'miners_revenue_btc':
self._state = '{0:.1f}'.format(stats.miners_revenue_btc *
0.00000001)
elif self.type == 'market_price_usd':
self._state = '{0:.2f}'.format(stats.market_price_usd)
2015-05-18 21:38:46 +00:00
2015-05-20 16:27:43 +00:00
2015-05-18 21:38:46 +00:00
class BitcoinData(object):
2016-03-08 15:46:34 +00:00
"""Get the latest data and update the states."""
2015-05-18 21:38:46 +00:00
def __init__(self):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
2015-05-18 21:38:46 +00:00
self.stats = None
self.ticker = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from blockchain.info."""
2015-05-20 16:27:43 +00:00
from blockchain import statistics, exchangerates
2015-05-18 21:38:46 +00:00
self.stats = statistics.get()
self.ticker = exchangerates.get_ticker()