Mark eagle entities as unavailable if connection with meter losts (#55102)

This commit is contained in:
Paulus Schoutsen 2021-08-23 22:35:26 -07:00 committed by GitHub
parent e92e206544
commit cac486440f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 5 deletions

View File

@ -126,6 +126,14 @@ class EagleDataCoordinator(DataUpdateCoordinator):
"""Return hardware address of meter."""
return self.entry.data[CONF_HARDWARE_ADDRESS]
@property
def is_connected(self):
"""Return if the hub is connected to the electric meter."""
if self.eagle200_meter:
return self.eagle200_meter.is_connected
return True
async def _async_update_data_200(self):
"""Get the latest data from the Eagle-200 device."""
if self.eagle200_meter is None:
@ -139,9 +147,14 @@ class EagleDataCoordinator(DataUpdateCoordinator):
hub, self.hardware_address
)
is_connected = self.eagle200_meter.is_connected
async with async_timeout.timeout(30):
data = await self.eagle200_meter.get_device_query()
if is_connected and not self.eagle200_meter.is_connected:
_LOGGER.warning("Lost connection with electricity meter")
_LOGGER.debug("API data: %s", data)
return {var["Name"]: var["Value"] for var in data.values()}

View File

@ -132,6 +132,11 @@ class EagleSensor(CoordinatorEntity, SensorEntity):
"""Return unique ID of entity."""
return f"{self.coordinator.cloud_id}-${self.coordinator.hardware_address}-{self.entity_description.key}"
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.coordinator.is_connected
@property
def native_value(self) -> StateType:
"""Return native value of the sensor."""

View File

@ -1,5 +1,5 @@
"""Tests for rainforest eagle sensors."""
from unittest.mock import Mock, patch
from unittest.mock import AsyncMock, Mock, patch
import pytest
@ -65,12 +65,15 @@ async def setup_rainforest_200(hass):
},
).add_to_hass(hass)
with patch(
"aioeagle.ElectricMeter.get_device_query",
return_value=MOCK_200_RESPONSE_WITHOUT_PRICE,
"aioeagle.ElectricMeter.create_instance",
return_value=Mock(
get_device_query=AsyncMock(return_value=MOCK_200_RESPONSE_WITHOUT_PRICE)
),
) as mock_update:
mock_update.return_value.is_connected = True
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
yield mock_update
yield mock_update.return_value
@pytest.fixture
@ -126,7 +129,7 @@ async def test_sensors_200(hass, setup_rainforest_200):
assert received.state == "232.232000"
assert received.attributes["unit_of_measurement"] == "kWh"
setup_rainforest_200.return_value = MOCK_200_RESPONSE_WITH_PRICE
setup_rainforest_200.get_device_query.return_value = MOCK_200_RESPONSE_WITH_PRICE
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
await hass.config_entries.async_reload(config_entry.entry_id)