Skip to content

Commit

Permalink
Remove inapplicable sensor entities (#41)
Browse files Browse the repository at this point in the history
* Refactored unique id generation into coordinator
* Remove inapplicable sensor entities
  • Loading branch information
iprak authored Jul 27, 2024
1 parent d355be2 commit adfa675
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
22 changes: 21 additions & 1 deletion custom_components/weatherapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""The WeatherAPI integration."""

from datetime import timedelta
import logging
from typing import Final

from homeassistant.config_entries import ConfigEntry
Expand All @@ -12,18 +13,23 @@
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er

from .const import (
CONFIG_ADD_SENSORS,
CONFIG_FORECAST,
CONFIG_IGNORE_PAST_HOUR,
DEFAULT_ADD_SENSORS,
DEFAULT_FORECAST,
DEFAULT_IGNORE_PAST_HOUR,
DOMAIN,
UPDATE_INTERVAL_MINUTES,
)
from .coordinator import WeatherAPIUpdateCoordinator, WeatherAPIUpdateCoordinatorConfig
from .sensor import SENSOR_DESCRIPTIONS

PLATFORMS: Final = [Platform.WEATHER, Platform.SENSOR]
_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
Expand All @@ -33,11 +39,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):

latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
location_name = entry.data[CONF_NAME]

config = WeatherAPIUpdateCoordinatorConfig(
api_key=entry.data[CONF_API_KEY],
location=f"{latitude},{longitude}",
name=entry.data[CONF_NAME],
name=location_name,
update_interval=timedelta(minutes=UPDATE_INTERVAL_MINUTES),
forecast=entry.options.get(CONFIG_FORECAST, DEFAULT_FORECAST),
ignore_past_forecast=entry.options.get(
Expand All @@ -52,6 +59,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
hass.data[DOMAIN][entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

# Remove previous sensor entries if sensors are not being added
if not entry.options.get(CONFIG_ADD_SENSORS, DEFAULT_ADD_SENSORS):
ent_reg = er.async_get(hass)

for description in SENSOR_DESCRIPTIONS:
unique_id = coordinator.generate_sensor_unique_id(description)

if entity_id := ent_reg.async_get_entity_id(
Platform.SENSOR, DOMAIN, unique_id
):
_LOGGER.debug("Removing sensor entity %s", entity_id)
ent_reg.async_remove(entity_id)

return True


Expand Down
6 changes: 6 additions & 0 deletions custom_components/weatherapi/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
ATTR_PM_10,
ATTR_SO2,
)
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_SUNNY,
Expand Down Expand Up @@ -435,6 +436,11 @@ def parse_current(self, json):
),
}

def generate_sensor_unique_id(self, description: SensorEntityDescription) -> str:
"""Generate unique id for a sensor."""
name = f"{self.config.name} {description.name}"
return f"{self.location}_{name}"


class InvalidApiKey(HomeAssistantError):
"""Error to indicate there is an invalid api key."""
Expand Down
2 changes: 1 addition & 1 deletion custom_components/weatherapi/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def __init__(
entity_id_format, f"{WEATHERAPI_DOMAIN}_{name}", hass=coordinator.hass
)

self._attr_unique_id = f"{self.coordinator.location}_{name}"
self._attr_unique_id = coordinator.generate_sensor_unique_id(description)

@property
def available(self) -> bool:
Expand Down

0 comments on commit adfa675

Please # to comment.