Skip to content

Commit

Permalink
Merge pull request #86 from henricm/handle-unknown-values
Browse files Browse the repository at this point in the history
fix: handle unknown value for energy sensor
  • Loading branch information
argoyle authored Nov 5, 2021
2 parents 9b88cbb + b027287 commit 66aa8ef
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions custom_components/ferroamp/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
26 changes: 26 additions & 0 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 66aa8ef

Please sign in to comment.