From 1ebb1405cebfd44f59c37495a14798ef8fbb6a17 Mon Sep 17 00:00:00 2001 From: Malene Trab Date: Wed, 18 Oct 2023 07:48:06 +0000 Subject: [PATCH] Minor code update and optimization --- custom_components/webastoconnect/__init__.py | 12 +++---- custom_components/webastoconnect/api.py | 4 ++- .../webastoconnect/binary_sensor.py | 9 +++-- .../webastoconnect/device_tracker.py | 36 ++++++++++++------- custom_components/webastoconnect/number.py | 28 ++++++--------- custom_components/webastoconnect/sensor.py | 14 +++++--- custom_components/webastoconnect/switch.py | 15 +++++--- 7 files changed, 68 insertions(+), 50 deletions(-) diff --git a/custom_components/webastoconnect/__init__.py b/custom_components/webastoconnect/__init__.py index a0172d6..606baf5 100644 --- a/custom_components/webastoconnect/__init__.py +++ b/custom_components/webastoconnect/__init__.py @@ -8,7 +8,7 @@ from homeassistant.loader import async_get_integration from pywebasto.exceptions import UnauthorizedException -from .api import WebastoConnector, WebastoConnectUpdateCoordinator +from .api import WebastoConnectUpdateCoordinator from .const import ATTR_COORDINATOR, DOMAIN, PLATFORMS, STARTUP LOGGER = logging.getLogger(__name__) @@ -53,12 +53,10 @@ async def _async_setup(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" - for platform in PLATFORMS: - await hass.config_entries.async_forward_entry_unload(entry, platform) - - hass.data[DOMAIN].pop(entry.entry_id) - - return True + unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + if unload_ok: + hass.data[DOMAIN].pop(entry.entry_id) + return unload_ok async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: diff --git a/custom_components/webastoconnect/api.py b/custom_components/webastoconnect/api.py index 29dd225..bae0d09 100644 --- a/custom_components/webastoconnect/api.py +++ b/custom_components/webastoconnect/api.py @@ -52,4 +52,6 @@ async def _async_update_data(self) -> datetime | None: try: await self.hass.async_add_executor_job(self.cloud.update) except Exception as ex: - raise Exception(f"Failed communicating with the API: {ex}") from ex + raise Exception( # pylint: disable=broad-exception-raised + f"Failed communicating with the API: {ex}" + ) from ex diff --git a/custom_components/webastoconnect/binary_sensor.py b/custom_components/webastoconnect/binary_sensor.py index 8f7a7db..5ead607 100644 --- a/custom_components/webastoconnect/binary_sensor.py +++ b/custom_components/webastoconnect/binary_sensor.py @@ -8,7 +8,10 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory from homeassistant.core import callback -from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, +) from homeassistant.util import slugify as util_slugify from .api import WebastoConnectUpdateCoordinator @@ -46,7 +49,9 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): async_add_devices(binarysensors) -class WebastoConnectBinarySensor(CoordinatorEntity, BinarySensorEntity): +class WebastoConnectBinarySensor( + CoordinatorEntity[DataUpdateCoordinator[None]], BinarySensorEntity +): """Representation of a Webasto Connect Binary Sensor.""" def __init__( diff --git a/custom_components/webastoconnect/device_tracker.py b/custom_components/webastoconnect/device_tracker.py index ff2cdb6..aa51a9d 100644 --- a/custom_components/webastoconnect/device_tracker.py +++ b/custom_components/webastoconnect/device_tracker.py @@ -7,7 +7,10 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.core import callback from homeassistant.helpers.entity import EntityDescription -from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, +) from homeassistant.util import slugify as util_slugify from .api import WebastoConnectUpdateCoordinator @@ -19,6 +22,7 @@ key="devicetracker", name="Location", entity_registry_enabled_default=True, + icon="mdi:car", ) @@ -32,7 +36,9 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): async_add_devices([entity]) -class WebastoConnectDeviceTracker(CoordinatorEntity, TrackerEntity): +class WebastoConnectDeviceTracker( + CoordinatorEntity[DataUpdateCoordinator[None]], TrackerEntity +): """A device tracker for Webasto Connect.""" def __init__( @@ -40,7 +46,7 @@ def __init__( description: EntityDescription, coordinator: WebastoConnectUpdateCoordinator, ) -> None: - """Initialize a Webasto Connect switch.""" + """Initialize a Webasto Connect device tracker.""" super().__init__(coordinator) self.entity_description = description @@ -53,6 +59,9 @@ def __init__( f"{self._attr_name}_{self._config.entry_id}" ) + self._prev_lat = self.coordinator.cloud.location["lat"] + self._prev_lon = self.coordinator.cloud.location["lon"] + self._attr_should_poll = False self._attr_device_info = { @@ -66,25 +75,26 @@ def __init__( util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") ) - self._handle_location() - - def _handle_location(self) -> None: + @property + def available(self) -> bool: """Handle the location states.""" if isinstance(self.coordinator.cloud.location, type(None)): self._attr_available = False + return False else: self._attr_available = True - - # if self.coordinator.cloud.allow_location: - # self.enabled = True - # else: - # self.enabled = False + return True @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" - self._handle_location() - self.async_write_ha_state() + if ( + self.coordinator.cloud.location["lat"] != self._prev_lat + or self.coordinator.cloud.location["lon"] != self._prev_lon + ): + self._prev_lat = self.coordinator.cloud.location["lat"] + self._prev_lon = self.coordinator.cloud.location["lon"] + self.async_write_ha_state() @property def source_type(self) -> SourceType | str | None: diff --git a/custom_components/webastoconnect/number.py b/custom_components/webastoconnect/number.py index 5110bc8..fe495d7 100644 --- a/custom_components/webastoconnect/number.py +++ b/custom_components/webastoconnect/number.py @@ -1,14 +1,16 @@ """Support for number entities in Webasto Connect.""" import logging -from typing import Any, cast +from typing import cast from homeassistant.components import number from homeassistant.components.number import NumberEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory -from homeassistant.core import callback -from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, +) from homeassistant.util import slugify as util_slugify from .api import WebastoConnectUpdateCoordinator @@ -53,17 +55,19 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] - for number in NUMBERS: - entity = WebastoConnectNumber(number, coordinator) + for num in NUMBERS: + entity = WebastoConnectNumber(num, coordinator) LOGGER.debug( - "Adding number '%s' with entity_id '%s'", number.name, entity.entity_id + "Adding number '%s' with entity_id '%s'", num.name, entity.entity_id ) numbers_list.append(entity) async_add_devices(numbers_list) -class WebastoConnectNumber(CoordinatorEntity, NumberEntity): +class WebastoConnectNumber( + CoordinatorEntity[DataUpdateCoordinator[None]], NumberEntity +): """Representation of a Webasto Connect number.""" def __init__( @@ -100,19 +104,9 @@ def __init__( util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") ) - @callback - def _handle_coordinator_update(self) -> None: - """Handle updated data from the coordinator.""" - self.async_write_ha_state() - @property def native_value(self) -> float | None: """Get the native value.""" - LOGGER.debug( - "Native value for '%s' is '%s'", - self.entity_id, - self.entity_description.value_fn(self.coordinator.cloud), - ) return cast(float, self.entity_description.value_fn(self.coordinator.cloud)) async def async_set_native_value(self, value: float) -> None: diff --git a/custom_components/webastoconnect/sensor.py b/custom_components/webastoconnect/sensor.py index 6128c5f..d32bb4b 100644 --- a/custom_components/webastoconnect/sensor.py +++ b/custom_components/webastoconnect/sensor.py @@ -2,7 +2,6 @@ import logging -import homeassistant.util.dt as dt_util from homeassistant.components import sensor from homeassistant.components.sensor import ( SensorDeviceClass, @@ -12,7 +11,10 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory from homeassistant.core import callback -from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, +) from homeassistant.util import slugify as util_slugify from .api import WebastoConnectUpdateCoordinator @@ -56,7 +58,7 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): - """Setup binary_sensors.""" + """Setup sensors.""" sensors = [] coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] @@ -64,14 +66,16 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): for b_s in BINARY_SENSORS: entity = WebastoConnectSensor(b_s, coordinator) LOGGER.debug( - "Adding binary_sensor '%s' with entity_id '%s'", b_s.name, entity.entity_id + "Adding sensor '%s' with entity_id '%s'", b_s.name, entity.entity_id ) sensors.append(entity) async_add_devices(sensors) -class WebastoConnectSensor(CoordinatorEntity, SensorEntity): +class WebastoConnectSensor( + CoordinatorEntity[DataUpdateCoordinator[None]], SensorEntity +): """Representation of a Webasto Connect Sensor.""" def __init__( diff --git a/custom_components/webastoconnect/switch.py b/custom_components/webastoconnect/switch.py index 18c7248..96c53dd 100644 --- a/custom_components/webastoconnect/switch.py +++ b/custom_components/webastoconnect/switch.py @@ -8,7 +8,10 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory from homeassistant.core import callback -from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, +) from homeassistant.util import slugify as util_slugify from .api import WebastoConnectUpdateCoordinator @@ -44,17 +47,19 @@ async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] - for sw in SWITCHES: - entity = WebastoConnectSwitch(sw, coordinator) + for swi in SWITCHES: + entity = WebastoConnectSwitch(swi, coordinator) LOGGER.debug( - "Adding switch '%s' with entity_id '%s'", sw.name, entity.entity_id + "Adding switch '%s' with entity_id '%s'", swi.name, entity.entity_id ) switches.append(entity) async_add_devices(switches) -class WebastoConnectSwitch(CoordinatorEntity, SwitchEntity): +class WebastoConnectSwitch( + CoordinatorEntity[DataUpdateCoordinator[None]], SwitchEntity +): """Representation of a Webasto Connect switch.""" def __init__(