Use async_on_remove for KNX entities removal (#95658)

* Use `async_on_remove` for KNX entities removal

* review
This commit is contained in:
Matthias Alphart 2023-07-01 13:16:45 +02:00 committed by GitHub
parent 432bfffef9
commit c81b6255c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 14 deletions

View File

@ -42,8 +42,5 @@ class KnxEntity(Entity):
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Store register state change callback.""" """Store register state change callback."""
self._device.register_device_updated_cb(self.after_update_callback) self._device.register_device_updated_cb(self.after_update_callback)
# will remove all callbacks and xknx tasks
async def async_will_remove_from_hass(self) -> None: self.async_on_remove(self._device.shutdown)
"""Disconnect device object when removed."""
# will also remove all callbacks
self._device.shutdown()

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta
from functools import partial
from typing import Any from typing import Any
from xknx import XKNX from xknx import XKNX
@ -221,9 +222,9 @@ class KNXSystemSensor(SensorEntity):
self.knx.xknx.connection_manager.register_connection_state_changed_cb( self.knx.xknx.connection_manager.register_connection_state_changed_cb(
self.after_update_callback self.after_update_callback
) )
self.async_on_remove(
async def async_will_remove_from_hass(self) -> None: partial(
"""Disconnect device object when removed.""" self.knx.xknx.connection_manager.unregister_connection_state_changed_cb,
self.knx.xknx.connection_manager.unregister_connection_state_changed_cb( self.after_update_callback,
self.after_update_callback )
) )

View File

@ -99,11 +99,11 @@ async def test_removed_entity(
hass: HomeAssistant, knx: KNXTestKit, entity_registry: er.EntityRegistry hass: HomeAssistant, knx: KNXTestKit, entity_registry: er.EntityRegistry
) -> None: ) -> None:
"""Test unregister callback when entity is removed.""" """Test unregister callback when entity is removed."""
with patch(
"xknx.core.connection_manager.ConnectionManager.unregister_connection_state_changed_cb"
) as unregister_mock:
await knx.setup_integration({}) await knx.setup_integration({})
with patch.object(
knx.xknx.connection_manager, "unregister_connection_state_changed_cb"
) as unregister_mock:
entity_registry.async_update_entity( entity_registry.async_update_entity(
"sensor.knx_interface_connection_established", "sensor.knx_interface_connection_established",
disabled_by=er.RegistryEntryDisabler.USER, disabled_by=er.RegistryEntryDisabler.USER,