Give the Bitcoin sensors proper names, icons and a device (#188579)

This commit is contained in:
Juri Calleri
2026-10-28 18:48:00 +01:00
committed by GitHub
parent 8f980b770d
commit eae2da37de
7 changed files with 636 additions and 489 deletions
@@ -6,7 +6,7 @@ from blockchain import exchangerates
import probatio
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_CURRENCY, CONF_DISPLAY_OPTIONS
from homeassistant.const import CONF_CURRENCY
from homeassistant.core import HomeAssistant
from homeassistant.helpers.selector import (
SelectSelector,
@@ -83,8 +83,5 @@ class BitcoinConfigFlow(ConfigFlow, domain=DOMAIN):
return self.async_create_entry(
title=INTEGRATION_TITLE,
data={
CONF_CURRENCY: currency,
CONF_DISPLAY_OPTIONS: import_data[CONF_DISPLAY_OPTIONS],
},
data={CONF_CURRENCY: currency},
)
@@ -0,0 +1,69 @@
{
"entity": {
"sensor": {
"blocks_size": {
"default": "mdi:database"
},
"btc_mined": {
"default": "mdi:pickaxe"
},
"difficulty": {
"default": "mdi:chart-bell-curve"
},
"estimated_btc_sent": {
"default": "mdi:send"
},
"estimated_transaction_volume_usd": {
"default": "mdi:cash-multiple"
},
"exchangerate": {
"default": "mdi:currency-btc"
},
"hash_rate": {
"default": "mdi:speedometer"
},
"market_price_usd": {
"default": "mdi:cash"
},
"mined_blocks": {
"default": "mdi:cube-outline"
},
"miners_revenue_btc": {
"default": "mdi:pickaxe"
},
"miners_revenue_usd": {
"default": "mdi:pickaxe"
},
"minutes_between_blocks": {
"default": "mdi:timer-outline"
},
"next_retarget": {
"default": "mdi:target"
},
"number_of_transactions": {
"default": "mdi:swap-horizontal"
},
"timestamp": {
"default": "mdi:clock-outline"
},
"total_blocks": {
"default": "mdi:cube-outline"
},
"total_btc": {
"default": "mdi:currency-btc"
},
"total_btc_sent": {
"default": "mdi:send"
},
"total_fees_btc": {
"default": "mdi:cash-minus"
},
"trade_volume_btc": {
"default": "mdi:chart-line"
},
"trade_volume_usd": {
"default": "mdi:chart-line"
}
}
}
}
+33 -30
View File
@@ -15,6 +15,7 @@ from homeassistant.const import CONF_CURRENCY, CONF_DISPLAY_OPTIONS, UnitOfTime
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import (
AddConfigEntryEntitiesCallback,
AddEntitiesCallback,
@@ -35,99 +36,99 @@ PARALLEL_UPDATES = 0
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="exchangerate",
name="Exchange rate (1 BTC)",
translation_key="exchangerate",
),
SensorEntityDescription(
key="trade_volume_btc",
name="Trade volume",
translation_key="trade_volume_btc",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="miners_revenue_usd",
name="Miners revenue",
translation_key="miners_revenue_usd",
native_unit_of_measurement="USD",
),
SensorEntityDescription(
key="btc_mined",
name="Mined",
translation_key="btc_mined",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="trade_volume_usd",
name="Trade volume",
translation_key="trade_volume_usd",
native_unit_of_measurement="USD",
),
SensorEntityDescription(
key="difficulty",
name="Difficulty",
translation_key="difficulty",
),
SensorEntityDescription(
key="minutes_between_blocks",
name="Time between Blocks",
translation_key="minutes_between_blocks",
native_unit_of_measurement=UnitOfTime.MINUTES,
),
SensorEntityDescription(
key="number_of_transactions",
name="No. of Transactions",
translation_key="number_of_transactions",
),
SensorEntityDescription(
key="hash_rate",
name="Hash rate",
translation_key="hash_rate",
native_unit_of_measurement=f"PH/{UnitOfTime.SECONDS}",
),
SensorEntityDescription(
key="timestamp",
name="Timestamp",
translation_key="timestamp",
),
SensorEntityDescription(
key="mined_blocks",
name="Mined Blocks",
translation_key="mined_blocks",
),
SensorEntityDescription(
key="blocks_size",
name="Block size",
translation_key="blocks_size",
),
SensorEntityDescription(
key="total_fees_btc",
name="Total fees",
translation_key="total_fees_btc",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="total_btc_sent",
name="Total sent",
translation_key="total_btc_sent",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="estimated_btc_sent",
name="Estimated sent",
translation_key="estimated_btc_sent",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="total_btc",
name="Total",
translation_key="total_btc",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="total_blocks",
name="Total Blocks",
translation_key="total_blocks",
),
SensorEntityDescription(
key="next_retarget",
name="Next retarget",
translation_key="next_retarget",
),
SensorEntityDescription(
key="estimated_transaction_volume_usd",
name="Est. Transaction volume",
translation_key="estimated_transaction_volume_usd",
native_unit_of_measurement="USD",
),
SensorEntityDescription(
key="miners_revenue_btc",
name="Miners revenue",
translation_key="miners_revenue_btc",
native_unit_of_measurement="BTC",
),
SensorEntityDescription(
key="market_price_usd",
name="Market price",
translation_key="market_price_usd",
native_unit_of_measurement="USD",
),
)
@@ -223,15 +224,9 @@ async def async_setup_entry(
if currency not in coordinator.data.ticker:
_LOGGER.warning("Currency %s is not available. Using USD", currency)
# Two sensors share each of the names Trade volume and Miners revenue, and
# only the first one created gets the plain entity ID. Creating the sensors
# an imported YAML setup already had first keeps their entity IDs.
previous = entry.data.get(CONF_DISPLAY_OPTIONS, [])
async_add_entities(
BitcoinSensor(coordinator, currency, description)
for description in sorted(
SENSOR_TYPES, key=lambda description: description.key not in previous
)
for description in SENSOR_TYPES
)
@@ -239,7 +234,7 @@ class BitcoinSensor(CoordinatorEntity[BitcoinDataUpdateCoordinator], SensorEntit
"""Representation of a Bitcoin sensor."""
_attr_attribution = "Data provided by blockchain.com"
_attr_icon = "mdi:currency-btc"
_attr_has_entity_name = True
def __init__(
self,
@@ -250,7 +245,15 @@ class BitcoinSensor(CoordinatorEntity[BitcoinDataUpdateCoordinator], SensorEntit
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_{description.key}"
entry = coordinator.config_entry
self._attr_unique_id = f"{entry.entry_id}_{description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.entry_id)},
entry_type=DeviceEntryType.SERVICE,
manufacturer="Blockchain.com",
name=INTEGRATION_TITLE,
configuration_url="https://www.blockchain.com/explorer",
)
self._currency = currency
self._update_from_data()
@@ -15,6 +15,76 @@
}
}
},
"entity": {
"sensor": {
"blocks_size": {
"name": "Blocks size"
},
"btc_mined": {
"name": "Mined"
},
"difficulty": {
"name": "Difficulty"
},
"estimated_btc_sent": {
"name": "Estimated sent"
},
"estimated_transaction_volume_usd": {
"name": "Estimated transaction volume"
},
"exchangerate": {
"name": "Exchange rate"
},
"hash_rate": {
"name": "Hash rate"
},
"market_price_usd": {
"name": "Market price"
},
"mined_blocks": {
"name": "Mined blocks",
"unit_of_measurement": "blocks"
},
"miners_revenue_btc": {
"name": "Miners revenue"
},
"miners_revenue_usd": {
"name": "Miners revenue in USD"
},
"minutes_between_blocks": {
"name": "Time between blocks"
},
"next_retarget": {
"name": "Next retarget"
},
"number_of_transactions": {
"name": "Transactions",
"unit_of_measurement": "transactions"
},
"timestamp": {
"name": "Statistics timestamp"
},
"total_blocks": {
"name": "Total blocks",
"unit_of_measurement": "[%key:component::bitcoin::entity::sensor::mined_blocks::unit_of_measurement%]"
},
"total_btc": {
"name": "Total supply"
},
"total_btc_sent": {
"name": "Total sent"
},
"total_fees_btc": {
"name": "Total fees"
},
"trade_volume_btc": {
"name": "Trade volume"
},
"trade_volume_usd": {
"name": "Trade volume in USD"
}
}
},
"issues": {
"deprecated_yaml_import_issue_cannot_connect": {
"description": "Configuring {integration_title} using YAML is being removed.\n\nWhile importing your YAML configuration, Home Assistant could not reach blockchain.com. Check your internet connection and restart Home Assistant to try again, or remove the `{domain}` sensor platform from your `configuration.yaml` file and set the integration up from the UI.",
File diff suppressed because it is too large Load Diff
+2 -8
View File
@@ -84,10 +84,7 @@ async def test_import_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) ->
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Bitcoin"
assert result["data"] == {
CONF_CURRENCY: "EUR",
CONF_DISPLAY_OPTIONS: ["exchangerate"],
}
assert result["data"] == {CONF_CURRENCY: "EUR"}
assert len(mock_setup_entry.mock_calls) == 1
@@ -100,10 +97,7 @@ async def test_import_flow_lowercase_currency(hass: HomeAssistant) -> None:
data={**YAML_CONFIG, CONF_CURRENCY: "eur"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_CURRENCY: "EUR",
CONF_DISPLAY_OPTIONS: ["exchangerate"],
}
assert result["data"] == {CONF_CURRENCY: "EUR"}
@pytest.mark.usefixtures("mock_setup_entry")
+45 -43
View File
@@ -1,5 +1,6 @@
"""Tests for the Bitcoin sensor platform."""
import logging
from unittest.mock import MagicMock
from blockchain.exchangerates import Currency
@@ -17,18 +18,23 @@ from homeassistant.components.bitcoin.coordinator import SCAN_INTERVAL
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import SOURCE_IGNORE
from homeassistant.const import (
ATTR_FRIENDLY_NAME,
ATTR_UNIT_OF_MEASUREMENT,
CONF_CURRENCY,
CONF_DISPLAY_OPTIONS,
STATE_UNAVAILABLE,
)
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.helpers import (
device_registry as dr,
entity_registry as er,
issue_registry as ir,
)
from homeassistant.setup import async_setup_component
from . import setup_integration
ENTITY_EXCHANGE_RATE = "sensor.exchange_rate_1_btc"
ENTITY_EXCHANGE_RATE = "sensor.bitcoin_exchange_rate"
YAML_CONFIG = {
SENSOR_DOMAIN: {
@@ -164,7 +170,7 @@ async def test_yaml_import(
await hass.async_block_till_done()
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert entry.data == {CONF_CURRENCY: "EUR", CONF_DISPLAY_OPTIONS: ["exchangerate"]}
assert entry.data == {CONF_CURRENCY: "EUR"}
assert issue_registry.async_get_issue(
HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}"
)
@@ -286,47 +292,43 @@ async def test_yaml_import_with_ignored_entry(
)
@pytest.mark.parametrize(
("display_options", "expected"),
[
pytest.param(
["trade_volume_usd"], {"sensor.trade_volume": "USD"}, id="trade_volume_usd"
),
pytest.param(
["trade_volume_btc"], {"sensor.trade_volume": "BTC"}, id="trade_volume_btc"
),
pytest.param(
["trade_volume_btc", "trade_volume_usd"],
{"sensor.trade_volume": "BTC", "sensor.trade_volume_2": "USD"},
id="both_trade_volumes",
),
pytest.param(
["miners_revenue_btc"],
{"sensor.miners_revenue": "BTC"},
id="miners_revenue_btc",
),
pytest.param(
["miners_revenue_usd"],
{"sensor.miners_revenue": "USD"},
id="miners_revenue_usd",
),
],
)
@pytest.mark.usefixtures("mock_statistics", "mock_exchangerates")
async def test_imported_sensors_keep_their_entity_ids(
hass: HomeAssistant, display_options: list[str], expected: dict[str, str]
async def test_registered_sensors_keep_their_entity_ids(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sensors an imported YAML setup had keep the entity ID they had.
The expected values are what the YAML platform created for these
display_options before the config flow existed.
"""
entry = MockConfigEntry(
domain=DOMAIN,
title="Bitcoin",
data={CONF_CURRENCY: "USD", CONF_DISPLAY_OPTIONS: display_options},
"""Test sensors that are already registered keep their entity ID and name it."""
mock_config_entry.add_to_hass(hass)
entity_registry.async_get_or_create(
SENSOR_DOMAIN,
DOMAIN,
f"{mock_config_entry.entry_id}_exchangerate",
suggested_object_id="exchange_rate_1_btc",
config_entry=mock_config_entry,
)
await setup_integration(hass, entry)
for entity_id, unit in expected.items():
assert hass.states.get(entity_id).attributes[ATTR_UNIT_OF_MEASUREMENT] == unit
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.exchange_rate_1_btc")
assert state.attributes[ATTR_FRIENDLY_NAME] == "Bitcoin Exchange rate"
assert hass.states.get(ENTITY_EXCHANGE_RATE) is None
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
@pytest.mark.usefixtures("mock_statistics", "mock_exchangerates")
async def test_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the sensors belong to one Bitcoin service device."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device_by_identifier(
(DOMAIN, mock_config_entry.entry_id), mock_config_entry.entry_id
)
assert device == snapshot