Keep the previous value for pollen and radar when the API fails only for those items but not for the main forecast

This commit is contained in:
Jules 2024-05-10 18:43:54 +02:00
parent 3c2bd51e85
commit ac0fe07f4f
Signed by: jdejaegh
GPG key ID: 99D6D184CA66933A
3 changed files with 19 additions and 9 deletions

View file

@ -116,10 +116,8 @@ class IrmKmiCoordinator(DataUpdateCoordinator):
try: try:
images_from_api = await self.download_images_from_api(animation_data, country, localisation_layer_url) images_from_api = await self.download_images_from_api(animation_data, country, localisation_layer_url)
except IrmKmiApiError as err: except IrmKmiApiError as err:
_LOGGER.warning(f"Could not get images for weather radar: {err}") _LOGGER.warning(f"Could not get images for weather radar: {err}. Keep the existing radar data.")
# TODO idea return self.data.get('animation', RadarAnimationData()) return self.data.get('animation', RadarAnimationData()) if self.data is not None else RadarAnimationData()
# this way, when we cannot update, we keep the old data
return RadarAnimationData()
localisation = images_from_api[0] localisation = images_from_api[0]
images_from_api = images_from_api[1:] images_from_api = images_from_api[1:]
@ -152,8 +150,9 @@ class IrmKmiCoordinator(DataUpdateCoordinator):
_LOGGER.debug(f"Requesting pollen SVG at url {svg_url}") _LOGGER.debug(f"Requesting pollen SVG at url {svg_url}")
pollen_svg: str = await self._api_client.get_svg(svg_url) pollen_svg: str = await self._api_client.get_svg(svg_url)
except IrmKmiApiError as err: except IrmKmiApiError as err:
_LOGGER.warning(f"Could not get pollen data from the API: {err}") _LOGGER.warning(f"Could not get pollen data from the API: {err}. Keeping the same data.")
return PollenParser.get_default_data() return self.data.get('pollen', PollenParser.get_unavailable_data()) \
if self.data is not None else PollenParser.get_unavailable_data()
return PollenParser(pollen_svg).get_pollen_data() return PollenParser(pollen_svg).get_pollen_data()

View file

@ -8,6 +8,11 @@ from custom_components.irm_kmi.const import POLLEN_NAMES
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def get_unavailable_data() -> dict:
"""Return all the known pollen with 'none' value"""
return {k.lower(): 'none' for k in POLLEN_NAMES}
class PollenParser: class PollenParser:
""" """
The SVG looks as follows (see test fixture for a real example) The SVG looks as follows (see test fixture for a real example)
@ -25,6 +30,7 @@ class PollenParser:
For the color scale, look for a white dot (nearly) at the same level as the pollen name. From the white dot For the color scale, look for a white dot (nearly) at the same level as the pollen name. From the white dot
horizontal position, determine the level horizontal position, determine the level
""" """
def __init__( def __init__(
self, self,
xml_string: str xml_string: str
@ -53,6 +59,11 @@ class PollenParser:
"""Return all the known pollen with 'none' value""" """Return all the known pollen with 'none' value"""
return {k.lower(): 'none' for k in POLLEN_NAMES} return {k.lower(): 'none' for k in POLLEN_NAMES}
@staticmethod
def get_unavailable_data() -> dict:
"""Return all the known pollen with 'none' value"""
return {k.lower(): None for k in POLLEN_NAMES}
@staticmethod @staticmethod
def get_option_values() -> List[str]: def get_option_values() -> List[str]:
"""List all the values that the pollen can have""" """List all the values that the pollen can have"""
@ -128,4 +139,3 @@ class PollenParser:
_LOGGER.debug(f"Pollen data: {pollen_data}") _LOGGER.debug(f"Pollen data: {pollen_data}")
return pollen_data return pollen_data

View file

@ -27,6 +27,7 @@ def test_svg_pollen_parsing():
assert data == {'birch': 'none', 'oak': 'active', 'hazel': 'none', 'mugwort': 'none', 'alder': 'active', assert data == {'birch': 'none', 'oak': 'active', 'hazel': 'none', 'mugwort': 'none', 'alder': 'active',
'grasses': 'none', 'ash': 'active'} 'grasses': 'none', 'ash': 'active'}
def test_pollen_options(): def test_pollen_options():
assert PollenParser.get_option_values() == ['active', 'green', 'yellow', 'orange', 'red', 'purple', 'none'] assert PollenParser.get_option_values() == ['active', 'green', 'yellow', 'orange', 'red', 'purple', 'none']
@ -50,7 +51,7 @@ async def test_pollen_data_from_api(
assert result == expected assert result == expected
async def test_pollen_error_leads_to_default_values( async def test_pollen_error_leads_to_unavailable_on_first_call(
hass: HomeAssistant, hass: HomeAssistant,
mock_config_entry: MockConfigEntry, mock_config_entry: MockConfigEntry,
mock_exception_irm_kmi_api_svg_pollen: AsyncMock mock_exception_irm_kmi_api_svg_pollen: AsyncMock
@ -59,5 +60,5 @@ async def test_pollen_error_leads_to_default_values(
api_data = get_api_data("be_forecast_warning.json") api_data = get_api_data("be_forecast_warning.json")
result = await coordinator._async_pollen_data(api_data) result = await coordinator._async_pollen_data(api_data)
expected = PollenParser.get_default_data() expected = PollenParser.get_unavailable_data()
assert result == expected assert result == expected