From c2f16cf21d06a44cc7d8f7cd5c9631e6b936128a Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 8 Sep 2020 23:11:42 +0200 Subject: [PATCH] Fix MQTT light value template (#39820) --- .../components/mqtt/light/schema_basic.py | 4 +++ tests/components/mqtt/test_light.py | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/homeassistant/components/mqtt/light/schema_basic.py b/homeassistant/components/mqtt/light/schema_basic.py index 54af71b3e05..e19fcbf0e40 100644 --- a/homeassistant/components/mqtt/light/schema_basic.py +++ b/homeassistant/components/mqtt/light/schema_basic.py @@ -35,6 +35,7 @@ from homeassistant.const import ( CONF_PAYLOAD_OFF, CONF_PAYLOAD_ON, CONF_UNIQUE_ID, + CONF_VALUE_TEMPLATE, STATE_ON, ) from homeassistant.core import callback @@ -157,6 +158,9 @@ async def async_setup_entity_basic( hass, config, async_add_entities, config_entry, discovery_data=None ): """Set up a MQTT Light.""" + if CONF_STATE_VALUE_TEMPLATE not in config and CONF_VALUE_TEMPLATE in config: + config[CONF_STATE_VALUE_TEMPLATE] = config[CONF_VALUE_TEMPLATE] + async_add_entities([MqttLight(hass, config, config_entry, discovery_data)]) diff --git a/tests/components/mqtt/test_light.py b/tests/components/mqtt/test_light.py index 56a5b4012c8..da4d90ad5ec 100644 --- a/tests/components/mqtt/test_light.py +++ b/tests/components/mqtt/test_light.py @@ -648,6 +648,35 @@ async def test_controlling_state_via_topic_with_templates(hass, mqtt_mock): assert state.attributes.get("xy_color") == (0.14, 0.131) +async def test_controlling_state_via_topic_with_value_template(hass, mqtt_mock): + """Test the setting of the state with undocumented value_template.""" + config = { + light.DOMAIN: { + "platform": "mqtt", + "name": "test", + "state_topic": "test_light_rgb/status", + "command_topic": "test_light_rgb/set", + "value_template": "{{ value_json.hello }}", + } + } + + assert await async_setup_component(hass, light.DOMAIN, config) + await hass.async_block_till_done() + + state = hass.states.get("light.test") + assert state.state == STATE_OFF + + async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') + + state = hass.states.get("light.test") + assert state.state == STATE_ON + + async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "OFF"}') + + state = hass.states.get("light.test") + assert state.state == STATE_OFF + + async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): """Test the sending of command in optimistic mode.""" config = {