From b0272878396266c78b0b3d747c6cc8ea2e6f9e5b Mon Sep 17 00:00:00 2001 From: Joakim Olsson Date: Thu, 4 Nov 2021 20:18:55 +0100 Subject: [PATCH] fix: handle unknown value for energy sensor Fixes #85 --- custom_components/ferroamp/sensor.py | 8 ++++++++ tests/test_sensor.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/custom_components/ferroamp/sensor.py b/custom_components/ferroamp/sensor.py index 72a6f24..6864720 100644 --- a/custom_components/ferroamp/sensor.py +++ b/custom_components/ferroamp/sensor.py @@ -853,6 +853,7 @@ def update_state_from_events(self, events): else: val = round(temp / count / 3600000000, self._precision) if self._attr_native_value is None\ + or (isinstance(self._attr_native_value, str) and not self.isfloat(self._attr_native_value))\ or self._attr_state_class != STATE_CLASS_TOTAL_INCREASING\ or val > float(self._attr_native_value): self._attr_native_value = val @@ -866,6 +867,13 @@ def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_ENERGY) + def isfloat(self, value): + try: + float(value) + return True + except ValueError: + return False + class RelayStatusFerroampSensor(KeyedFerroampSensor): def __init__(self, name, entity_prefix, key, device_id, device_name, interval, config_id, **kwargs): diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 0f85b2c..4be3ce8 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -1555,6 +1555,32 @@ async def test_always_increasing(hass, mqtt_mock): assert sensor.state == "1348.5" +async def test_always_increasing_unknown_value(hass, mqtt_mock): + mock_restore_cache( + hass, + [ + State("sensor.ferroamp_total_solar_energy", "unknown") + ], + ) + + hass.state = CoreState.starting + + config_entry = create_config() + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + topic = "extapi/data/ehub" + msg = '{"id":{"val":"1"},"wpv":{"val": "4422089590383"}}' + async_fire_mqtt_message(hass, topic, msg) + await hass.async_block_till_done() + + er = await entity_registry.async_get_registry(hass) + entity = er.async_get("sensor.ferroamp_total_solar_energy") + assert entity is not None + sensor = hass.data[DOMAIN][DATA_DEVICES][config_entry.unique_id]["ferroamp_ehub"][entity.unique_id] + assert sensor.state == 1228.4 + + async def test_average_calculation(hass, mqtt_mock): config_entry = MockConfigEntry( domain=DOMAIN,