Allow `unknown` state to be set (#65183)

pull/65296/head
Jan Bouwhuis 2022-01-31 10:25:08 +01:00 committed by GitHub
parent f6b0f26783
commit bfaada34e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 1 deletions

View File

@ -49,6 +49,7 @@ DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_PAYLOAD_ON = "ON" DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_FORCE_UPDATE = False DEFAULT_FORCE_UPDATE = False
CONF_EXPIRE_AFTER = "expire_after" CONF_EXPIRE_AFTER = "expire_after"
PAYLOAD_NONE = "None"
PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend(
{ {
@ -174,6 +175,8 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity):
self._state = True self._state = True
elif payload == self._config[CONF_PAYLOAD_OFF]: elif payload == self._config[CONF_PAYLOAD_OFF]:
self._state = False self._state = False
elif payload == PAYLOAD_NONE:
self._state = None
else: # Payload is not for this entity else: # Payload is not for this entity
template_info = "" template_info = ""
if self._config.get(CONF_VALUE_TEMPLATE) is not None: if self._config.get(CONF_VALUE_TEMPLATE) is not None:
@ -221,7 +224,7 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity):
self.async_write_ha_state() self.async_write_ha_state()
@property @property
def is_on(self): def is_on(self) -> bool | None:
"""Return true if the binary sensor is on.""" """Return true if the binary sensor is on."""
return self._state return self._state

View File

@ -269,6 +269,10 @@ async def test_setting_sensor_value_via_mqtt_message(hass, mqtt_mock):
state = hass.states.get("binary_sensor.test") state = hass.states.get("binary_sensor.test")
assert state.state == STATE_OFF assert state.state == STATE_OFF
async_fire_mqtt_message(hass, "test-topic", "None")
state = hass.states.get("binary_sensor.test")
assert state.state == STATE_UNKNOWN
async def test_invalid_sensor_value_via_mqtt_message(hass, mqtt_mock, caplog): async def test_invalid_sensor_value_via_mqtt_message(hass, mqtt_mock, caplog):
"""Test the setting of the value via MQTT.""" """Test the setting of the value via MQTT."""