Skip to content

Commit

Permalink
Stop polling on weather sensors
Browse files Browse the repository at this point in the history
Use async updates when coordinator updates, do not poll.
  • Loading branch information
izacus committed Aug 27, 2024
1 parent f54f234 commit b0ab220
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 23 deletions.
3 changes: 2 additions & 1 deletion custom_components/swissweather/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
self._post_code = config_entry.data[CONF_POST_CODE]
self._client = MeteoClient()
update_interval = timedelta(minutes=randrange(55, 65))
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval,
always_update=False)

async def _async_update_data(self) -> Tuple[CurrentState, WeatherForecast]:
_LOGGER.info("Updating weather data...")
Expand Down
32 changes: 12 additions & 20 deletions custom_components/swissweather/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
UnitOfTemperature,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import SwissWeatherDataCoordinator
from .const import CONF_POST_CODE, CONF_STATION_CODE, DOMAIN
Expand Down Expand Up @@ -75,10 +76,14 @@ async def async_setup_entry(
entities: list[SwissWeatherSensor] = [SwissWeatherSensor(postCode, stationCode, sensorEntry, coordinator) for sensorEntry in SENSORS]
async_add_entities(entities)

class SwissWeatherSensor(SensorEntity):
class SwissWeatherSensor(CoordinatorEntity[SwissWeatherDataCoordinator], SensorEntity):
def __init__(self, post_code:str, station_code:str, sensor_entry:SwissWeatherSensorEntry, coordinator:SwissWeatherDataCoordinator) -> None:
self.entity_description = SensorEntityDescription(key=sensor_entry.key, name=sensor_entry.description, native_unit_of_measurement=sensor_entry.native_unit, device_class=sensor_entry.device_class, state_class=sensor_entry.state_class)
self._coordinator = coordinator
super().__init__(coordinator)
self.entity_description = SensorEntityDescription(key=sensor_entry.key,
name=sensor_entry.description,
native_unit_of_measurement=sensor_entry.native_unit,
device_class=sensor_entry.device_class,
state_class=sensor_entry.state_class)
self._sensor_entry = sensor_entry
if station_code is None:
id_combo = f"{post_code}"
Expand All @@ -88,22 +93,9 @@ def __init__(self, post_code:str, station_code:str, sensor_entry:SwissWeatherSen
self._attr_unique_id = f"{post_code}.{sensor_entry.key}"
self._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERVICE, name=f"MeteoSwiss at {id_combo}", identifiers={(DOMAIN, f"swissweather-{id_combo}")})

@property
def available(self) -> bool:
return self._coordinator.last_update_success

async def async_added_to_hass(self) -> None:
"""Connect to dispatcher listening for entity data notifications."""
self.async_on_remove(
self._coordinator.async_add_listener(self.async_write_ha_state)
)

async def async_update(self) -> None:
await self._coordinator.async_request_refresh()

@property
def native_value(self) -> StateType | Decimal:
if self._coordinator.data is None:
if self.coordinator.data is None:
return None
currentState = self._coordinator.data[0]
return self._sensor_entry.data_function(currentState)
currentState = self.coordinator.data[0]
return self._sensor_entry.data_function(currentState)
3 changes: 1 addition & 2 deletions custom_components/swissweather/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import datetime
import logging
from typing import Any

from homeassistant.components.weather import Forecast, WeatherEntity
from homeassistant.components.weather.const import WeatherEntityFeature
Expand All @@ -14,8 +13,8 @@
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

Expand Down

0 comments on commit b0ab220

Please sign in to comment.