Switch async_track_state_change to the faster async_track_state_change_event part 3 (#37852)

async_track_state_change_event is faster than async_track_state_change
This commit is contained in:
J. Nick Koston authored and GitHub committed 2020-07-14 09:40:01 -10:00
1 parent ea17d36cbb
commit 5cd6370822
3 files changed
+76 -58

No files matched your search

+19 -10
View File
@@ -31,7 +31,7 @@ import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.device_registry as dr
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.json import JSONEncoder
from homeassistant.helpers.storage import Store
from homeassistant.helpers.template import Template
@@ -133,23 +133,32 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool
)
)
async def send_home_assistant_state(
entity_id: str, _, new_state: Optional[State]
) -> None:
"""Forward Home Assistant states to ESPHome."""
async def send_home_assistant_state_event(event: Event) -> None:
"""Forward Home Assistant states updates to ESPHome."""
new_state = event.data.get("new_state")
if new_state is None:
return
entity_id = event.data.get("entity_id")
await cli.send_home_assistant_state(entity_id, new_state.state)
async def _send_home_assistant_state(
entity_id: str, new_state: Optional[State]
) -> None:
"""Forward Home Assistant states to ESPHome."""
await cli.send_home_assistant_state(entity_id, new_state.state)
@callback
def async_on_state_subscription(entity_id: str) -> None:
"""Subscribe and forward states for requested entities."""
unsub = async_track_state_change(hass, entity_id, send_home_assistant_state)
entry_data.disconnect_callbacks.append(unsub)
# Send initial state
hass.async_create_task(
send_home_assistant_state(entity_id, None, hass.states.get(entity_id))
unsub = async_track_state_change_event(
hass, [entity_id], send_home_assistant_state_event
)
entry_data.disconnect_callbacks.append(unsub)
new_state = hass.states.get(entity_id)
if new_state is None:
return
# Send initial state
hass.async_create_task(_send_home_assistant_state(entity_id, new_state))
async def on_login() -> None:
"""Subscribe to states and list entities on successful API login."""