Google Assistant: parallize as many requests as possible (#33472)

* Google Assistant: parallize as many requests as possible

* Fix double comment
This commit is contained in:
Paulus Schoutsen 2020-03-31 12:01:31 -07:00 committed by GitHub
parent f085a0c54a
commit 06216a8a45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 15 deletions

View File

@ -131,6 +131,24 @@ async def async_devices_query(hass, data, payload):
return {"devices": devices}
async def _entity_execute(entity, data, executions):
"""Execute all commands for an entity.
Returns a dict if a special result needs to be set.
"""
for execution in executions:
try:
await entity.execute(data, execution)
except SmartHomeError as err:
return {
"ids": [entity.entity_id],
"status": "ERROR",
**err.to_response(),
}
return None
@HANDLERS.register("action.devices.EXECUTE")
async def handle_devices_execute(hass, data, payload):
"""Handle action.devices.EXECUTE request.
@ -138,6 +156,7 @@ async def handle_devices_execute(hass, data, payload):
https://developers.google.com/assistant/smarthome/develop/process-intents#EXECUTE
"""
entities = {}
executions = {}
results = {}
for command in payload["commands"]:
@ -159,7 +178,10 @@ async def handle_devices_execute(hass, data, payload):
if entity_id in results:
continue
if entity_id not in entities:
if entity_id in entities:
executions[entity_id].append(execution)
continue
state = hass.states.get(entity_id)
if state is None:
@ -171,15 +193,18 @@ async def handle_devices_execute(hass, data, payload):
continue
entities[entity_id] = GoogleEntity(hass, data.config, state)
executions[entity_id] = [execution]
try:
await entities[entity_id].execute(data, execution)
except SmartHomeError as err:
results[entity_id] = {
"ids": [entity_id],
"status": "ERROR",
**err.to_response(),
}
execute_results = await asyncio.gather(
*[
_entity_execute(entities[entity_id], data, executions[entity_id])
for entity_id in executions
]
)
for entity_id, result in zip(executions, execute_results):
if result is not None:
results[entity_id] = result
final_results = list(results.values())

View File

@ -442,6 +442,9 @@ async def test_execute(hass):
"source": "cloud",
}
service_events = sorted(
service_events, key=lambda ev: ev.data["service_data"]["entity_id"]
)
assert len(service_events) == 4
assert service_events[0].data == {
"domain": "light",