diff --git a/homeassistant/components/mqtt/switch.py b/homeassistant/components/mqtt/switch.py index fb33c16fd74..c11e843fc9b 100644 --- a/homeassistant/components/mqtt/switch.py +++ b/homeassistant/components/mqtt/switch.py @@ -90,18 +90,17 @@ class MqttSwitch(MqttEntity, SwitchEntity, RestoreEntity): def _setup_from_config(self, config: ConfigType) -> None: """(Re)Setup the entity.""" self._attr_device_class = config.get(CONF_DEVICE_CLASS) - state_on: str | None = config.get(CONF_STATE_ON) - self._state_on = state_on if state_on else config[CONF_PAYLOAD_ON] - state_off: str | None = config.get(CONF_STATE_OFF) - self._state_off = state_off if state_off else config[CONF_PAYLOAD_OFF] - + self._is_on_map = { + state_on if state_on else config[CONF_PAYLOAD_ON]: True, + state_off if state_off else config[CONF_PAYLOAD_OFF]: False, + PAYLOAD_NONE: None, + } self._optimistic = ( config[CONF_OPTIMISTIC] or config.get(CONF_STATE_TOPIC) is None ) self._attr_assumed_state = bool(self._optimistic) - self._value_template = MqttValueTemplate( self._config.get(CONF_VALUE_TEMPLATE), entity=self ).async_render_with_possible_json_value @@ -109,13 +108,8 @@ class MqttSwitch(MqttEntity, SwitchEntity, RestoreEntity): @callback def _state_message_received(self, msg: ReceiveMessage) -> None: """Handle new MQTT state messages.""" - payload = self._value_template(msg.payload) - if payload == self._state_on: - self._attr_is_on = True - elif payload == self._state_off: - self._attr_is_on = False - elif payload == PAYLOAD_NONE: - self._attr_is_on = None + if (payload := self._value_template(msg.payload)) in self._is_on_map: + self._attr_is_on = self._is_on_map[payload] @callback def _prepare_subscribe_topics(self) -> None: