Simplify mqtt switch state message processor (#118187)
This commit is contained in:
parent
e74292e358
commit
f0b4f4655c
1 changed files with 7 additions and 13 deletions
|
@ -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:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue