Significantly improve performance of conversation default_agent listening for new states (#93577)

Use the async_track_state_added_domain helper instead of tracking
all state changes and rejecting them as it is already optimized
for this job
This commit is contained in:
J. Nick Koston 2023-05-25 22:04:38 -05:00 committed by GitHub
parent f251c464e2
commit e2b69fc470
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -31,7 +31,7 @@ from homeassistant.helpers import (
template, template,
translation, translation,
) )
from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers.event import async_track_state_added_domain
from homeassistant.util.json import JsonObjectType, json_loads_object from homeassistant.util.json import JsonObjectType, json_loads_object
from .agent import AbstractConversationAgent, ConversationInput, ConversationResult from .agent import AbstractConversationAgent, ConversationInput, ConversationResult
@ -83,22 +83,16 @@ def async_setup(hass: core.HomeAssistant) -> None:
async_should_expose(hass, DOMAIN, entity_id) async_should_expose(hass, DOMAIN, entity_id)
@core.callback @core.callback
def async_entity_state_listener( def async_entity_state_listener(event: core.Event) -> None:
changed_entity: str,
old_state: core.State | None,
new_state: core.State | None,
):
"""Set expose flag on new entities.""" """Set expose flag on new entities."""
if old_state is not None or new_state is None: async_should_expose(hass, DOMAIN, event.data["entity_id"])
return
async_should_expose(hass, DOMAIN, changed_entity)
@core.callback @core.callback
def async_hass_started(hass: core.HomeAssistant) -> None: def async_hass_started(hass: core.HomeAssistant) -> None:
"""Set expose flag on all entities.""" """Set expose flag on all entities."""
for state in hass.states.async_all(): for state in hass.states.async_all():
async_should_expose(hass, DOMAIN, state.entity_id) async_should_expose(hass, DOMAIN, state.entity_id)
async_track_state_change(hass, MATCH_ALL, async_entity_state_listener) async_track_state_added_domain(hass, MATCH_ALL, async_entity_state_listener)
start.async_at_started(hass, async_hass_started) start.async_at_started(hass, async_hass_started)