From bd67ebb87bfe96be1ceb265f93c9ac039b83c3fb Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Tue, 24 Nov 2026 15:13:01 +0100 Subject: [PATCH] Add signal strength sensor to Tile BLE (#193466) Co-authored-by: Claude --- homeassistant/components/tile_ble/__init__.py | 2 +- .../components/tile_ble/quality_scale.yaml | 10 +-- homeassistant/components/tile_ble/sensor.py | 77 ++++++++++++++++ .../tile_ble/snapshots/test_sensor.ambr | 56 ++++++++++++ tests/components/tile_ble/test_sensor.py | 88 +++++++++++++++++++ 5 files changed, 225 insertions(+), 8 deletions(-) create mode 100644 homeassistant/components/tile_ble/sensor.py create mode 100644 tests/components/tile_ble/snapshots/test_sensor.ambr create mode 100644 tests/components/tile_ble/test_sensor.py diff --git a/homeassistant/components/tile_ble/__init__.py b/homeassistant/components/tile_ble/__init__.py index f8c85d4f3e2d..858fad3dce79 100644 --- a/homeassistant/components/tile_ble/__init__.py +++ b/homeassistant/components/tile_ble/__init__.py @@ -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: diff --git a/homeassistant/components/tile_ble/quality_scale.yaml b/homeassistant/components/tile_ble/quality_scale.yaml index 6933778ca067..6078114c8432 100644 --- a/homeassistant/components/tile_ble/quality_scale.yaml +++ b/homeassistant/components/tile_ble/quality_scale.yaml @@ -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. diff --git a/homeassistant/components/tile_ble/sensor.py b/homeassistant/components/tile_ble/sensor.py new file mode 100644 index 000000000000..5f418656d905 --- /dev/null +++ b/homeassistant/components/tile_ble/sensor.py @@ -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() diff --git a/tests/components/tile_ble/snapshots/test_sensor.ambr b/tests/components/tile_ble/snapshots/test_sensor.ambr new file mode 100644 index 000000000000..f0563fc19fc1 --- /dev/null +++ b/tests/components/tile_ble/snapshots/test_sensor.ambr @@ -0,0 +1,56 @@ +# serializer version: 1 +# name: test_entities[sensor.tile_signal_strength-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.tile_signal_strength', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Signal strength', + 'options': dict({ + }), + 'original_device_class': , + '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({ + : 'signal_strength', + : 'Tile Signal strength', + : , + : 'dBm', + }), + 'context': , + 'entity_id': 'sensor.tile_signal_strength', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '-60', + }) +# --- diff --git a/tests/components/tile_ble/test_sensor.py b/tests/components/tile_ble/test_sensor.py new file mode 100644 index 000000000000..4cb61b15db33 --- /dev/null +++ b/tests/components/tile_ble/test_sensor.py @@ -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"