mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 11:33:11 -04:00
Keep PECO outage sensors available when the map alert can't be fetched (#195913)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5653748d0d
commit
e2e9099031
@@ -4,6 +4,7 @@ from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from typing import override
|
||||
|
||||
from aiohttp import ClientError
|
||||
from peco import (
|
||||
AlertResults,
|
||||
BadJSONError,
|
||||
@@ -26,7 +27,7 @@ class PECOCoordinatorData:
|
||||
"""Data class to hold PECO outage and alert results."""
|
||||
|
||||
outages: OutageResults
|
||||
alerts: AlertResults
|
||||
alerts: AlertResults | None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -57,6 +58,7 @@ class PecoOutageCoordinator(DataUpdateCoordinator[PECOCoordinatorData]):
|
||||
self._api = PecoOutageApi()
|
||||
self._websession = async_get_clientsession(hass)
|
||||
self._county: str = entry.data[CONF_COUNTY]
|
||||
self._alerts_unavailable_logged = False
|
||||
|
||||
@override
|
||||
async def _async_update_data(self) -> PECOCoordinatorData:
|
||||
@@ -67,11 +69,24 @@ class PecoOutageCoordinator(DataUpdateCoordinator[PECOCoordinatorData]):
|
||||
if self._county == "TOTAL"
|
||||
else await self._api.get_outage_count(self._county, self._websession)
|
||||
)
|
||||
alerts = await self._api.get_map_alerts(self._websession)
|
||||
except HttpError as err:
|
||||
raise UpdateFailed(f"Error fetching data: {err}") from err
|
||||
except BadJSONError as err:
|
||||
raise UpdateFailed(f"Error parsing data: {err}") from err
|
||||
|
||||
# The map alert is fetched separately, so that a failure to read it
|
||||
# does not discard the outage counts fetched above.
|
||||
alerts: AlertResults | None = None
|
||||
try:
|
||||
alerts = await self._api.get_map_alerts(self._websession)
|
||||
except (HttpError, BadJSONError, TimeoutError, ClientError) as err:
|
||||
if not self._alerts_unavailable_logged:
|
||||
LOGGER.info("The PECO map alert is unavailable: %s", err)
|
||||
self._alerts_unavailable_logged = True
|
||||
else:
|
||||
if self._alerts_unavailable_logged:
|
||||
LOGGER.info("The PECO map alert is available again")
|
||||
self._alerts_unavailable_logged = False
|
||||
return PECOCoordinatorData(outages, alerts)
|
||||
|
||||
|
||||
|
||||
@@ -23,8 +23,9 @@ from .coordinator import PecoConfigEntry, PECOCoordinatorData, PecoOutageCoordin
|
||||
class PECOSensorEntityDescription(SensorEntityDescription):
|
||||
"""Description for PECO sensor."""
|
||||
|
||||
value_fn: Callable[[PECOCoordinatorData], int | str]
|
||||
value_fn: Callable[[PECOCoordinatorData], int | str | None]
|
||||
attribute_fn: Callable[[PECOCoordinatorData], dict[str, str]]
|
||||
available_fn: Callable[[PECOCoordinatorData], bool] = lambda data: True
|
||||
|
||||
|
||||
PARALLEL_UPDATES: Final = 0
|
||||
@@ -61,8 +62,11 @@ SENSOR_LIST: tuple[PECOSensorEntityDescription, ...] = (
|
||||
PECOSensorEntityDescription(
|
||||
key="map_alert",
|
||||
translation_key="map_alert",
|
||||
value_fn=lambda data: str(data.alerts.alert_title),
|
||||
attribute_fn=lambda data: {ATTR_CONTENT: data.alerts.alert_content},
|
||||
value_fn=lambda data: data.alerts.alert_title if data.alerts else None,
|
||||
attribute_fn=lambda data: (
|
||||
{ATTR_CONTENT: data.alerts.alert_content} if data.alerts else {}
|
||||
),
|
||||
available_fn=lambda data: data.alerts is not None,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -104,7 +108,15 @@ class PecoSensor(CoordinatorEntity[PecoOutageCoordinator], SensorEntity):
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> int | str:
|
||||
def available(self) -> bool:
|
||||
"""Return if the sensor is available."""
|
||||
return super().available and self.entity_description.available_fn(
|
||||
self.coordinator.data
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> int | str | None:
|
||||
"""Return the value of the sensor."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
||||
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
"""Test the PECO Outage Counter sensors."""
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
from peco import AlertResults, OutageResults
|
||||
from aiohttp import ClientError
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from peco import AlertResults, BadJSONError, HttpError, OutageResults
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
from homeassistant.components.peco.const import DOMAIN
|
||||
from homeassistant.components.peco.const import DOMAIN, OUTAGE_SCAN_INTERVAL
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
MOCK_ENTRY_DATA = {"county": "TOTAL"}
|
||||
@@ -94,3 +99,67 @@ async def test_sensor_available(
|
||||
assert sensor_entity is not None
|
||||
assert sensor_entity.state != "unavailable"
|
||||
assert sensor_entity.state == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [HttpError, BadJSONError, TimeoutError, ClientError])
|
||||
async def test_map_alert_error_keeps_outage_sensors(
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
error: type[Exception],
|
||||
) -> None:
|
||||
"""Test that a failed map alert fetch only makes the map alert unavailable."""
|
||||
caplog.set_level(logging.INFO)
|
||||
config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)
|
||||
config_entry.add_to_hass(hass)
|
||||
outages = OutageResults(
|
||||
customers_out=123,
|
||||
percent_customers_out=15,
|
||||
outage_count=456,
|
||||
customers_served=789,
|
||||
)
|
||||
|
||||
with (
|
||||
patch("peco.PecoOutageApi.get_outage_count", return_value=outages),
|
||||
patch("peco.PecoOutageApi.get_map_alerts", side_effect=error()),
|
||||
):
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
# A second failed update must not log the failure again.
|
||||
freezer.tick(timedelta(minutes=OUTAGE_SCAN_INTERVAL))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
for sensor, expected in (
|
||||
("customers_out", "123"),
|
||||
("percent_customers_out", "15"),
|
||||
("outage_count", "456"),
|
||||
("customers_served", "789"),
|
||||
):
|
||||
state = hass.states.get(f"sensor.bucks_{sensor}")
|
||||
assert state is not None
|
||||
assert state.state == expected
|
||||
state = hass.states.get("sensor.bucks_map_alert")
|
||||
assert state is not None
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
assert caplog.text.count("The PECO map alert is unavailable") == 1
|
||||
|
||||
with (
|
||||
patch("peco.PecoOutageApi.get_outage_count", return_value=outages),
|
||||
patch(
|
||||
"peco.PecoOutageApi.get_map_alerts",
|
||||
return_value=AlertResults(
|
||||
alert_content="Testing 1234", alert_title="Testing 4321"
|
||||
),
|
||||
),
|
||||
):
|
||||
freezer.tick(timedelta(minutes=OUTAGE_SCAN_INTERVAL))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.bucks_map_alert")
|
||||
assert state is not None
|
||||
assert state.state == "Testing 4321"
|
||||
assert state.attributes["content"] == "Testing 1234"
|
||||
assert "The PECO map alert is available again" in caplog.text
|
||||
|
||||
Reference in New Issue
Block a user