Add 'fire_event' command to websocket api (#63378)

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Nico Müller 2022-01-05 21:28:40 +01:00 committed by GitHub
parent 25fe213f22
commit cf1df5ff38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 0 deletions

View File

@ -44,6 +44,7 @@ def async_register_commands(
async_reg(hass, handle_call_service)
async_reg(hass, handle_entity_source)
async_reg(hass, handle_execute_script)
async_reg(hass, handle_fire_event)
async_reg(hass, handle_get_config)
async_reg(hass, handle_get_services)
async_reg(hass, handle_get_states)
@ -526,3 +527,22 @@ async def handle_execute_script(
script_obj = Script(hass, msg["sequence"], f"{const.DOMAIN} script", const.DOMAIN)
await script_obj.async_run(msg.get("variables"), context=context)
connection.send_message(messages.result_message(msg["id"], {"context": context}))
@decorators.websocket_command(
{
vol.Required("type"): "fire_event",
vol.Required("event_type"): str,
vol.Optional("event_data"): dict,
}
)
@decorators.require_admin
@decorators.async_response
async def handle_fire_event(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle fire event command."""
context = connection.context(msg)
hass.bus.async_fire(msg["event_type"], msg.get("event_data"), context=context)
connection.send_result(msg["id"], {"context": context})

View File

@ -24,6 +24,63 @@ from homeassistant.setup import DATA_SETUP_TIME, async_setup_component
from tests.common import MockEntity, MockEntityPlatform, async_mock_service
async def test_fire_event(hass, websocket_client):
"""Test fire event command."""
runs = []
async def event_handler(event):
runs.append(event)
hass.bus.async_listen_once("event_type_test", event_handler)
await websocket_client.send_json(
{
"id": 5,
"type": "fire_event",
"event_type": "event_type_test",
"event_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(runs) == 1
assert runs[0].event_type == "event_type_test"
assert runs[0].data == {"hello": "world"}
async def test_fire_event_without_data(hass, websocket_client):
"""Test fire event command."""
runs = []
async def event_handler(event):
runs.append(event)
hass.bus.async_listen_once("event_type_test", event_handler)
await websocket_client.send_json(
{
"id": 5,
"type": "fire_event",
"event_type": "event_type_test",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(runs) == 1
assert runs[0].event_type == "event_type_test"
assert runs[0].data == {}
async def test_call_service(hass, websocket_client):
"""Test call service command."""
calls = async_mock_service(hass, "domain_test", "test_service")