Update MQTT number to treat received payload as UTF-8 (#52121)

* Update MQTT number to treat received payload as UTF-8

* Lint
This commit is contained in:
Erik Montnemery 2021-06-23 15:35:18 +02:00 committed by GitHub
parent a374e24843
commit 77de233679
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 10 deletions

View File

@ -44,7 +44,7 @@ DEFAULT_OPTIMISTIC = False
def validate_config(config): def validate_config(config):
"""Validate that the configuration is valid, throws if it isn't.""" """Validate that the configuration is valid, throws if it isn't."""
if config.get(CONF_MIN) >= config.get(CONF_MAX): if config.get(CONF_MIN) >= config.get(CONF_MAX):
raise vol.Invalid(f"'{CONF_MAX}'' must be > '{CONF_MIN}'") raise vol.Invalid(f"'{CONF_MAX}' must be > '{CONF_MIN}'")
return config return config
@ -94,10 +94,10 @@ class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
def __init__(self, config, config_entry, discovery_data): def __init__(self, config, config_entry, discovery_data):
"""Initialize the MQTT Number.""" """Initialize the MQTT Number."""
self._config = config self._config = config
self._optimistic = False
self._sub_state = None self._sub_state = None
self._current_number = None self._current_number = None
self._optimistic = config.get(CONF_OPTIMISTIC)
NumberEntity.__init__(self) NumberEntity.__init__(self)
MqttEntity.__init__(self, None, config, config_entry, discovery_data) MqttEntity.__init__(self, None, config, config_entry, discovery_data)
@ -107,6 +107,10 @@ class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
"""Return the config schema.""" """Return the config schema."""
return PLATFORM_SCHEMA return PLATFORM_SCHEMA
def _setup_from_config(self, config):
"""(Re)Setup the entity."""
self._optimistic = config[CONF_OPTIMISTIC]
async def _subscribe_topics(self): async def _subscribe_topics(self):
"""(Re)Subscribe to topics.""" """(Re)Subscribe to topics."""
@ -114,16 +118,14 @@ class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
@log_messages(self.hass, self.entity_id) @log_messages(self.hass, self.entity_id)
def message_received(msg): def message_received(msg):
"""Handle new MQTT messages.""" """Handle new MQTT messages."""
payload = msg.payload
try: try:
if msg.payload.decode("utf-8").isnumeric(): if payload.isnumeric():
num_value = int(msg.payload) num_value = int(msg.payload)
else: else:
num_value = float(msg.payload) num_value = float(msg.payload)
except ValueError: except ValueError:
_LOGGER.warning( _LOGGER.warning("Payload '%s' is not a Number", msg.payload)
"Payload '%s' is not a Number",
msg.payload.decode("utf-8", errors="ignore"),
)
return return
if num_value < self.min_value or num_value > self.max_value: if num_value < self.min_value or num_value > self.max_value:
@ -151,7 +153,6 @@ class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
"topic": self._config.get(CONF_STATE_TOPIC), "topic": self._config.get(CONF_STATE_TOPIC),
"msg_callback": message_received, "msg_callback": message_received,
"qos": self._config[CONF_QOS], "qos": self._config[CONF_QOS],
"encoding": None,
} }
}, },
) )

View File

@ -359,7 +359,7 @@ async def test_entity_id_update_discovery_update(hass, mqtt_mock):
async def test_entity_debug_info_message(hass, mqtt_mock): async def test_entity_debug_info_message(hass, mqtt_mock):
"""Test MQTT debug info.""" """Test MQTT debug info."""
await help_test_entity_debug_info_message( await help_test_entity_debug_info_message(
hass, mqtt_mock, number.DOMAIN, DEFAULT_CONFIG, payload=b"1" hass, mqtt_mock, number.DOMAIN, DEFAULT_CONFIG, payload="1"
) )
@ -408,7 +408,7 @@ async def test_invalid_min_max_attributes(hass, caplog, mqtt_mock):
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert f"'{CONF_MAX}'' must be > '{CONF_MIN}'" in caplog.text assert f"'{CONF_MAX}' must be > '{CONF_MIN}'" in caplog.text
async def test_mqtt_payload_not_a_number_warning(hass, caplog, mqtt_mock): async def test_mqtt_payload_not_a_number_warning(hass, caplog, mqtt_mock):