Store proximity settings in config entry options (#191677)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
G Johansson
2026-11-10 12:01:48 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 60abb25d26
commit 373a6ecd55
7 changed files with 148 additions and 61 deletions
+25 -7
View File
@@ -4,11 +4,12 @@ import logging
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.helpers.event import (
async_track_entity_registry_updated_event,
async_track_state_change_event,
)
from homeassistant.helpers.typing import ConfigType
from .const import CONF_TRACKED_ENTITIES, DOMAIN
from .coordinator import (
@@ -21,6 +22,8 @@ from .coordinator import (
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
@callback
def _async_migrate_tracked_entity_removed_issues(hass: HomeAssistant) -> None:
@@ -39,7 +42,9 @@ def _async_migrate_tracked_entity_removed_issues(hass: HomeAssistant) -> None:
TRACKED_ENTITY_REMOVED_ISSUE_PREFIX
)
for entry in hass.config_entries.async_entries(DOMAIN):
if entity_id not in entry.data[CONF_TRACKED_ENTITIES]:
# Entries are only migrated from data to options when set up, after this
settings = {**entry.data, **entry.options}
if entity_id not in settings[CONF_TRACKED_ENTITIES]:
continue
async_create_tracked_entity_removed_issue(hass, entry, entity_id)
if legacy_issue.dismissed_version is not None:
@@ -60,7 +65,7 @@ def _async_delete_untracked_entity_removed_issues(
issue_registry = ir.async_get(hass)
tracked_issue_ids = {
tracked_entity_removed_issue_id(entry.entry_id, entity_id)
for entity_id in entry.data[CONF_TRACKED_ENTITIES]
for entity_id in entry.options[CONF_TRACKED_ENTITIES]
}
prefix = tracked_entity_removed_issue_id(entry.entry_id, "")
for domain, issue_id in list(issue_registry.issues):
@@ -72,11 +77,24 @@ def _async_delete_untracked_entity_removed_issues(
ir.async_delete_issue(hass, DOMAIN, issue_id)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the proximity component."""
_async_migrate_tracked_entity_removed_issues(hass)
return True
async def async_migrate_entry(hass: HomeAssistant, entry: ProximityConfigEntry) -> None:
"""Migrate old entry."""
if entry.version == 1:
hass.config_entries.async_update_entry(
entry, data={}, options={**entry.data, **entry.options}, version=2
)
async def async_setup_entry(hass: HomeAssistant, entry: ProximityConfigEntry) -> None:
"""Set up Proximity from a config entry."""
_LOGGER.debug("setup %s with config:%s", entry.title, entry.data)
_LOGGER.debug("setup %s with config:%s", entry.title, entry.options)
_async_migrate_tracked_entity_removed_issues(hass)
_async_delete_untracked_entity_removed_issues(hass, entry)
coordinator = ProximityDataUpdateCoordinator(hass, entry)
@@ -84,7 +102,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ProximityConfigEntry) ->
entry.async_on_unload(
async_track_state_change_event(
hass,
entry.data[CONF_TRACKED_ENTITIES],
entry.options[CONF_TRACKED_ENTITIES],
coordinator.async_check_proximity_state_change,
)
)
@@ -92,7 +110,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ProximityConfigEntry) ->
entry.async_on_unload(
async_track_entity_registry_updated_event(
hass,
entry.data[CONF_TRACKED_ENTITIES],
entry.options[CONF_TRACKED_ENTITIES],
coordinator.async_check_tracked_entity_change,
)
)
@@ -7,7 +7,11 @@ import probatio
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.person import DOMAIN as PERSON_DOMAIN
from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult, OptionsFlow
from homeassistant.config_entries import (
ConfigFlow,
ConfigFlowResult,
OptionsFlowWithReload,
)
from homeassistant.const import CONF_ZONE, UnitOfLength
from homeassistant.core import State, callback
from homeassistant.helpers.selector import (
@@ -60,7 +64,7 @@ def _base_schema(user_input: dict[str, Any]) -> VolDictType:
class ProximityConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a proximity config flow."""
VERSION = 1
VERSION = 2
def _user_form_schema(
self, user_input: dict[str, Any] | None = None
@@ -110,7 +114,9 @@ class ProximityConfigFlow(ConfigFlow, domain=DOMAIN):
tries += 1
possible_title = f"{title} {tries}"
return self.async_create_entry(title=possible_title, data=user_input)
return self.async_create_entry(
title=possible_title, data={}, options=user_input
)
return self.async_show_form(
step_id="user",
@@ -118,7 +124,7 @@ class ProximityConfigFlow(ConfigFlow, domain=DOMAIN):
)
class ProximityOptionsFlow(OptionsFlow):
class ProximityOptionsFlow(OptionsFlowWithReload):
"""Handle a option flow."""
def _user_form_schema(self, user_input: dict[str, Any]) -> probatio.Schema:
@@ -129,16 +135,11 @@ class ProximityOptionsFlow(OptionsFlow):
) -> ConfigFlowResult:
"""Handle options flow."""
if user_input is not None:
# Settings are stored in data, so OptionsFlowWithReload would not reload
if self.hass.config_entries.async_update_entry(
self.config_entry, data={**self.config_entry.data, **user_input}
):
self.hass.config_entries.async_schedule_reload(
self.config_entry.entry_id
)
return self.async_create_entry(title=self.config_entry.title, data={})
return self.async_create_entry(
data={**self.config_entry.options, **user_input}
)
return self.async_show_form(
step_id="init",
data_schema=self._user_form_schema(dict(self.config_entry.data)),
data_schema=self._user_form_schema(dict(self.config_entry.options)),
)
@@ -125,11 +125,11 @@ class ProximityDataUpdateCoordinator(DataUpdateCoordinator[ProximityData]):
def __init__(self, hass: HomeAssistant, config_entry: ProximityConfigEntry) -> None:
"""Initialize the Proximity coordinator."""
self.ignored_zone_ids: list[str] = config_entry.data[CONF_IGNORED_ZONES]
self.tracked_entities: list[str] = config_entry.data[CONF_TRACKED_ENTITIES]
self.tolerance: int = config_entry.data[CONF_TOLERANCE]
self.proximity_zone_id: str = config_entry.data[CONF_ZONE]
self.unit_of_measurement: str = config_entry.data.get(
self.ignored_zone_ids: list[str] = config_entry.options[CONF_IGNORED_ZONES]
self.tracked_entities: list[str] = config_entry.options[CONF_TRACKED_ENTITIES]
self.tolerance: int = config_entry.options[CONF_TOLERANCE]
self.proximity_zone_id: str = config_entry.options[CONF_ZONE]
self.unit_of_measurement: str = config_entry.options.get(
CONF_UNIT_OF_MEASUREMENT, hass.config.units.length_unit
)
self.entity_mapping: dict[str, list[str]] = defaultdict(list)
@@ -186,8 +186,8 @@ class ProximityDataUpdateCoordinator(DataUpdateCoordinator[ProximityData]):
self.hass.config_entries.async_update_entry(
self.config_entry,
data={
**self.config_entry.data,
options={
**self.config_entry.options,
CONF_TRACKED_ENTITIES: [
tracked_entity
for tracked_entity in (
@@ -81,6 +81,13 @@
}),
'entry': dict({
'data': dict({
}),
'disabled_by': None,
'discovery_keys': dict({
}),
'domain': 'proximity',
'minor_version': 1,
'options': dict({
'ignored_zones': list([
]),
'tolerance': 1,
@@ -92,13 +99,6 @@
]),
'zone': 'zone.home',
}),
'disabled_by': None,
'discovery_keys': dict({
}),
'domain': 'proximity',
'minor_version': 1,
'options': dict({
}),
'pref_disable_new_entities': False,
'pref_disable_polling': False,
'source': 'user',
@@ -106,7 +106,7 @@
]),
'title': 'home',
'unique_id': 'proximity_home',
'version': 1,
'version': 2,
}),
})
# ---
+12 -7
View File
@@ -67,7 +67,8 @@ async def test_user_flow(
user_input=user_input,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == expected_result
assert result["data"] == {}
assert result["options"] == expected_result
zone = hass.states.get(user_input[CONF_ZONE])
assert result["title"] == zone.name
@@ -108,7 +109,8 @@ async def test_options_flow(
mock_config = MockConfigEntry(
domain=DOMAIN,
title="home",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: ["zone.work"],
@@ -134,8 +136,8 @@ async def test_options_flow(
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert mock_config.data == {CONF_ZONE: "zone.home", **user_input}
assert mock_config.options == {}
assert mock_config.data == {}
assert mock_config.options == {CONF_ZONE: "zone.home", **user_input}
assert mock_setup_entry.call_count == expected_setup_calls
@@ -150,7 +152,8 @@ async def test_abort_duplicated_entry(hass: HomeAssistant) -> None:
mock_config = MockConfigEntry(
domain=DOMAIN,
title="home",
data=DATA,
version=2,
options=DATA,
unique_id=f"{DOMAIN}_home",
)
mock_config.add_to_hass(hass)
@@ -176,7 +179,8 @@ async def test_avoid_duplicated_title(hass: HomeAssistant) -> None:
MockConfigEntry(
domain=DOMAIN,
title="home",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: ["zone.work"],
@@ -188,7 +192,8 @@ async def test_avoid_duplicated_title(hass: HomeAssistant) -> None:
MockConfigEntry(
domain=DOMAIN,
title="home 3",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test2"],
CONF_IGNORED_ZONES: ["zone.work"],
@@ -48,7 +48,8 @@ async def test_entry_diagnostics(
mock_entry = MockConfigEntry(
domain=DOMAIN,
title="home",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: [
"device_tracker.test1",
@@ -90,7 +91,8 @@ async def test_entry_diagnostics_renamed_entity(
mock_entry = MockConfigEntry(
domain=DOMAIN,
title="home",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: [],
+78 -17
View File
@@ -16,7 +16,7 @@ from homeassistant.components.proximity.const import (
CONF_TRACKED_ENTITIES,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState
from homeassistant.const import (
ATTR_FRIENDLY_NAME,
CONF_ZONE,
@@ -42,7 +42,8 @@ async def async_setup_single_entry(
mock_config = MockConfigEntry(
domain=DOMAIN,
title="Home",
data={
version=2,
options={
CONF_ZONE: zone,
CONF_TRACKED_ENTITIES: tracked_entites,
CONF_IGNORED_ZONES: ignored_zones,
@@ -78,7 +79,8 @@ async def test_proximities(hass: HomeAssistant, config: dict) -> None:
mock_config = MockConfigEntry(
domain=DOMAIN,
title=title,
data=config,
version=2,
options=config,
)
mock_config.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config.entry_id)
@@ -417,7 +419,8 @@ async def test_overlapping_zones_in_zones_reports_arrived(
home_config = MockConfigEntry(
domain=DOMAIN,
title="Home",
data={
version=2,
options={
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: [],
@@ -427,7 +430,8 @@ async def test_overlapping_zones_in_zones_reports_arrived(
backyard_config = MockConfigEntry(
domain=DOMAIN,
title="Backyard",
data={
version=2,
options={
CONF_ZONE: "zone.backyard",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: [],
@@ -990,18 +994,29 @@ async def test_create_removed_tracked_entity_issue(
def _mock_proximity_entry(
hass: HomeAssistant, title: str, zone: str, tracked_entities: list[str]
hass: HomeAssistant,
title: str,
zone: str,
tracked_entities: list[str],
*,
version: int = 2,
disabled_by: ConfigEntryDisabler | None = None,
) -> MockConfigEntry:
"""Add a proximity config entry to hass without setting it up."""
settings = {
CONF_ZONE: zone,
CONF_TRACKED_ENTITIES: tracked_entities,
CONF_IGNORED_ZONES: [],
CONF_TOLERANCE: 1,
}
# Version 1 entries store their settings in data
entry = MockConfigEntry(
domain=DOMAIN,
title=title,
data={
CONF_ZONE: zone,
CONF_TRACKED_ENTITIES: tracked_entities,
CONF_IGNORED_ZONES: [],
CONF_TOLERANCE: 1,
},
version=version,
data=settings if version == 1 else {},
options=settings if version > 1 else {},
disabled_by=disabled_by,
)
entry.add_to_hass(hass)
return entry
@@ -1102,19 +1117,42 @@ async def test_removed_tracked_entity_issue_deleted_when_untracked(
pytest.param("2025.1.0", HA_VERSION, id="ignored"),
],
)
@pytest.mark.parametrize(
"entry_version",
[
pytest.param(1, id="settings_in_data"),
pytest.param(2, id="settings_in_options"),
],
)
async def test_migrate_legacy_removed_tracked_entity_issue(
hass: HomeAssistant,
hass_storage: dict[str, Any],
issue_registry: ir.IssueRegistry,
legacy_dismissed_version: str | None,
expected_dismissed_version: str | None,
entry_version: int,
) -> None:
"""Test a legacy removed tracked entity issue is migrated per config entry."""
tracked_entity_id = "device_tracker.test1"
untracked_entity_id = "device_tracker.test2"
home_entry = _mock_proximity_entry(hass, "Home", "zone.home", [tracked_entity_id])
work_entry = _mock_proximity_entry(hass, "Work", "zone.work", [tracked_entity_id])
other_entry = _mock_proximity_entry(hass, "Other", "zone.home", [])
home_entry = _mock_proximity_entry(
hass, "Home", "zone.home", [tracked_entity_id], version=entry_version
)
work_entry = _mock_proximity_entry(
hass, "Work", "zone.work", [tracked_entity_id], version=entry_version
)
other_entry = _mock_proximity_entry(
hass, "Other", "zone.home", [], version=entry_version
)
# Disabled entries are not set up, so they are never migrated
disabled_entry = _mock_proximity_entry(
hass,
"Disabled",
"zone.work",
[tracked_entity_id],
version=1,
disabled_by=ConfigEntryDisabler.USER,
)
hass_storage[ir.STORAGE_KEY] = {
"version": ir.STORAGE_VERSION_MAJOR,
"minor_version": ir.STORAGE_VERSION_MINOR,
@@ -1171,8 +1209,10 @@ async def test_migrate_legacy_removed_tracked_entity_issue(
{"entity_id": tracked_entity_id, "name": entry.title},
expected_dismissed_version,
)
for entry in (home_entry, work_entry)
for entry in (home_entry, work_entry, disabled_entry)
}
assert home_entry.state is ConfigEntryState.LOADED
assert work_entry.state is ConfigEntryState.LOADED
assert other_entry.state is ConfigEntryState.LOADED
@@ -1208,7 +1248,7 @@ async def test_track_renamed_tracked_entity(
entry = hass.config_entries.async_get_entry(mock_config.entry_id)
assert entry
assert entry.data[CONF_TRACKED_ENTITIES] == [f"{t1.entity_id}_renamed"]
assert entry.options[CONF_TRACKED_ENTITIES] == [f"{t1.entity_id}_renamed"]
async def test_sensor_unique_ids(
@@ -1372,3 +1412,24 @@ async def test_tracked_zone_location_is_changed(hass: HomeAssistant) -> None:
assert state.state == "1244478"
state = hass.states.get(f"{entity_base_name}_direction_of_travel")
assert state.state == STATE_UNKNOWN
async def test_migrate_data_to_options(hass: HomeAssistant) -> None:
"""Test a version 1 entry moves its settings from data to options."""
config = {
CONF_ZONE: "zone.home",
CONF_TRACKED_ENTITIES: ["device_tracker.test1"],
CONF_IGNORED_ZONES: ["zone.work"],
CONF_TOLERANCE: 1,
}
mock_config = MockConfigEntry(domain=DOMAIN, title="Home", version=1, data=config)
mock_config.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config.entry_id)
await hass.async_block_till_done()
assert mock_config.state is ConfigEntryState.LOADED
assert mock_config.version == 2
assert mock_config.data == {}
assert mock_config.options == config
assert hass.states.get("sensor.home_nearest_device") is not None