Cleanup async_track_state_change and augment docstring (#37251)

* Cleanup async_track_state_change and augment docstrings.

Skip from_state and to_state matching in
async_track_state_change when they are None

Optimize the state change listener for the most
common use case: no to_state and from_state
matching.

* Update benchmark to be more realistic (previously we assumed only one entity was present in the whole instance)

* Add more tests to ensure behavior is preserved

* Ensure new behavior matches test

* remove MATCH_ALL from zone automation since its the default anyways

* Might as well use async_track_state_change_event instead since MATCH_ALL is removed
This commit is contained in:
J. Nick Koston authored and GitHub committed 2020-07-05 17:31:33 -05:00
1 parent 2088092f7c
commit 34ccb6588c
4 files changed
+163 -32

No files matched your search

+42 -3
View File
@@ -114,7 +114,7 @@ async def time_changed_helper(hass):
@benchmark
async def state_changed_helper(hass):
"""Run a million events through state changed helper."""
"""Run a million events through state changed helper with 1000 entities."""
count = 0
entity_id = "light.kitchen"
event = asyncio.Event()
@@ -128,9 +128,48 @@ async def state_changed_helper(hass):
if count == 10 ** 6:
event.set()
hass.helpers.event.async_track_state_change(entity_id, listener, "off", "on")
for idx in range(1000):
hass.helpers.event.async_track_state_change(
f"{entity_id}{idx}", listener, "off", "on"
)
event_data = {
"entity_id": entity_id,
"entity_id": f"{entity_id}0",
"old_state": core.State(entity_id, "off"),
"new_state": core.State(entity_id, "on"),
}
for _ in range(10 ** 6):
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
start = timer()
await event.wait()
return timer() - start
@benchmark
async def state_changed_event_helper(hass):
"""Run a million events through state changed event helper with 1000 entities."""
count = 0
entity_id = "light.kitchen"
event = asyncio.Event()
@core.callback
def listener(*args):
"""Handle event."""
nonlocal count
count += 1
if count == 10 ** 6:
event.set()
hass.helpers.event.async_track_state_change_event(
[f"{entity_id}{idx}" for idx in range(1000)], listener
)
event_data = {
"entity_id": f"{entity_id}0",
"old_state": core.State(entity_id, "off"),
"new_state": core.State(entity_id, "on"),
}