Create a single entity for new met_eireann config entries (#98100)

This commit is contained in:
Erik Montnemery 2023-08-15 20:56:19 +02:00 committed by GitHub
parent caeb20f9c9
commit 3cf86d5d1f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 16 deletions

View file

@ -1,10 +1,12 @@
"""Support for Met Éireann weather service.""" """Support for Met Éireann weather service."""
import logging import logging
from typing import cast from types import MappingProxyType
from typing import Any, cast
from homeassistant.components.weather import ( from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION, ATTR_FORECAST_CONDITION,
ATTR_FORECAST_TIME, ATTR_FORECAST_TIME,
DOMAIN as WEATHER_DOMAIN,
Forecast, Forecast,
WeatherEntity, WeatherEntity,
WeatherEntityFeature, WeatherEntityFeature,
@ -20,6 +22,7 @@ from homeassistant.const import (
UnitOfTemperature, UnitOfTemperature,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
@ -50,12 +53,28 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Add a weather entity from a config_entry.""" """Add a weather entity from a config_entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id] coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities( entity_registry = er.async_get(hass)
[
MetEireannWeather(coordinator, config_entry.data, False), entities = [MetEireannWeather(coordinator, config_entry.data, False)]
MetEireannWeather(coordinator, config_entry.data, True),
] # Add hourly entity to legacy config entries
) if entity_registry.async_get_entity_id(
WEATHER_DOMAIN,
DOMAIN,
_calculate_unique_id(config_entry.data, True),
):
entities.append(MetEireannWeather(coordinator, config_entry.data, True))
async_add_entities(entities)
def _calculate_unique_id(config: MappingProxyType[str, Any], hourly: bool) -> str:
"""Calculate unique ID."""
name_appendix = ""
if hourly:
name_appendix = "-hourly"
return f"{config[CONF_LATITUDE]}-{config[CONF_LONGITUDE]}{name_appendix}"
class MetEireannWeather( class MetEireannWeather(
@ -75,6 +94,7 @@ class MetEireannWeather(
def __init__(self, coordinator, config, hourly): def __init__(self, coordinator, config, hourly):
"""Initialise the platform with a data instance and site.""" """Initialise the platform with a data instance and site."""
super().__init__(coordinator) super().__init__(coordinator)
self._attr_unique_id = _calculate_unique_id(config, hourly)
self._config = config self._config = config
self._hourly = hourly self._hourly = hourly
@ -87,15 +107,6 @@ class MetEireannWeather(
self.hass, self.async_update_listeners(("daily", "hourly")) self.hass, self.async_update_listeners(("daily", "hourly"))
) )
@property
def unique_id(self):
"""Return unique ID."""
name_appendix = ""
if self._hourly:
name_appendix = "-hourly"
return f"{self._config[CONF_LATITUDE]}-{self._config[CONF_LONGITUDE]}{name_appendix}"
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""

View file

@ -13,6 +13,7 @@ from homeassistant.components.weather import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator from tests.typing import WebSocketGenerator
@ -31,6 +32,31 @@ async def setup_config_entry(hass: HomeAssistant) -> ConfigEntry:
return mock_data return mock_data
async def test_new_config_entry(hass: HomeAssistant, mock_weather) -> None:
"""Test the expected entities are created."""
registry = er.async_get(hass)
await setup_config_entry(hass)
assert len(hass.states.async_entity_ids("weather")) == 1
entry = hass.config_entries.async_entries()[0]
assert len(er.async_entries_for_config_entry(registry, entry.entry_id)) == 1
async def test_legacy_config_entry(hass: HomeAssistant, mock_weather) -> None:
"""Test the expected entities are created."""
registry = er.async_get(hass)
registry.async_get_or_create(
WEATHER_DOMAIN,
DOMAIN,
"10-20-hourly",
)
await setup_config_entry(hass)
assert len(hass.states.async_entity_ids("weather")) == 2
entry = hass.config_entries.async_entries()[0]
assert len(er.async_entries_for_config_entry(registry, entry.entry_id)) == 2
async def test_weather(hass: HomeAssistant, mock_weather) -> None: async def test_weather(hass: HomeAssistant, mock_weather) -> None:
"""Test weather entity.""" """Test weather entity."""
await setup_config_entry(hass) await setup_config_entry(hass)