From 7ed1d4988b44942c5d5f9e687e369d3ff0b85d36 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Tue, 6 Dec 2022 09:31:19 +0100 Subject: [PATCH] Add QoS parameter to MQTT websocket_subscribe (#83241) --- homeassistant/components/mqtt/__init__.py | 4 ++- tests/components/mqtt/test_init.py | 31 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 1c0df640c08..37b947050b7 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -573,6 +573,7 @@ def websocket_mqtt_info( { vol.Required("type"): "mqtt/subscribe", vol.Required("topic"): valid_subscribe_topic, + vol.Optional("qos"): valid_qos_schema, } ) @websocket_api.async_response @@ -606,8 +607,9 @@ async def websocket_subscribe( ) # Perform UTF-8 decoding directly in callback routine + qos: int = msg["qos"] if "qos" in msg else DEFAULT_QOS connection.subscriptions[msg["id"]] = await async_subscribe( - hass, msg["topic"], forward_messages, encoding=None + hass, msg["topic"], forward_messages, encoding=None, qos=qos ) connection.send_message(websocket_api.result_message(msg["id"])) diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 3388854fce5..38849167959 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -2021,6 +2021,37 @@ async def test_mqtt_ws_subscription( response = await client.receive_json() assert response["success"] + # Subscribe with QoS 2 + await client.send_json( + {"id": 9, "type": "mqtt/subscribe", "topic": "test-topic", "qos": 2} + ) + response = await client.receive_json() + assert response["success"] + + async_fire_mqtt_message(hass, "test-topic", "test1", 2) + async_fire_mqtt_message(hass, "test-topic", "test2", 2) + async_fire_mqtt_message(hass, "test-topic", b"\xDE\xAD\xBE\xEF", 2) + + response = await client.receive_json() + assert response["event"]["topic"] == "test-topic" + assert response["event"]["payload"] == "test1" + assert response["event"]["qos"] == 2 + + response = await client.receive_json() + assert response["event"]["topic"] == "test-topic" + assert response["event"]["payload"] == "test2" + assert response["event"]["qos"] == 2 + + response = await client.receive_json() + assert response["event"]["topic"] == "test-topic" + assert response["event"]["payload"] == "b'\\xde\\xad\\xbe\\xef'" + assert response["event"]["qos"] == 2 + + # Unsubscribe + await client.send_json({"id": 15, "type": "unsubscribe_events", "subscription": 9}) + response = await client.receive_json() + assert response["success"] + async def test_mqtt_ws_subscription_not_admin( hass, hass_ws_client, mqtt_mock_entry_no_yaml_config, hass_read_only_access_token