Add Tile BLE integration (#188526)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-11-19 18:09:19 +01:00
committed by GitHub
co-authored by Claude
parent 763a03dca8
commit 8a75863a3c
20 changed files with 1134 additions and 9 deletions
Generated
+2
View File
@@ -2010,6 +2010,8 @@ AGENTS.md @home-assistant/core
/tests/components/tibber/ @danielhiversen
/homeassistant/components/tile/ @bachya
/tests/components/tile/ @bachya
/homeassistant/components/tile_ble/ @joostlek
/tests/components/tile_ble/ @joostlek
/homeassistant/components/tilt_ble/ @apt-itude
/tests/components/tilt_ble/ @apt-itude
/homeassistant/components/tilt_pi/ @michaelheyman
+5
View File
@@ -0,0 +1,5 @@
{
"domain": "tile",
"name": "Tile",
"integrations": ["tile", "tile_ble"]
}
@@ -0,0 +1,22 @@
"""The Tile BLE integration."""
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .coordinator import TileBleConfigEntry, TileBleCoordinator
PLATFORMS = [Platform.DEVICE_TRACKER]
async def async_setup_entry(hass: HomeAssistant, entry: TileBleConfigEntry) -> None:
"""Set up Tile BLE from a config entry."""
coordinator = TileBleCoordinator(hass, entry)
entry.runtime_data = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(coordinator.async_start())
async def async_unload_entry(hass: HomeAssistant, entry: TileBleConfigEntry) -> None:
"""Unload a config entry."""
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
@@ -0,0 +1,177 @@
"""Config flow for the Tile BLE integration."""
from typing import Any, override
import probatio
from tile_ble import (
TILE_SERVICE_UUID,
TileBleAuthenticationError,
TileBleDevice,
TileBleError,
TileCloudAuthenticationError,
TileCloudError,
address_matches_tile_id,
async_get_tiles,
async_read_tile_id,
)
from homeassistant.components.bluetooth import (
BluetoothServiceInfoBleak,
async_ble_device_from_address,
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ADDRESS, CONF_PASSWORD, CONF_USERNAME
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .const import CONF_AUTH_KEY, DOMAIN
STEP_USER_SCHEMA = probatio.Schema(
{
probatio.Required(CONF_USERNAME): str,
probatio.Required(probatio.Secret(CONF_PASSWORD)): str,
}
)
class CannotConnect(HomeAssistantError):
"""Error to indicate the Tile cannot be connected to."""
class UnknownTile(HomeAssistantError):
"""Error to indicate the Tile is not in the Tile account."""
class TileBleConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Tile BLE."""
VERSION = 1
def __init__(self) -> None:
"""Initialize the config flow."""
self._tiles: dict[str, tuple[str, str]] = {}
self._devices: dict[str, str | None] = {}
@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Log in to the Tile account to get the names and keys of its Tiles."""
errors: dict[str, str] = {}
if user_input is not None:
# The Tile cloud identifies the login by a cookie, so each login
# gets its own session.
try:
tiles = await async_get_tiles(
async_create_clientsession(self.hass),
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
)
except TileCloudAuthenticationError:
errors["base"] = "invalid_auth"
except TileCloudError:
errors["base"] = "cannot_connect"
else:
self._tiles = {
tile.tile_id: (tile.name, tile.auth_key)
for tile in tiles
if tile.auth_key
}
if not self._tiles:
return self.async_abort(reason="no_tiles")
return await self.async_step_device()
return self.async_show_form(
step_id="user", data_schema=STEP_USER_SCHEMA, errors=errors
)
async def async_step_device(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Let the user pick one of their Tiles that Home Assistant can see."""
errors: dict[str, str] = {}
if user_input is not None:
address = user_input[CONF_ADDRESS]
await self.async_set_unique_id(address)
self._abort_if_unique_id_configured()
try:
name, auth_key = await self._async_validate(address)
except UnknownTile:
errors["base"] = "unknown_tile"
except TileBleAuthenticationError:
errors["base"] = "wrong_tile"
except CannotConnect, TileBleError:
errors["base"] = "cannot_connect"
else:
return self.async_create_entry(
title=name, data={CONF_AUTH_KEY: auth_key}
)
current_addresses = self._async_current_ids()
devices = [
(service_info, self._match_tile(service_info.address))
for service_info in async_discovered_service_info(
self.hass, connectable=False
)
if service_info.address not in current_addresses
and TILE_SERVICE_UUID in service_info.service_uuids
]
if not devices:
return self.async_abort(reason="no_devices_found")
# Tiles matched to the account first; the rest are only known by address.
devices.sort(key=lambda device: (device[1] is None, -device[0].rssi))
self._devices = {
service_info.address: tile_id for service_info, tile_id in devices
}
return self.async_show_form(
step_id="device",
data_schema=probatio.Schema(
{
probatio.Required(CONF_ADDRESS): probatio.In(
{
service_info.address: self._device_label(
service_info, tile_id
)
for service_info, tile_id in devices
}
)
}
),
errors=errors,
)
def _device_label(
self, service_info: BluetoothServiceInfoBleak, tile_id: str | None
) -> str:
"""Return how a Tile is shown in the device list."""
if tile_id:
return f"{self._tiles[tile_id][0]} ({service_info.address})"
return f"{service_info.address} ({service_info.rssi} dBm)"
def _match_tile(self, address: str) -> str | None:
"""Return the ID of the account's Tile that uses this address."""
return next(
(
tile_id
for tile_id in self._tiles
if address_matches_tile_id(address, tile_id)
),
None,
)
async def _async_validate(self, address: str) -> tuple[str, str]:
"""Identify the Tile at this address and check that its key works."""
if not (
ble_device := async_ble_device_from_address(
self.hass, address, connectable=True
)
):
raise CannotConnect
tile_id = self._devices[address] or await async_read_tile_id(ble_device)
if tile_id not in self._tiles:
raise UnknownTile
name, auth_key = self._tiles[tile_id]
await TileBleDevice(ble_device, auth_key).async_authenticate()
return name, auth_key
@@ -0,0 +1,5 @@
"""Constants for the Tile BLE integration."""
DOMAIN = "tile_ble"
CONF_AUTH_KEY = "auth_key"
@@ -0,0 +1,32 @@
"""Coordinator for the Tile BLE integration."""
import logging
from typing import TYPE_CHECKING
from homeassistant.components.bluetooth import BluetoothScanningMode
from homeassistant.components.bluetooth.passive_update_coordinator import (
PassiveBluetoothDataUpdateCoordinator,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
_LOGGER = logging.getLogger(__name__)
type TileBleConfigEntry = ConfigEntry[TileBleCoordinator]
class TileBleCoordinator(PassiveBluetoothDataUpdateCoordinator):
"""Track the advertisements of a Tile."""
def __init__(self, hass: HomeAssistant, config_entry: TileBleConfigEntry) -> None:
"""Initialize the coordinator."""
if TYPE_CHECKING:
assert config_entry.unique_id is not None
super().__init__(
hass,
_LOGGER,
config_entry.unique_id,
BluetoothScanningMode.PASSIVE,
connectable=False,
)
self.config_entry = config_entry
@@ -0,0 +1,45 @@
"""Device tracker for the Tile BLE integration."""
from typing import override
from homeassistant.components.device_tracker import BaseScannerEntity, SourceType
from homeassistant.core import HomeAssistant
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 device tracker."""
async_add_entities([TileBleDeviceTracker(entry.runtime_data, entry.title)])
class TileBleDeviceTracker(TileBleEntity, BaseScannerEntity):
"""Tracks whether a Tile is within Bluetooth range."""
_attr_name = None
_attr_source_type = SourceType.BLUETOOTH_LE
def __init__(self, coordinator: TileBleCoordinator, name: str) -> None:
"""Initialize the device tracker."""
super().__init__(coordinator, name)
self._attr_unique_id = coordinator.address
@property
@override
def available(self) -> bool:
"""Return True, as a Tile out of range is away rather than unavailable."""
return True
@property
@override
def is_connected(self) -> bool:
"""Return True if the Tile is within Bluetooth range."""
return self.coordinator.available
@@ -0,0 +1,23 @@
"""Base entity for the Tile BLE integration."""
from homeassistant.components.bluetooth.passive_update_coordinator import (
PassiveBluetoothCoordinatorEntity,
)
from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceInfo
from .coordinator import TileBleCoordinator
class TileBleEntity(PassiveBluetoothCoordinatorEntity[TileBleCoordinator]):
"""Base class for Tile BLE entities."""
_attr_has_entity_name = True
def __init__(self, coordinator: TileBleCoordinator, name: str) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(
connections={(CONNECTION_BLUETOOTH, coordinator.address)},
manufacturer="Tile Inc.",
name=name,
)
@@ -0,0 +1,14 @@
{
"domain": "tile_ble",
"name": "Tile BLE",
"categories": ["presence_location.trackers"],
"codeowners": ["@joostlek"],
"config_flow": true,
"dependencies": ["bluetooth_adapters"],
"documentation": "https://www.home-assistant.io/integrations/tile_ble",
"integration_type": "device",
"iot_class": "local_push",
"loggers": ["tile_ble"],
"quality_scale": "bronze",
"requirements": ["tile-ble==0.1.0"]
}
@@ -0,0 +1,106 @@
rules:
# Bronze
action-setup:
status: exempt
comment: This integration does not register actions.
appropriate-polling:
status: exempt
comment: This integration listens to Bluetooth advertisements and does not poll.
brands: done
common-modules: done
config-flow-test-coverage: done
config-flow: done
dependency-transparency: done
docs-actions:
status: exempt
comment: This integration does not register actions.
docs-conditions:
status: exempt
comment: This integration does not have any conditions.
docs-high-level-description: done
docs-installation-instructions: done
docs-removal-instructions: done
docs-triggers:
status: exempt
comment: This integration does not have any triggers.
entity-event-setup: done
entity-unique-id: done
has-entity-name: done
runtime-data: done
test-before-configure: done
test-before-setup:
status: exempt
comment: A Tile that is out of range at startup is expected and is reported as away.
unique-config-entry: done
# Silver
action-exceptions:
status: exempt
comment: This integration does not provide actions.
config-entry-unloading: done
docs-configuration-parameters:
status: exempt
comment: This integration does not have an options flow.
docs-installation-parameters: todo
entity-unavailable:
status: exempt
comment: A Tile out of range is reported as away instead of unavailable.
integration-owner: done
log-when-unavailable:
status: exempt
comment: A Tile going out of range is expected and is reported as away.
parallel-updates: done
reauthentication-flow:
status: exempt
comment: The Tile account is only used during setup to get the Tile's key, which does not change. The credentials are not stored.
test-coverage: done
# Gold
devices: done
diagnostics: todo
discovery:
status: exempt
comment: Tiles owned by other people are common, so Tiles are added through the user flow instead of discovery.
discovery-update-info:
status: exempt
comment: This integration does not use discovery.
docs-data-update: todo
docs-examples: todo
docs-known-limitations: todo
docs-supported-devices: todo
docs-supported-functions: todo
docs-troubleshooting: todo
docs-use-cases: todo
dynamic-devices:
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-translations:
status: exempt
comment: The device tracker uses the device name.
exception-translations:
status: exempt
comment: This integration does not raise exceptions.
icon-translations:
status: exempt
comment: The device tracker has no custom icon.
reconfiguration-flow:
status: exempt
comment: There is nothing to reconfigure.
repair-issues:
status: exempt
comment: This integration does not have any repair issues.
stale-devices:
status: exempt
comment: Each config entry represents a single Tile.
# Platinum
async-dependency: done
inject-websession: done
strict-typing: todo
@@ -0,0 +1,37 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]",
"no_tiles": "No Tiles were found in this Tile account."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown_tile": "This Tile is not in your Tile account. Pick another Tile.",
"wrong_tile": "The Tile did not accept the key from your Tile account. Pick another Tile."
},
"step": {
"device": {
"data": {
"address": "[%key:common::config_flow::data::device%]"
},
"data_description": {
"address": "Your Tiles are listed by name. A Tile listed by its address could not be matched to your account; Home Assistant connects to it to find out which Tile it is."
},
"description": "Pick the Tile you want to set up."
},
"user": {
"data": {
"password": "[%key:common::config_flow::data::password%]",
"username": "[%key:common::config_flow::data::email%]"
},
"data_description": {
"password": "The password of your Tile account.",
"username": "The email address of your Tile account."
},
"description": "Log in to your Tile account to get the names of your Tiles and the keys needed to ring them. Only the key of the Tile you set up is stored, not your credentials."
}
}
}
}
+1
View File
@@ -860,6 +860,7 @@ FLOWS = {
"threema",
"tibber",
"tile",
"tile_ble",
"tilt_ble",
"tilt_pi",
"time_date",
+23 -9
View File
@@ -15470,15 +15470,29 @@
},
"tile": {
"name": "Tile",
"integration_type": "hub",
"categories": [
"presence_location.trackers"
],
"connectivity": [
"cloud"
],
"config_flow": true,
"iot_class": "cloud_polling"
"integrations": {
"tile": {
"integration_type": "hub",
"config_flow": true,
"iot_class": "cloud_polling",
"categories": [
"presence_location.trackers"
],
"connectivity": [
"cloud"
],
"name": "Tile"
},
"tile_ble": {
"integration_type": "device",
"config_flow": true,
"iot_class": "local_push",
"categories": [
"presence_location.trackers"
],
"name": "Tile BLE"
}
}
},
"tilt": {
"name": "Tilt",
+3
View File
@@ -3352,6 +3352,9 @@ thingspeak==1.0.0
# homeassistant.components.lg_thinq
thinqconnect==1.0.14
# homeassistant.components.tile_ble
tile-ble==0.1.0
# homeassistant.components.tilt_ble
tilt-ble==1.0.1
+53
View File
@@ -0,0 +1,53 @@
"""Tests for the Tile BLE integration."""
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
TILE_ADDRESS = "AA:BB:CC:DD:EE:FF"
AUTH_KEY = "AAECAwQFBgcICQoLDA0ODw=="
OTHER_AUTH_KEY = "EBESExQVFhcYGRobHB0eHw=="
# Wallet's address is derived from its Tile ID; Keys' address is not.
WALLET_TILE_ID = "aabbccddeeff0102"
KEYS_TILE_ID = "5176d2dffdbca32a"
TILE_SERVICE_UUID = "0000feed-0000-1000-8000-00805f9b34fb"
TILE_SERVICE_INFO = BluetoothServiceInfo(
name="Tile",
address=TILE_ADDRESS,
rssi=-60,
manufacturer_data={},
service_data={TILE_SERVICE_UUID: b"\x02\x00\xc5\x8a\xac\xcd\x31\x2f\x47\x9e"},
service_uuids=[TILE_SERVICE_UUID],
source="local",
)
NEAR_TILE_SERVICE_INFO = BluetoothServiceInfo(
name="Tile",
address="AA:BB:CC:DD:EE:11",
rssi=-40,
manufacturer_data={},
service_data={TILE_SERVICE_UUID: b"\x02\x00\x01\x02\x03\x04\x05\x06\x07\x08"},
service_uuids=[TILE_SERVICE_UUID],
source="local",
)
NOT_TILE_SERVICE_INFO = BluetoothServiceInfo(
name="Not a Tile",
address="AA:BB:CC:DD:EE:22",
rssi=-30,
manufacturer_data={76: b"\x02\x15"},
service_data={},
service_uuids=[],
source="local",
)
async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
"""Set up the Tile BLE integration for testing."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
+71
View File
@@ -0,0 +1,71 @@
"""Common fixtures for the Tile BLE tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pytest_homeassistant.common import MockConfigEntry
from tile_ble import TileCloudTile
from homeassistant.components.tile_ble.const import CONF_AUTH_KEY, DOMAIN
from . import AUTH_KEY, KEYS_TILE_ID, OTHER_AUTH_KEY, TILE_ADDRESS, WALLET_TILE_ID
@pytest.fixture(autouse=True)
def mock_bluetooth(enable_bluetooth: None) -> None:
"""Auto mock bluetooth."""
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.tile_ble.async_setup_entry", return_value=None
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Return a Tile BLE config entry."""
return MockConfigEntry(
domain=DOMAIN,
title="Tile",
unique_id=TILE_ADDRESS,
data={CONF_AUTH_KEY: AUTH_KEY},
)
@pytest.fixture
def mock_get_tiles() -> Generator[AsyncMock]:
"""Mock getting the Tiles of the account from the Tile cloud."""
with patch(
"homeassistant.components.tile_ble.config_flow.async_get_tiles",
return_value=[
TileCloudTile(WALLET_TILE_ID, "Wallet", AUTH_KEY),
TileCloudTile(KEYS_TILE_ID, "Keys", OTHER_AUTH_KEY),
TileCloudTile("phone", "Phone", None),
],
) as mock_get_tiles:
yield mock_get_tiles
@pytest.fixture
def mock_tile_ble_device() -> Generator[MagicMock]:
"""Mock talking to a Tile over Bluetooth."""
with patch(
"homeassistant.components.tile_ble.config_flow.TileBleDevice",
autospec=True,
) as mock_device:
yield mock_device
@pytest.fixture
def mock_read_tile_id() -> Generator[AsyncMock]:
"""Mock reading the Tile ID of a Tile over Bluetooth."""
with patch(
"homeassistant.components.tile_ble.config_flow.async_read_tile_id",
return_value=KEYS_TILE_ID,
) as mock_read:
yield mock_read
@@ -0,0 +1,87 @@
# serializer version: 1
# name: test_entities.2
DeviceRegistryEntrySnapshot({
'area_id': None,
'config_entry_id': <ANY>,
'config_subentry_id': None,
'configuration_url': None,
'connections': set({
tuple(
'bluetooth',
'AA:BB:CC:DD:EE:FF',
),
}),
'disabled_by': None,
'entry_type': None,
'hw_version': None,
'id': <ANY>,
'identifiers': set({
}),
'labels': set({
}),
'manufacturer': 'Tile Inc.',
'model': None,
'model_id': None,
'name': 'Tile',
'name_by_user': None,
'serial_number': None,
'sw_version': None,
'via_device_id': None,
})
# ---
# name: test_entities[device_tracker.tile-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<DeviceTrackerEntityCapabilityAttribute.TRACKING_TYPE: 'tracking_type'>: <TrackingType.CONNECTION: 'connection'>,
}),
'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': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.tile',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': None,
'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',
'unit_of_measurement': None,
})
# ---
# name: test_entities[device_tracker.tile-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Tile',
<DeviceTrackerEntityStateAttribute.IN_ZONES: 'in_zones'>: list([
]),
<DeviceTrackerEntityStateAttribute.SOURCE_TYPE: 'source_type'>: <SourceType.BLUETOOTH_LE: 'bluetooth_le'>,
<DeviceTrackerEntityCapabilityAttribute.TRACKING_TYPE: 'tracking_type'>: <TrackingType.CONNECTION: 'connection'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.tile',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'not_home',
})
# ---
@@ -0,0 +1,312 @@
"""Tests for the Tile BLE config flow."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.components.bluetooth import inject_bluetooth_service_info
from tile_ble import (
TileBleAuthenticationError,
TileBleConnectionError,
TileCloudAuthenticationError,
TileCloudError,
)
from homeassistant.components.tile_ble.const import CONF_AUTH_KEY, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_ADDRESS, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult, FlowResultType
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
from . import (
AUTH_KEY,
NEAR_TILE_SERVICE_INFO,
NOT_TILE_SERVICE_INFO,
OTHER_AUTH_KEY,
TILE_ADDRESS,
TILE_SERVICE_INFO,
)
ACCOUNT_INPUT = {CONF_USERNAME: "user@host.com", CONF_PASSWORD: "password"}
UNMATCHED_ADDRESS = NEAR_TILE_SERVICE_INFO.address
async def _log_in(hass: HomeAssistant) -> FlowResult:
"""Log in to the Tile account and return the device step."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "device"
return result
@pytest.mark.usefixtures("mock_setup_entry", "mock_get_tiles")
async def test_user_flow(
hass: HomeAssistant,
mock_tile_ble_device: MagicMock,
mock_read_tile_id: AsyncMock,
) -> None:
"""Test setting up a Tile that is matched to the account by its address."""
for service_info in (
TILE_SERVICE_INFO,
NOT_TILE_SERVICE_INFO,
NEAR_TILE_SERVICE_INFO,
):
inject_bluetooth_service_info(hass, service_info)
result = await _log_in(hass)
# Tiles from the account come first, even when another Tile is closer.
assert list(result["data_schema"].schema[CONF_ADDRESS].container.items()) == [
(TILE_ADDRESS, "Wallet (AA:BB:CC:DD:EE:FF)"),
(UNMATCHED_ADDRESS, "AA:BB:CC:DD:EE:11 (-40 dBm)"),
]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Wallet"
assert result["data"] == {CONF_AUTH_KEY: AUTH_KEY}
assert result["result"].unique_id == TILE_ADDRESS
ble_device, auth_key = mock_tile_ble_device.call_args.args
assert ble_device.address == TILE_ADDRESS
assert auth_key == AUTH_KEY
mock_tile_ble_device.return_value.async_authenticate.assert_awaited_once()
mock_read_tile_id.assert_not_called()
@pytest.mark.usefixtures("mock_setup_entry", "mock_get_tiles")
async def test_user_flow_unmatched_tile(
hass: HomeAssistant,
mock_tile_ble_device: MagicMock,
mock_read_tile_id: AsyncMock,
) -> None:
"""Test setting up a Tile that is identified by reading its Tile ID."""
inject_bluetooth_service_info(hass, NEAR_TILE_SERVICE_INFO)
result = await _log_in(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: UNMATCHED_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Keys"
assert result["data"] == {CONF_AUTH_KEY: OTHER_AUTH_KEY}
assert result["result"].unique_id == UNMATCHED_ADDRESS
assert mock_read_tile_id.call_args.args[0].address == UNMATCHED_ADDRESS
assert mock_tile_ble_device.call_args.args[1] == OTHER_AUTH_KEY
@pytest.mark.parametrize(
("exception", "error"),
[
pytest.param(TileCloudAuthenticationError, "invalid_auth", id="invalid_auth"),
pytest.param(TileCloudError, "cannot_connect", id="cannot_connect"),
],
)
@pytest.mark.usefixtures("mock_setup_entry", "mock_tile_ble_device")
async def test_user_errors(
hass: HomeAssistant,
mock_get_tiles: AsyncMock,
exception: type[Exception],
error: str,
) -> None:
"""Test logging in to the Tile account can recover from errors."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_get_tiles.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error}
mock_get_tiles.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "device"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_account_without_tiles(
hass: HomeAssistant, mock_get_tiles: AsyncMock
) -> None:
"""Test the flow aborts when the account has no Tiles with a key."""
mock_get_tiles.return_value = []
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_tiles"
@pytest.mark.parametrize(
("exception", "error"),
[
pytest.param(TileBleAuthenticationError, "wrong_tile", id="wrong_tile"),
pytest.param(TileBleConnectionError, "cannot_connect", id="cannot_connect"),
],
)
@pytest.mark.usefixtures("mock_setup_entry", "mock_get_tiles")
async def test_authenticate_errors(
hass: HomeAssistant,
mock_tile_ble_device: MagicMock,
exception: type[Exception],
error: str,
) -> None:
"""Test checking the key over Bluetooth can recover from errors."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
result = await _log_in(hass)
mock_tile_ble_device.return_value.async_authenticate.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "device"
assert result["errors"] == {"base": error}
mock_tile_ble_device.return_value.async_authenticate.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("side_effect", "error"),
[
pytest.param(TileBleConnectionError, "cannot_connect", id="cannot_connect"),
pytest.param(["0000000000000000"], "unknown_tile", id="unknown_tile"),
],
)
@pytest.mark.usefixtures("mock_setup_entry", "mock_get_tiles", "mock_tile_ble_device")
async def test_read_tile_id_errors(
hass: HomeAssistant,
mock_read_tile_id: AsyncMock,
side_effect: type[Exception] | list[str],
error: str,
) -> None:
"""Test identifying an unmatched Tile can recover from errors."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
inject_bluetooth_service_info(hass, NEAR_TILE_SERVICE_INFO)
result = await _log_in(hass)
mock_read_tile_id.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: UNMATCHED_ADDRESS}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "device"
assert result["errors"] == {"base": error}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.usefixtures("mock_setup_entry", "mock_get_tiles")
async def test_tile_not_connectable(
hass: HomeAssistant, mock_tile_ble_device: MagicMock
) -> None:
"""Test the Tile cannot be connected to when checking the key."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
result = await _log_in(hass)
with patch(
"homeassistant.components.tile_ble.config_flow.async_ble_device_from_address",
return_value=None,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
mock_tile_ble_device.assert_not_called()
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
"service_infos",
[
pytest.param([], id="nothing_seen"),
pytest.param([NOT_TILE_SERVICE_INFO], id="no_tiles_seen"),
],
)
@pytest.mark.usefixtures("mock_get_tiles")
async def test_no_devices(
hass: HomeAssistant, service_infos: list[BluetoothServiceInfo]
) -> None:
"""Test the flow aborts when no Tiles are seen."""
for service_info in service_infos:
inject_bluetooth_service_info(hass, service_info)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
@pytest.mark.usefixtures("mock_get_tiles")
async def test_configured_tiles_skipped(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test Tiles that are already set up are not offered again."""
mock_config_entry.add_to_hass(hass)
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], ACCOUNT_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
@pytest.mark.usefixtures("mock_get_tiles")
async def test_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test a Tile set up while the form was open is not added twice."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
result = await _log_in(hass)
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ADDRESS: TILE_ADDRESS}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@@ -0,0 +1,96 @@
"""Tests for the Tile BLE device tracker."""
from collections.abc import Generator
from datetime import timedelta
import time
from unittest.mock import patch
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
async_fire_time_changed,
snapshot_platform,
)
from pytest_homeassistant.components.bluetooth import (
inject_bluetooth_service_info,
patch_all_discovered_devices,
patch_bluetooth_time,
)
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.bluetooth import (
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
)
from homeassistant.const import STATE_HOME, STATE_NOT_HOME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt as dt_util
from . import TILE_ADDRESS, TILE_SERVICE_INFO, setup_integration
ENTITY_ID = "device_tracker.tile"
@pytest.fixture(autouse=True)
def platforms() -> Generator[None]:
"""Only set up the device tracker platform."""
with patch(
"homeassistant.components.tile_ble.PLATFORMS", [Platform.DEVICE_TRACKER]
):
yield
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test the device tracker and its device."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
device = device_registry.async_get_device_by_connection(
(dr.CONNECTION_BLUETOOTH, TILE_ADDRESS), mock_config_entry.entry_id
)
assert device == snapshot
async def test_already_home(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test a Tile that is in range at startup is home."""
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_HOME
async def test_arrive_and_leave(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test a Tile is home while it advertises and away once it stops."""
start_monotonic = time.monotonic()
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_NOT_HOME
inject_bluetooth_service_info(hass, TILE_SERVICE_INFO)
await hass.async_block_till_done()
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_HOME
offset = FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
with (
patch_bluetooth_time(start_monotonic + offset),
patch_all_discovered_devices([]),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=offset))
await hass.async_block_till_done()
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_NOT_HOME
+20
View File
@@ -0,0 +1,20 @@
"""Tests for the Tile BLE integration setup."""
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
async def test_load_unload(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test the config entry loads without the Tile in range and unloads."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED