Ignore invalid summation values from Rainforest Eagle meters (#186571)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lennart Goedhart
2026-10-14 23:44:41 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent e2184a6168
commit 1a9b49bee7
4 changed files with 109 additions and 6 deletions
@@ -7,3 +7,6 @@ CONF_HARDWARE_ADDRESS = "hardware_address"
TYPE_EAGLE_100 = "eagle-100"
TYPE_EAGLE_200 = "eagle-200"
SUMMATION_DELIVERED = "zigbee:CurrentSummationDelivered"
SUMMATION_RECEIVED = "zigbee:CurrentSummationReceived"
@@ -3,6 +3,7 @@
import asyncio
from datetime import timedelta
import logging
from typing import Any
import aioeagle
from eagle100 import Eagle as Eagle100Reader
@@ -17,6 +18,8 @@ from .const import (
CONF_CLOUD_ID,
CONF_HARDWARE_ADDRESS,
CONF_INSTALL_CODE,
SUMMATION_DELIVERED,
SUMMATION_RECEIVED,
TYPE_EAGLE_100,
)
from .data import UPDATE_100_ERRORS
@@ -25,6 +28,23 @@ type RainforestEagleConfigEntry = ConfigEntry[EagleDataCoordinator]
_LOGGER = logging.getLogger(__name__)
# Summations are 48-bit Wh counters, reported here in kWh; some meters
# occasionally send a value at the top of that range instead of the reading.
INVALID_SUMMATION_KWH = (2**48 - 2**32) / 1000
def _discard_invalid_summations(data: dict[str, Any]) -> dict[str, Any]:
"""Replace summation values that cannot be real readings with None."""
for key in (SUMMATION_DELIVERED, SUMMATION_RECEIVED):
try:
value = float(data[key])
except KeyError, TypeError, ValueError:
continue
if value >= INVALID_SUMMATION_KWH:
_LOGGER.warning("Ignoring invalid %s from meter: %s", key, data[key])
data[key] = None
return data
class EagleDataCoordinator(DataUpdateCoordinator):
"""Get the latest data from the Eagle device."""
@@ -96,7 +116,9 @@ class EagleDataCoordinator(DataUpdateCoordinator):
_LOGGER.warning("Lost connection with electricity meter")
_LOGGER.debug("API data: %s", data)
return {var["Name"]: var["Value"] for var in data.values()}
return _discard_invalid_summations(
{var["Name"]: var["Value"] for var in data.values()}
)
async def _async_update_data_100(self):
"""Get the latest data from the Eagle-100 device."""
@@ -106,7 +128,7 @@ class EagleDataCoordinator(DataUpdateCoordinator):
raise UpdateFailed from error
_LOGGER.debug("API data: %s", data)
return data
return _discard_invalid_summations(data)
def _fetch_data_100(self):
"""Fetch and return the four sensor values in a dict."""
@@ -15,7 +15,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .const import DOMAIN, SUMMATION_DELIVERED, SUMMATION_RECEIVED
from .coordinator import EagleDataCoordinator, RainforestEagleConfigEntry
SENSORS = (
@@ -27,14 +27,14 @@ SENSORS = (
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="zigbee:CurrentSummationDelivered",
key=SUMMATION_DELIVERED,
translation_key="total_energy_delivered",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="zigbee:CurrentSummationReceived",
key=SUMMATION_RECEIVED,
translation_key="total_energy_received",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
@@ -1,9 +1,19 @@
"""Tests for rainforest eagle sensors."""
from copy import deepcopy
from datetime import timedelta
from unittest.mock import Mock
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.rainforest_eagle.const import DOMAIN
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from . import MOCK_200_RESPONSE_WITH_PRICE
from . import MOCK_200_RESPONSE_WITH_PRICE, MOCK_200_RESPONSE_WITHOUT_PRICE
from tests.common import async_fire_time_changed
async def test_sensors_200(hass: HomeAssistant, setup_rainforest_200) -> None:
@@ -57,3 +67,71 @@ async def test_sensors_100(hass: HomeAssistant, setup_rainforest_100) -> None:
assert received is not None
assert received.state == "232.232000"
assert received.attributes["unit_of_measurement"] == "kWh"
async def _refresh(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None:
"""Advance to the next coordinator poll."""
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()
@pytest.mark.parametrize(
("variable", "entity_id", "valid_state"),
[
pytest.param(
"zigbee:CurrentSummationDelivered",
"sensor.eagle_200_total_energy_delivered",
"45251.285000",
id="delivered",
),
pytest.param(
"zigbee:CurrentSummationReceived",
"sensor.eagle_200_total_energy_received",
"232.232000",
id="received",
),
],
)
async def test_invalid_summation_200(
hass: HomeAssistant,
setup_rainforest_200: Mock,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
variable: str,
entity_id: str,
valid_state: str,
) -> None:
"""Test a summation at the top of the 48-bit range is ignored."""
invalid_response = deepcopy(MOCK_200_RESPONSE_WITHOUT_PRICE)
# 0xfffffffffff0 Wh, as reported by a meter in place of a real reading.
invalid_response[variable]["Value"] = "281474976710.640"
setup_rainforest_200.get_device_query.return_value = invalid_response
await _refresh(hass, freezer)
assert hass.states.get(entity_id).state == STATE_UNKNOWN
assert f"Ignoring invalid {variable} from meter" in caplog.text
setup_rainforest_200.get_device_query.return_value = MOCK_200_RESPONSE_WITHOUT_PRICE
await _refresh(hass, freezer)
assert hass.states.get(entity_id).state == valid_state
async def test_non_numeric_summation_200(
hass: HomeAssistant,
setup_rainforest_200: Mock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a non-numeric summation does not make the other sensors unavailable."""
response = deepcopy(MOCK_200_RESPONSE_WITHOUT_PRICE)
response["zigbee:CurrentSummationDelivered"]["Value"] = "invalid"
setup_rainforest_200.get_device_query.return_value = response
await _refresh(hass, freezer)
assert hass.states.get("sensor.eagle_200_power_demand").state == "1.152000"
assert hass.states.get("sensor.eagle_200_total_energy_received").state == (
"232.232000"
)