From f728eb912cfb8fc874cf6eace583d911fe824cf0 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Fri, 16 Oct 2026 04:20:48 +1000 Subject: [PATCH] Add Teslemetry Bluetooth binary sensors (#182585) --- .../components/teslemetry/__init__.py | 44 +-- .../components/teslemetry/binary_sensor.py | 140 +++++++++- .../components/teslemetry/icons.json | 12 + homeassistant/components/teslemetry/models.py | 5 + .../components/teslemetry/strings.json | 6 + tests/components/teslemetry/__init__.py | 51 +++- tests/components/teslemetry/const.py | 4 + .../snapshots/test_binary_sensor.ambr | 102 +++++++ .../teslemetry/test_binary_sensor.py | 255 +++++++++++++++++- .../components/teslemetry/test_config_flow.py | 11 +- tests/components/teslemetry/test_init.py | 48 +--- 11 files changed, 609 insertions(+), 69 deletions(-) diff --git a/homeassistant/components/teslemetry/__init__.py b/homeassistant/components/teslemetry/__init__.py index 33a626977d0c..837fb31a82f4 100644 --- a/homeassistant/components/teslemetry/__init__.py +++ b/homeassistant/components/teslemetry/__init__.py @@ -26,6 +26,7 @@ from tesla_fleet_api.exceptions import ( ) from tesla_fleet_api.router import VehicleRouter from tesla_fleet_api.tesla import EnergySiteRouter +from tesla_fleet_api.tesla.vehicle.bluetooth import VehicleBluetooth from tesla_fleet_api.teslemetry import EnergySite, Teslemetry, Vehicle from tesla_fleet_api.teslemetry.energysite import TeslemetryEnergySite from teslemetry_stream import TeslemetryStream, TeslemetryStreamAuthenticationError @@ -298,17 +299,6 @@ def _setup_vehicle_repairs( ) -def _ble_address_for_vin(entry: TeslemetryConfigEntry, vin: str) -> str | None: - """Return the paired Bluetooth address for a vehicle, if one was added.""" - for subentry in entry.subentries.values(): - if ( - subentry.subentry_type == SUBENTRY_TYPE_VEHICLE - and subentry.data.get(CONF_VIN) == vin - ): - return subentry.data.get(CONF_ADDRESS) - return None - - # Two failure shapes must be caught to fall back to cloud control: the library # wraps existing-key failures in PrivateKeyError, the create-race path raises raw errors. _BLE_KEY_ERRORS: Final = ( @@ -322,14 +312,13 @@ _BLE_KEY_ERRORS: Final = ( async def _async_resolve_vehicle_api( hass: HomeAssistant, - entry: TeslemetryConfigEntry, vin: str, cloud_vehicle: Vehicle, -) -> Vehicle | VehicleRouter: - """Return the API a vehicle's platforms should call.""" - address = _ble_address_for_vin(entry, vin) + address: str | None, +) -> tuple[Vehicle | VehicleRouter, VehicleBluetooth | None]: + """Return the API a vehicle's platforms should call, and its Bluetooth backend.""" if not address: - return cloud_vehicle + return cloud_vehicle, None # A bad BLE key file for one vehicle must not tear down the whole entry. try: @@ -341,7 +330,7 @@ async def _async_resolve_vehicle_api( vin, exc_info=True, ) - return cloud_vehicle + return cloud_vehicle, None # disable keep alive to allow vehicles to sleep bluetooth_vehicle = parent.vehicles.createBluetooth( vin, @@ -360,7 +349,10 @@ async def _async_resolve_vehicle_api( bluetooth_vehicle.set_device(device) return True - return VehicleRouter(bluetooth_vehicle, cloud_vehicle, health=_in_range) + return ( + VehicleRouter(bluetooth_vehicle, cloud_vehicle, health=_in_range), + bluetooth_vehicle, + ) def _find_energy_subentry_id(entry: TeslemetryConfigEntry, site_id: int) -> str | None: @@ -709,11 +701,21 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - ) stream_vehicle = stream.get_vehicle(vin) - vehicle_api = await _async_resolve_vehicle_api( + # Pairing always stores an address, so the subentry is the Bluetooth switch. + ble_address: str | None = next( + ( + subentry.data[CONF_ADDRESS] + for subentry in entry.subentries.values() + if subentry.subentry_type == SUBENTRY_TYPE_VEHICLE + and subentry.data.get(CONF_VIN) == vin + ), + None, + ) + vehicle_api, ble_api = await _async_resolve_vehicle_api( hass, - entry, vin, vehicle, + ble_address, ) vehicles.append( @@ -727,6 +729,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - vin=vin, firmware=firmware or "Unknown", device=device, + ble_address=ble_address, + ble_api=ble_api, ) ) diff --git a/homeassistant/components/teslemetry/binary_sensor.py b/homeassistant/components/teslemetry/binary_sensor.py index 1995dadf095f..c281854e6566 100644 --- a/homeassistant/components/teslemetry/binary_sensor.py +++ b/homeassistant/components/teslemetry/binary_sensor.py @@ -8,13 +8,14 @@ from tesla_fleet_api import firmware_at_least from tesla_fleet_api.const import Scope from teslemetry_stream.vehicle import TeslemetryStreamVehicle +from homeassistant.components import bluetooth from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import STATE_OFF, STATE_ON, EntityCategory, Platform -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import StateType @@ -24,6 +25,7 @@ from .const import TeslemetryState from .entity import ( TeslemetryEnergyInfoEntity, TeslemetryEnergyLiveEntity, + TeslemetryRootEntity, TeslemetryVehiclePollingEntity, TeslemetryVehicleStreamEntity, ) @@ -551,6 +553,21 @@ ENERGY_INFO_DESCRIPTIONS: tuple[TeslemetryBinarySensorEntityDescription, ...] = ), ) +BLUETOOTH_PRESENCE_DESCRIPTION = TeslemetryBinarySensorEntityDescription( + key="bluetooth", + translation_key="bluetooth", + device_class=BinarySensorDeviceClass.CONNECTIVITY, + entity_category=EntityCategory.DIAGNOSTIC, +) + +BLUETOOTH_SESSION_DESCRIPTION = TeslemetryBinarySensorEntityDescription( + key="bluetooth_session", + translation_key="bluetooth_session", + device_class=BinarySensorDeviceClass.CONNECTIVITY, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, +) + async def async_setup_entry( hass: HomeAssistant, @@ -578,6 +595,17 @@ async def async_setup_entry( entities.append( TeslemetryVehiclePollingBinarySensorEntity(vehicle, description) ) + if vehicle.ble_address: + entities.append( + TeslemetryVehicleBluetoothPresenceBinarySensorEntity( + vehicle, BLUETOOTH_PRESENCE_DESCRIPTION, vehicle.ble_address + ) + ) + entities.append( + TeslemetryVehicleBluetoothSessionBinarySensorEntity( + vehicle, BLUETOOTH_SESSION_DESCRIPTION + ) + ) entities.extend( TeslemetryEnergyLiveBinarySensorEntity(energysite, description) @@ -711,3 +739,113 @@ class TeslemetryEnergyInfoBinarySensorEntity( def _async_update_attrs(self) -> None: """Update the attributes of the binary sensor.""" self._attr_is_on = self.entity_description.polling_value_fn(self._value) + + +class TeslemetryVehicleBluetoothBinarySensorEntity( + TeslemetryRootEntity, BinarySensorEntity +): + """Base class for Teslemetry vehicle Bluetooth binary sensors.""" + + entity_description: TeslemetryBinarySensorEntityDescription + _attr_should_poll = False + + def __init__( + self, + data: TeslemetryVehicleData, + description: TeslemetryBinarySensorEntityDescription, + ) -> None: + """Initialize the Bluetooth binary sensor.""" + self.entity_description = description + self._attr_unique_id = f"{data.vin}-{description.key}" + self._attr_device_info = data.device + + +class TeslemetryVehicleBluetoothPresenceBinarySensorEntity( + TeslemetryVehicleBluetoothBinarySensorEntity +): + """Binary sensor for a vehicle being visible to the Bluetooth stack.""" + + def __init__( + self, + data: TeslemetryVehicleData, + description: TeslemetryBinarySensorEntityDescription, + address: str, + ) -> None: + """Initialize the Bluetooth presence binary sensor.""" + self._address = address + super().__init__(data, description) + + @override + async def async_added_to_hass(self) -> None: + """Follow the Bluetooth stack's own presence history for the address.""" + await super().async_added_to_hass() + self._attr_is_on = bluetooth.async_address_present(self.hass, self._address) + self.async_on_remove( + bluetooth.async_register_callback( + self.hass, + self._async_advertisement, + bluetooth.BluetoothCallbackMatcher(address=self._address), + # Any other mode would ask scanners to actively probe the vehicle. + bluetooth.BluetoothScanningMode.PASSIVE, + ) + ) + self.async_on_remove( + bluetooth.async_track_unavailable( + self.hass, self._async_unavailable, self._address + ) + ) + + @callback + def _async_advertisement( + self, + service_info: bluetooth.BluetoothServiceInfoBleak, + change: bluetooth.BluetoothChange, + ) -> None: + """Handle an advertisement broadcast by the vehicle.""" + self._attr_is_on = True + self.async_write_ha_state() + + @callback + def _async_unavailable( + self, service_info: bluetooth.BluetoothServiceInfoBleak + ) -> None: + """Handle the vehicle falling out of the stack's presence history.""" + self._attr_is_on = False + self.async_write_ha_state() + + +class TeslemetryVehicleBluetoothSessionBinarySensorEntity( + TeslemetryVehicleBluetoothBinarySensorEntity +): + """Binary sensor for Home Assistant's own Bluetooth link to a vehicle.""" + + # Links are opened per command and never kept alive, so there is no session + # until the library reports one. + _attr_is_on = False + + def __init__( + self, + data: TeslemetryVehicleData, + description: TeslemetryBinarySensorEntityDescription, + ) -> None: + """Initialize the Bluetooth session binary sensor.""" + # A vehicle whose key failed to load can never hold a link to report on, + # but the entity must still exist so its registry entry survives. + self._ble_api = data.ble_api + self._attr_available = data.ble_api is not None + super().__init__(data, description) + + @override + async def async_added_to_hass(self) -> None: + """Subscribe to the library's connect and disconnect events.""" + await super().async_added_to_hass() + if self._ble_api is not None: + self.async_on_remove( + self._ble_api.listen_connection_status(self._async_connection_status) + ) + + @callback + def _async_connection_status(self, connected: bool) -> None: + """Handle the Bluetooth session being established or lost.""" + self._attr_is_on = connected + self.async_write_ha_state() diff --git a/homeassistant/components/teslemetry/icons.json b/homeassistant/components/teslemetry/icons.json index 857b8086c914..1418f0543ddd 100644 --- a/homeassistant/components/teslemetry/icons.json +++ b/homeassistant/components/teslemetry/icons.json @@ -7,6 +7,18 @@ "on": "mdi:home-battery" } }, + "bluetooth": { + "state": { + "off": "mdi:bluetooth-off", + "on": "mdi:bluetooth" + } + }, + "bluetooth_session": { + "state": { + "off": "mdi:bluetooth-off", + "on": "mdi:bluetooth-connect" + } + }, "cellular": { "state": { "off": "mdi:signal-cellular-outline", diff --git a/homeassistant/components/teslemetry/models.py b/homeassistant/components/teslemetry/models.py index b951173f60b6..054e8a69a2ec 100644 --- a/homeassistant/components/teslemetry/models.py +++ b/homeassistant/components/teslemetry/models.py @@ -6,6 +6,7 @@ from dataclasses import dataclass, field from tesla_fleet_api.const import Scope from tesla_fleet_api.router import VehicleRouter from tesla_fleet_api.tesla import EnergySiteRouter +from tesla_fleet_api.tesla.vehicle.bluetooth import VehicleBluetooth from tesla_fleet_api.teslemetry import EnergySite, Vehicle from teslemetry_stream import TeslemetryStream, TeslemetryStreamVehicle @@ -45,6 +46,10 @@ class TeslemetryVehicleData: vin: str firmware: str device: DeviceInfo + # Set exactly when the vehicle has a Bluetooth subentry; ble_api is + # additionally None when the private key could not be loaded. + ble_address: str | None + ble_api: VehicleBluetooth | None wakelock: asyncio.Lock = field(default_factory=asyncio.Lock) diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index 606ef39bfee1..b3b553dfefa6 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -158,6 +158,12 @@ "blind_spot_collision_warning_chime": { "name": "Blind spot collision warning chime" }, + "bluetooth": { + "name": "Bluetooth" + }, + "bluetooth_session": { + "name": "Bluetooth session" + }, "bms_full_charge_complete": { "name": "BMS full charge" }, diff --git a/tests/components/teslemetry/__init__.py b/tests/components/teslemetry/__init__.py index 75ea2cd22ced..f46179913914 100644 --- a/tests/components/teslemetry/__init__.py +++ b/tests/components/teslemetry/__init__.py @@ -5,11 +5,18 @@ from unittest.mock import patch from syrupy.assertion import SnapshotAssertion -from homeassistant.components.teslemetry.const import DOMAIN -from homeassistant.const import Platform +from homeassistant.components.teslemetry.const import ( + CONF_VIN, + DOMAIN, + SUBENTRY_TYPE_VEHICLE, +) +from homeassistant.config_entries import ConfigSubentryData +from homeassistant.const import CONF_ADDRESS, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er +from .const import ADDRESS, VIN + from tests.common import MockConfigEntry @@ -31,6 +38,46 @@ def mock_config_entry() -> MockConfigEntry: ) +def mock_ble_config_entry() -> MockConfigEntry: + """Create a mock config entry whose vehicle subentry is already BLE paired.""" + + entry = mock_config_entry() + return MockConfigEntry( + domain=entry.domain, + version=entry.version, + minor_version=entry.minor_version, + unique_id=entry.unique_id, + data=dict(entry.data), + subentries_data=[ + ConfigSubentryData( + subentry_type=SUBENTRY_TYPE_VEHICLE, + unique_id=VIN, + title="Test", + data={CONF_VIN: VIN, CONF_ADDRESS: ADDRESS}, + ) + ], + ) + + +async def setup_ble_platform( + hass: HomeAssistant, + platforms: list[Platform] | None = None, +) -> MockConfigEntry: + """Set up the Teslemetry platform for a BLE paired vehicle.""" + + entry = mock_ble_config_entry() + entry.add_to_hass(hass) + + if platforms is None: + await hass.config_entries.async_setup(entry.entry_id) + else: + with patch("homeassistant.components.teslemetry.PLATFORMS", platforms): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + return entry + + async def setup_platform( hass: HomeAssistant, platforms: list[Platform] | None = None, diff --git a/tests/components/teslemetry/const.py b/tests/components/teslemetry/const.py index 23a0022f5f4b..e36da49e9ad6 100644 --- a/tests/components/teslemetry/const.py +++ b/tests/components/teslemetry/const.py @@ -8,6 +8,10 @@ from tests.common import load_json_object_fixture UNIQUE_ID = "abc-123" CONFIG_V1 = {CONF_ACCESS_TOKEN: "abc-123"} +# The vehicle in products.json, and the Bluetooth address a subentry pairs it at. +VIN = "LRW3F7EK4NC700000" +ADDRESS = "AA:BB:CC:DD:EE:FF" + WAKE_UP_ONLINE = {"response": {"state": TeslemetryState.ONLINE}, "error": None} PRODUCTS = load_json_object_fixture("products.json", DOMAIN) diff --git a/tests/components/teslemetry/snapshots/test_binary_sensor.ambr b/tests/components/teslemetry/snapshots/test_binary_sensor.ambr index 70d4447cff51..274478d94df0 100644 --- a/tests/components/teslemetry/snapshots/test_binary_sensor.ambr +++ b/tests/components/teslemetry/snapshots/test_binary_sensor.ambr @@ -1866,3 +1866,105 @@ 'state': 'on', }) # --- +# name: test_bluetooth_binary_sensors[binary_sensor.test_bluetooth][binary_sensor.test_bluetooth-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.test_bluetooth', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Bluetooth', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Bluetooth', + 'platform': 'teslemetry', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'bluetooth', + 'unique_id': 'LRW3F7EK4NC700000-bluetooth', + 'unit_of_measurement': None, + }) +# --- +# name: test_bluetooth_binary_sensors[binary_sensor.test_bluetooth][binary_sensor.test_bluetooth-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'connectivity', + : 'Test Bluetooth', + }), + 'context': , + 'entity_id': 'binary_sensor.test_bluetooth', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_bluetooth_binary_sensors[binary_sensor.test_bluetooth_session][binary_sensor.test_bluetooth_session-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.test_bluetooth_session', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Bluetooth session', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Bluetooth session', + 'platform': 'teslemetry', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'bluetooth_session', + 'unique_id': 'LRW3F7EK4NC700000-bluetooth_session', + 'unit_of_measurement': None, + }) +# --- +# name: test_bluetooth_binary_sensors[binary_sensor.test_bluetooth_session][binary_sensor.test_bluetooth_session-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'connectivity', + : 'Test Bluetooth session', + }), + 'context': , + 'entity_id': 'binary_sensor.test_bluetooth_session', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/teslemetry/test_binary_sensor.py b/tests/components/teslemetry/test_binary_sensor.py index 8d02e3699914..b76d8893d8c5 100644 --- a/tests/components/teslemetry/test_binary_sensor.py +++ b/tests/components/teslemetry/test_binary_sensor.py @@ -1,22 +1,49 @@ """Test the Teslemetry binary sensor platform.""" -from unittest.mock import AsyncMock +from collections.abc import Generator +from datetime import timedelta +import time +from unittest.mock import AsyncMock, MagicMock, patch from freezegun.api import FrozenDateTimeFactory +from habluetooth import CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS import pytest from syrupy.assertion import SnapshotAssertion +from tesla_fleet_api.tesla.vehicle.bluetooth import VehicleBluetooth from teslemetry_stream import Signal -from homeassistant.components.teslemetry.const import DOMAIN +from homeassistant.components.bluetooth.const import UNAVAILABLE_TRACK_SECONDS +from homeassistant.components.bluetooth.manager import HomeAssistantBluetoothManager +from homeassistant.components.teslemetry.const import DOMAIN, SUBENTRY_TYPE_VEHICLE from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL -from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform +from homeassistant.const import ( + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + Platform, +) from homeassistant.core import HomeAssistant, State from homeassistant.helpers import entity_registry as er +from homeassistant.util import dt as dt_util -from . import assert_entities, assert_entities_alt, setup_platform -from .const import METADATA, VEHICLE_DATA_ALT +from . import ( + assert_entities, + assert_entities_alt, + mock_ble_config_entry, + setup_ble_platform, + setup_platform, +) +from .const import ADDRESS, METADATA, VEHICLE_DATA_ALT, VIN from tests.common import async_fire_time_changed, mock_restore_cache +from tests.components.bluetooth import ( + generate_advertisement_data, + generate_ble_device, + inject_advertisement, + patch_all_discovered_devices, + patch_bluetooth_time, +) @pytest.mark.usefixtures("entity_registry_enabled_by_default") @@ -165,6 +192,224 @@ async def test_binary_sensors_connectivity( assert hass.states.get("binary_sensor.test_wi_fi").state == "off" +BLE_NAME = "Sdcdcb1a343110fbaC" +PRESENCE_ENTITY_ID = "binary_sensor.test_bluetooth" +SESSION_ENTITY_ID = "binary_sensor.test_bluetooth_session" + + +@pytest.fixture +def mock_ble_vehicle() -> Generator[VehicleBluetooth]: + """Back the paired vehicle with a real VehicleBluetooth that never signs.""" + vehicle = VehicleBluetooth(MagicMock(), VIN, key=False, keepalive_interval=None) + with patch("homeassistant.components.teslemetry.helpers.TeslaBluetooth") as parent: + parent.return_value.get_private_key = AsyncMock() + parent.return_value.vehicles.createBluetooth.return_value = vehicle + yield vehicle + + +def inject_vehicle_advertisement(hass: HomeAssistant) -> None: + """Make the Bluetooth stack hear one advertisement from the vehicle.""" + inject_advertisement( + hass, + generate_ble_device(ADDRESS, BLE_NAME), + generate_advertisement_data(local_name=BLE_NAME), + ) + + +async def drop_vehicle_from_stack(hass: HomeAssistant, start_monotonic: float) -> None: + """Advance past the stale and unavailable windows with nothing discovered.""" + advance = ( + CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + + UNAVAILABLE_TRACK_SECONDS + + 1 + ) + with ( + patch_bluetooth_time(start_monotonic + advance), + patch_all_discovered_devices([]), + ): + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=advance)) + await hass.async_block_till_done() + + +@pytest.mark.usefixtures( + "enable_bluetooth", "mock_ble_vehicle", "entity_registry_enabled_by_default" +) +@pytest.mark.parametrize( + "entity_id", + [PRESENCE_ENTITY_ID, SESSION_ENTITY_ID], +) +async def test_bluetooth_binary_sensors( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, + entity_id: str, +) -> None: + """Tests that the Bluetooth binary sensor entities are correct.""" + await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + assert entity_registry.async_get(entity_id) == snapshot(name=f"{entity_id}-entry") + assert hass.states.get(entity_id) == snapshot(name=f"{entity_id}-state") + + +@pytest.mark.usefixtures("enable_bluetooth") +async def test_bluetooth_binary_sensor( + hass: HomeAssistant, mock_ble_vehicle: VehicleBluetooth +) -> None: + """Tests that the Bluetooth binary sensor follows the stack's presence history. + + Tracking presence must never connect to or actively probe the vehicle, so the + same run asserts no BLE link was opened and no active scan was requested. + """ + start_monotonic = time.monotonic() + with ( + patch( + "tesla_fleet_api.tesla.vehicle.bluetooth.establish_connection" + ) as mock_establish_connection, + patch.object( + HomeAssistantBluetoothManager, "async_register_active_scan" + ) as mock_register_active_scan, + ): + await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + # Nothing heard yet, so the stack cannot see the vehicle. + assert hass.states.get(PRESENCE_ENTITY_ID).state == STATE_OFF + + inject_vehicle_advertisement(hass) + await hass.async_block_till_done() + assert hass.states.get(PRESENCE_ENTITY_ID).state == STATE_ON + + await drop_vehicle_from_stack(hass, start_monotonic) + assert hass.states.get(PRESENCE_ENTITY_ID).state == STATE_OFF + + mock_establish_connection.assert_not_called() + mock_register_active_scan.assert_not_called() + assert mock_ble_vehicle.get_device() is None + + +@pytest.mark.usefixtures("enable_bluetooth", "mock_ble_vehicle") +async def test_bluetooth_binary_sensor_already_in_range(hass: HomeAssistant) -> None: + """Tests that a vehicle the stack already knows about starts on.""" + inject_vehicle_advertisement(hass) + await hass.async_block_till_done() + + await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + assert hass.states.get(PRESENCE_ENTITY_ID).state == STATE_ON + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_legacy") +async def test_bluetooth_binary_sensors_need_a_paired_vehicle( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Tests that a vehicle without a Bluetooth subentry gets no Bluetooth sensors.""" + await setup_platform(hass, [Platform.BINARY_SENSOR]) + + assert entity_registry.async_get(PRESENCE_ENTITY_ID) is None + assert entity_registry.async_get(SESSION_ENTITY_ID) is None + + +@pytest.mark.usefixtures("enable_bluetooth", "mock_ble_vehicle") +async def test_bluetooth_session_binary_sensor_disabled_by_default( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Tests that the Bluetooth session binary sensor is disabled by default.""" + await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + assert (entry := entity_registry.async_get(SESSION_ENTITY_ID)) + assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION + assert hass.states.get(SESSION_ENTITY_ID) is None + + +@pytest.mark.usefixtures("enable_bluetooth", "entity_registry_enabled_by_default") +async def test_bluetooth_session_binary_sensor( + hass: HomeAssistant, mock_ble_vehicle: VehicleBluetooth +) -> None: + """Tests that the Bluetooth session binary sensor follows the BLE link.""" + await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + assert hass.states.get(SESSION_ENTITY_ID).state == STATE_OFF + + client = MagicMock() + client.is_connected = True + client.start_notify = AsyncMock() + client.disconnect = AsyncMock() + mock_ble_vehicle.set_device(generate_ble_device(ADDRESS, BLE_NAME)) + with patch( + "tesla_fleet_api.tesla.vehicle.bluetooth.establish_connection", + AsyncMock(return_value=client), + ): + await mock_ble_vehicle.connect() + await hass.async_block_till_done() + assert hass.states.get(SESSION_ENTITY_ID).state == STATE_ON + + await mock_ble_vehicle.disconnect() + await hass.async_block_till_done() + assert hass.states.get(SESSION_ENTITY_ID).state == STATE_OFF + + +@pytest.mark.usefixtures("enable_bluetooth", "entity_registry_enabled_by_default") +async def test_bluetooth_session_binary_sensor_without_key( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Tests that a failed key load keeps the session entity, unavailable. + + The entities are gated on the subentry rather than on the Bluetooth backend, + so a key load failure cannot look like an unpaired vehicle to the stale + entity cleanup and cost the user a customised registry entry. + """ + entry = mock_ble_config_entry() + entry.add_to_hass(hass) + existing = entity_registry.async_get_or_create( + Platform.BINARY_SENSOR, + DOMAIN, + f"{VIN}-bluetooth_session", + config_entry=entry, + suggested_object_id="test_bluetooth_session", + ) + entity_registry.async_update_entity(existing.entity_id, name="Garage link") + + with ( + patch( + "homeassistant.components.teslemetry.PLATFORMS", [Platform.BINARY_SENSOR] + ), + patch( + "homeassistant.components.teslemetry.helpers.TeslaBluetooth" + ) as mock_parent, + ): + mock_parent.return_value.get_private_key = AsyncMock( + side_effect=OSError("disk gone") + ) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert (survived := entity_registry.async_get(SESSION_ENTITY_ID)) + assert survived.id == existing.id + assert survived.name == "Garage link" + assert hass.states.get(SESSION_ENTITY_ID).state == STATE_UNAVAILABLE + assert hass.states.get(PRESENCE_ENTITY_ID).state == STATE_OFF + + +@pytest.mark.usefixtures("enable_bluetooth", "mock_ble_vehicle") +async def test_bluetooth_binary_sensors_removed_with_subentry( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Tests that removing the Bluetooth subentry removes both entities.""" + entry = await setup_ble_platform(hass, [Platform.BINARY_SENSOR]) + + assert entity_registry.async_get(PRESENCE_ENTITY_ID) + assert entity_registry.async_get(SESSION_ENTITY_ID) + + subentry_id = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE)[0].subentry_id + with patch( + "homeassistant.components.teslemetry.PLATFORMS", [Platform.BINARY_SENSOR] + ): + assert hass.config_entries.async_remove_subentry(entry, subentry_id) + await hass.async_block_till_done() + + assert entity_registry.async_get(PRESENCE_ENTITY_ID) is None + assert entity_registry.async_get(SESSION_ENTITY_ID) is None + + @pytest.mark.parametrize( ("scopes", "expected"), [ diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 24f611a95869..9b089ed8e6a1 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -89,7 +89,7 @@ from homeassistant.helpers import ( from homeassistant.setup import async_setup_component from . import mock_config_entry, setup_platform -from .const import CONFIG_V1, METADATA, PRODUCTS, UNIQUE_ID +from .const import ADDRESS, CONFIG_V1, METADATA, PRODUCTS, UNIQUE_ID, VIN from tests.common import MockConfigEntry, async_fire_time_changed from tests.components.bluetooth import ( @@ -722,10 +722,6 @@ async def test_migrate_error_from_future( assert entry.state is ConfigEntryState.MIGRATION_ERROR -VIN = "LRW3F7EK4NC700000" -ADDRESS = "AA:BB:CC:DD:EE:FF" - - def _entry_with_ble() -> MockConfigEntry: """Return a config entry whose vehicle subentry is already BLE-paired.""" entry = mock_config_entry() @@ -1909,13 +1905,14 @@ async def test_subentry_add_flow_keeps_device_on_parent( assert bound_device.id == existing_device.id assert bound_device.config_subentry_id is None - # The vehicle entities keep their unique IDs and stay on the parent entry. + # The vehicle entities keep their unique IDs and stay on the parent entry; + # pairing only adds the vehicle's Bluetooth entities. bound_entities = er.async_entries_for_device( entity_registry, bound_device.id, include_disabled_entities=True ) assert {entity.unique_id for entity in bound_entities} == { entity.unique_id for entity in vehicle_entities - } + } | {f"{VIN}-bluetooth", f"{VIN}-bluetooth_session"} assert all(entity.config_subentry_id is None for entity in bound_entities) diff --git a/tests/components/teslemetry/test_init.py b/tests/components/teslemetry/test_init.py index 9f70f3b3d7bd..f79c69aba64f 100644 --- a/tests/components/teslemetry/test_init.py +++ b/tests/components/teslemetry/test_init.py @@ -101,8 +101,9 @@ from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session from homeassistant.helpers.update_coordinator import UpdateFailed from homeassistant.setup import async_setup_component -from . import mock_config_entry, setup_platform +from . import mock_ble_config_entry, mock_config_entry, setup_platform from .const import ( + ADDRESS, CONFIG_V1, LIVE_STATUS, METADATA, @@ -114,6 +115,7 @@ from .const import ( VEHICLE_DATA, VEHICLE_DATA_ALT, VEHICLE_DATA_ASLEEP, + VIN, ) from tests.common import MockConfigEntry, async_fire_time_changed @@ -2232,35 +2234,13 @@ async def test_energy_stream_disconnect_marks_unavailable_and_recovers( ] -VIN = "LRW3F7EK4NC700000" -ADDRESS = "AA:BB:CC:DD:EE:FF" CLOUD_RESULT = {"response": {"result": True, "reason": "cloud"}} BLE_RESULT = {"response": {"result": True, "reason": "bluetooth"}} -def _entry_with_ble() -> MockConfigEntry: - """Return a config entry whose vehicle subentry is already BLE-paired.""" - entry = mock_config_entry() - return MockConfigEntry( - domain=entry.domain, - version=entry.version, - minor_version=entry.minor_version, - unique_id=entry.unique_id, - data=dict(entry.data), - subentries_data=[ - ConfigSubentryData( - subentry_type=SUBENTRY_TYPE_VEHICLE, - unique_id=VIN, - title="Test", - data={CONF_VIN: VIN, CONF_ADDRESS: ADDRESS}, - ) - ], - ) - - async def test_vehicle_router_with_bluetooth(hass: HomeAssistant) -> None: """A BLE-paired vehicle wraps its cloud API in a VehicleRouter.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( @@ -2338,7 +2318,7 @@ async def test_vehicle_bluetooth_key_load_falls_back_to_cloud( caplog: pytest.LogCaptureFixture, ) -> None: """A vehicle whose Bluetooth key fails to load degrades to cloud control.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( @@ -2374,7 +2354,7 @@ async def test_vehicle_bluetooth_key_load_recovers_on_reload( caplog: pytest.LogCaptureFixture, ) -> None: """A vehicle degraded to cloud by a key-load failure regains BLE control on reload.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( @@ -2416,7 +2396,7 @@ async def _paired_entry( hass: HomeAssistant, ble_lookup: MagicMock ) -> AsyncIterator[tuple[VehicleRouter, AsyncMock, AsyncMock]]: """Set up a BLE-paired entry, yielding its router and both backends.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) bluetooth_vehicle = AsyncMock() bluetooth_vehicle.set_device = MagicMock() @@ -2532,7 +2512,7 @@ async def test_vehicle_router_fails_over_on_stale_cache_hit( async def test_vehicle_paired_but_never_seen(hass: HomeAssistant) -> None: """A paired vehicle never seen by Bluetooth is built without a device handle.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( @@ -2565,7 +2545,7 @@ async def test_unload_disconnects_bluetooth( hass: HomeAssistant, disconnect_error: Exception | None ) -> None: """Unloading a routed entry disconnects its Bluetooth backend, errors and all.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) bluetooth_vehicle = AsyncMock() bluetooth_vehicle.disconnect = AsyncMock(side_effect=disconnect_error) @@ -2596,7 +2576,7 @@ async def test_unload_disconnects_bluetooth( async def test_unload_never_connected_bluetooth(hass: HomeAssistant) -> None: """Unloading a paired vehicle that was never in range does not raise.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) bluetooth_vehicle = AsyncMock() @@ -2627,7 +2607,7 @@ async def test_unload_disconnect_timeout( hass: HomeAssistant, caplog: pytest.LogCaptureFixture ) -> None: """A hung Bluetooth disconnect cannot block unload past the timeout.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) bluetooth_vehicle = AsyncMock() never_set = asyncio.Event() @@ -2667,7 +2647,7 @@ async def test_unload_disconnect_instant_timeout( hass: HomeAssistant, caplog: pytest.LogCaptureFixture ) -> None: """A TimeoutError raised by disconnect() itself is not mistaken for the deadline.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) bluetooth_vehicle = AsyncMock() bluetooth_vehicle.disconnect = AsyncMock(side_effect=TimeoutError("device busy")) @@ -2763,7 +2743,7 @@ async def test_router_fails_over_on_command_failed() -> None: async def _setup_paired_entry(hass: HomeAssistant) -> MockConfigEntry: """Set up an entry whose only account vehicle is already BLE-paired.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( patch( @@ -2806,7 +2786,7 @@ async def test_subentry_removal_keeps_vehicle_device_and_entities( entity_registry: er.EntityRegistry, ) -> None: """Removing a vehicle subentry leaves the cloud vehicle device and entities intact.""" - entry = _entry_with_ble() + entry = mock_ble_config_entry() entry.add_to_hass(hass) with ( patch(