Skip to content

Commit

Permalink
Update event tracking (#212)
Browse files Browse the repository at this point in the history
* Update event tracking

* Bump pytest-homeassistant-custom-component

* fix logic

* More changes

* Fixes

* Remove stuff

* Remove unnecessary variable
  • Loading branch information
raman325 authored Jun 15, 2024
1 parent 1edf87c commit d0a3c97
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 54 deletions.
56 changes: 29 additions & 27 deletions custom_components/lock_code_manager/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,23 @@
from homeassistant.const import (
CONF_NAME,
CONF_PIN,
MATCH_ALL,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.core import (
Event,
EventStateChangedData,
HomeAssistant,
State,
callback,
)
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.event import TrackStates, async_track_state_change_filtered
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import (
Expand Down Expand Up @@ -60,7 +65,11 @@ async def async_setup_entry(
def add_pin_active_entity(slot_num: int, ent_reg: er.EntityRegistry) -> None:
"""Add active binary sensor entities for slot."""
async_add_entities(
[LockCodeManagerActiveEntity(hass, ent_reg, config_entry, slot_num)],
[
LockCodeManagerActiveEntity(
hass, ent_reg, config_entry, slot_num, ATTR_ACTIVE
)
],
True,
)

Expand Down Expand Up @@ -101,19 +110,6 @@ class LockCodeManagerActiveEntity(BaseLockCodeManagerEntity, BinarySensorEntity)

_attr_entity_category = EntityCategory.DIAGNOSTIC

def __init__(
self,
hass: HomeAssistant,
ent_reg: er.EntityRegistry,
config_entry: ConfigEntry,
slot_num: int,
) -> None:
"""Initialize entity."""
BaseLockCodeManagerEntity.__init__(
self, hass, ent_reg, config_entry, slot_num, ATTR_ACTIVE
)
self._entity_id_map: dict[str, str] = {}

@callback
def _update_state(self, _: datetime | None = None) -> None:
"""Update binary sensor state by getting dependent states."""
Expand Down Expand Up @@ -158,10 +154,10 @@ async def _config_entry_update_listener(

@callback
def _handle_calendar_state_changes(
self, entity_id: str, _: State, __: State
self, event: Event[EventStateChangedData]
) -> None:
"""Handle calendar state changes."""
if entity_id == self._calendar_entity_id:
if event.data["entity_id"] == self._calendar_entity_id:
self._update_state()

async def async_added_to_hass(self) -> None:
Expand All @@ -170,9 +166,11 @@ async def async_added_to_hass(self) -> None:
await BaseLockCodeManagerEntity.async_added_to_hass(self)

self.async_on_remove(
async_track_state_change(
self.hass, MATCH_ALL, self._handle_calendar_state_changes
)
async_track_state_change_filtered(
self.hass,
TrackStates(True, set(), set()),
self._handle_calendar_state_changes,
).async_remove
)

self.async_on_remove(
Expand Down Expand Up @@ -250,12 +248,14 @@ def _get_entity_state(self, key: str) -> str | None:
return state.state

async def _async_update_state(
self,
entity_id: str | None = None,
from_state: State | None = None,
to_state: State | None = None,
self, event: Event[EventStateChangedData] | None = None
) -> None:
"""Update binary sensor state by getting dependent states."""
entity_id: str | None = None
to_state: State | None = None
if event:
entity_id = event.data["entity_id"]
to_state = event.data["new_state"]
if entity_id is not None and (
not (ent_entry := self.ent_reg.async_get(entity_id))
or ent_entry.platform != DOMAIN
Expand Down Expand Up @@ -341,6 +341,8 @@ async def async_added_to_hass(self) -> None:
# await CoordinatorEntity.async_added_to_hass(self)

self.async_on_remove(
async_track_state_change(self.hass, MATCH_ALL, self._async_update_state)
async_track_state_change_filtered(
self.hass, TrackStates(True, set(), set()), self._async_update_state
).async_remove
)
await self._async_update_state()
54 changes: 27 additions & 27 deletions custom_components/lock_code_manager/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@
from typing import Any, final

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_ENTITY_ID,
MATCH_ALL,
STATE_UNAVAILABLE,
STATE_UNLOCKED,
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNLOCKED
from homeassistant.core import (
Event,
EventStateChangedData,
HomeAssistant,
State,
callback,
)
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo, Entity, EntityCategory
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.event import TrackStates, async_track_state_change_filtered

from .const import (
ATTR_CODE_SLOT,
Expand Down Expand Up @@ -126,11 +127,8 @@ async def _internal_async_remove(self) -> None:
)
await self._async_remove()
await self.async_remove(force_remove=True)
_LOGGER.error("tes†")
_LOGGER.error(self.entity_id)
if self.ent_reg.async_get(self.entity_id):
self.ent_reg.async_remove(self.entity_id)
_LOGGER.error(self.hass.states.get(self.entity_id))

async def _async_remove(self) -> None:
"""
Expand Down Expand Up @@ -219,16 +217,27 @@ def _is_available(self) -> bool:

@callback
def _handle_available_state_update(
self,
entity_id: str | None = None,
_: State | None = None,
__: State | None = None,
self, event: Event[EventStateChangedData] | None = None
) -> None:
"""Handle availability state update."""
"""Update binary sensor state by getting dependent states."""
entity_id: str | None = None
from_state: State | None = None
to_state: State | None = None
if event:
entity_id = event.data["entity_id"]
from_state = event.data["old_state"]
to_state = event.data["new_state"]

if entity_id is not None and entity_id not in (
lock.lock.entity_id for lock in self.locks
):
return

if (from_state and STATE_UNAVAILABLE != from_state.state) and (
to_state and STATE_UNAVAILABLE != to_state.state
):
return

if (new_available := self._is_available()) != self._attr_available:
self._attr_available: bool = new_available
self.async_write_ha_state()
Expand All @@ -239,20 +248,11 @@ async def async_added_to_hass(self) -> None:

self.dispatcher_connect()
self.async_on_remove(
async_track_state_change(
async_track_state_change_filtered(
self.hass,
MATCH_ALL,
TrackStates(True, set(), set()),
self._handle_available_state_update,
to_state=STATE_UNAVAILABLE,
)
)
self.async_on_remove(
async_track_state_change(
self.hass,
MATCH_ALL,
self._handle_available_state_update,
from_state=STATE_UNAVAILABLE,
)
).async_remove
)
self._handle_available_state_update()

Expand Down

0 comments on commit d0a3c97

Please sign in to comment.