Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor code update and optimization #9

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions custom_components/webastoconnect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion custom_components/webastoconnect/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 7 additions & 2 deletions custom_components/webastoconnect/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__(
Expand Down
36 changes: 23 additions & 13 deletions custom_components/webastoconnect/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -19,6 +22,7 @@
key="devicetracker",
name="Location",
entity_registry_enabled_default=True,
icon="mdi:car",
)


Expand All @@ -32,15 +36,17 @@ 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__(
self,
description: EntityDescription,
coordinator: WebastoConnectUpdateCoordinator,
) -> None:
"""Initialize a Webasto Connect switch."""
"""Initialize a Webasto Connect device tracker."""
super().__init__(coordinator)

self.entity_description = description
Expand All @@ -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 = {
Expand All @@ -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:
Expand Down
28 changes: 11 additions & 17 deletions custom_components/webastoconnect/number.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 9 additions & 5 deletions custom_components/webastoconnect/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import logging

import homeassistant.util.dt as dt_util
from homeassistant.components import sensor
from homeassistant.components.sensor import (
SensorDeviceClass,
Expand All @@ -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
Expand Down Expand Up @@ -56,22 +58,24 @@


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]

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__(
Expand Down
15 changes: 10 additions & 5 deletions custom_components/webastoconnect/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__(
Expand Down
Loading