mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Add signal strength sensor to Tile BLE (#193466)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
efd437c356
commit
bd67ebb87b
@@ -5,7 +5,7 @@ from homeassistant.core import HomeAssistant
|
||||
|
||||
from .coordinator import TileBleConfigEntry, TileBleCoordinator
|
||||
|
||||
PLATFORMS = [Platform.DEVICE_TRACKER]
|
||||
PLATFORMS = [Platform.DEVICE_TRACKER, Platform.SENSOR]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: TileBleConfigEntry) -> None:
|
||||
|
||||
@@ -75,15 +75,11 @@ rules:
|
||||
status: exempt
|
||||
comment: Each config entry represents a single Tile.
|
||||
entity-category: done
|
||||
entity-device-class:
|
||||
status: exempt
|
||||
comment: The device tracker has no device class.
|
||||
entity-disabled-by-default:
|
||||
status: exempt
|
||||
comment: All entities are useful for every Tile.
|
||||
entity-device-class: done
|
||||
entity-disabled-by-default: done
|
||||
entity-translations:
|
||||
status: exempt
|
||||
comment: The device tracker uses the device name.
|
||||
comment: The device tracker uses the device name and the sensor uses its device class name.
|
||||
exception-translations:
|
||||
status: exempt
|
||||
comment: This integration does not raise exceptions.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Sensor for the Tile BLE integration."""
|
||||
|
||||
from typing import override
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
BluetoothServiceInfoBleak,
|
||||
async_last_service_info,
|
||||
async_register_advertisement_callback,
|
||||
)
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.const import SIGNAL_STRENGTH_DECIBELS_MILLIWATT, EntityCategory
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import TileBleConfigEntry, TileBleCoordinator
|
||||
from .entity import TileBleEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: TileBleConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the Tile BLE sensor."""
|
||||
async_add_entities([TileBleSignalStrengthSensor(entry.runtime_data, entry.title)])
|
||||
|
||||
|
||||
class TileBleSignalStrengthSensor(TileBleEntity, SensorEntity):
|
||||
"""Reports the signal strength of the Tile's advertisements."""
|
||||
|
||||
_attr_device_class = SensorDeviceClass.SIGNAL_STRENGTH
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
_attr_entity_registry_enabled_default = False
|
||||
_attr_native_unit_of_measurement = SIGNAL_STRENGTH_DECIBELS_MILLIWATT
|
||||
_attr_state_class = SensorStateClass.MEASUREMENT
|
||||
|
||||
def __init__(self, coordinator: TileBleCoordinator, name: str) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator, name)
|
||||
self._attr_unique_id = f"{coordinator.address}_signal_strength"
|
||||
|
||||
@override
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Follow every advertisement, as the coordinator skips unchanged data."""
|
||||
await super().async_added_to_hass()
|
||||
if service_info := async_last_service_info(
|
||||
self.hass, self.coordinator.address, connectable=False
|
||||
):
|
||||
self._attr_native_value = service_info.rssi
|
||||
self.async_on_remove(
|
||||
async_register_advertisement_callback(
|
||||
self.hass, self._handle_advertisement, self.coordinator.address
|
||||
)
|
||||
)
|
||||
|
||||
@callback
|
||||
def _handle_advertisement(self, service_info: BluetoothServiceInfoBleak) -> None:
|
||||
"""Update the RSSI from an advertisement of the preferred source.
|
||||
|
||||
Every adapter and proxy that sees the Tile reports its advertisements,
|
||||
so taking the RSSI of all of them would make it jump between sources.
|
||||
"""
|
||||
preferred = async_last_service_info(
|
||||
self.hass, self.coordinator.address, connectable=False
|
||||
)
|
||||
if (
|
||||
preferred is not None and service_info.source != preferred.source
|
||||
) or service_info.rssi == self._attr_native_value:
|
||||
return
|
||||
self._attr_native_value = service_info.rssi
|
||||
self.async_write_ha_state()
|
||||
@@ -0,0 +1,56 @@
|
||||
# serializer version: 1
|
||||
# name: test_entities[sensor.tile_signal_strength-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry connections=[('bluetooth', 'AA:BB:CC:DD:EE:FF')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
|
||||
'entity_id': 'sensor.tile_signal_strength',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Signal strength',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.SIGNAL_STRENGTH: 'signal_strength'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Signal strength',
|
||||
'platform': 'tile_ble',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': 'AA:BB:CC:DD:EE:FF_signal_strength',
|
||||
'unit_of_measurement': 'dBm',
|
||||
})
|
||||
# ---
|
||||
# name: test_entities[sensor.tile_signal_strength-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'signal_strength',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Tile Signal strength',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: 'dBm',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.tile_signal_strength',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '-60',
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Tests for the Tile BLE sensor."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, snapshot_platform
|
||||
from pytest_homeassistant.components.bluetooth import (
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
inject_advertisement_with_source,
|
||||
inject_bluetooth_service_info,
|
||||
)
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from . import TILE_ADDRESS, TILE_SERVICE_INFO, setup_integration
|
||||
|
||||
ENTITY_ID = "sensor.tile_signal_strength"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def platforms() -> Generator[None]:
|
||||
"""Only set up the sensor platform."""
|
||||
with patch("homeassistant.components.tile_ble.PLATFORMS", [Platform.SENSOR]):
|
||||
yield
|
||||
|
||||
|
||||
def _inject_advertisement(hass: HomeAssistant, rssi: int, source: str) -> None:
|
||||
"""Inject an advertisement of the Tile with unchanged data."""
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
generate_ble_device(TILE_ADDRESS, TILE_SERVICE_INFO.name),
|
||||
generate_advertisement_data(
|
||||
local_name=TILE_SERVICE_INFO.name,
|
||||
service_data=TILE_SERVICE_INFO.service_data,
|
||||
service_uuids=TILE_SERVICE_INFO.service_uuids,
|
||||
rssi=rssi,
|
||||
),
|
||||
source,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_entities(
|
||||
hass: HomeAssistant,
|
||||
snapshot: SnapshotAssertion,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test the signal strength sensor."""
|
||||
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_signal_strength_updates(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test the sensor follows the RSSI when only the RSSI changes."""
|
||||
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
_inject_advertisement(hass, -80, TILE_SERVICE_INFO.source)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (state := hass.states.get(ENTITY_ID))
|
||||
assert state.state == "-80"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_signal_strength_other_source(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test an advertisement from a source that is not preferred is ignored."""
|
||||
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
_inject_advertisement(hass, -90, "proxy")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (state := hass.states.get(ENTITY_ID))
|
||||
assert state.state == "-60"
|
||||
Reference in New Issue
Block a user