Skip to content

Commit

Permalink
Improve code quality for description entity (#512)
Browse files Browse the repository at this point in the history
  • Loading branch information
iMicknl authored Aug 10, 2021
1 parent ead6d92 commit 897612f
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 71 deletions.
30 changes: 3 additions & 27 deletions custom_components/tahoma/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,20 @@

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Callable

from homeassistant.components import binary_sensor
from homeassistant.components.binary_sensor import (
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from .coordinator import TahomaDataUpdateCoordinator
from .entity import OverkizEntity
from .entity import OverkizBinarySensorDescription, OverkizDescriptiveEntity

STATE_OPEN = "open"
STATE_PERSON_INSIDE = "personInside"
STATE_DETECTED = "detected"


@dataclass
class OverkizBinarySensorDescription(BinarySensorEntityDescription):
"""Class to describe a Overkiz binary sensor."""

is_on: Callable[[Any], Any] = lambda state: state


BINARY_SENSOR_DESCRIPTIONS = [
# RainSensor/RainSensor
OverkizBinarySensorDescription(
Expand Down Expand Up @@ -121,19 +107,9 @@ async def async_setup_entry(
async_add_entities(entities)


class TahomaBinarySensor(OverkizEntity, BinarySensorEntity):
class TahomaBinarySensor(OverkizDescriptiveEntity, BinarySensorEntity):
"""Representation of a TaHoma Binary Sensor."""

def __init__(
self,
device_url: str,
coordinator: TahomaDataUpdateCoordinator,
description: OverkizBinarySensorDescription,
):
"""Initialize the device."""
super().__init__(device_url, coordinator)
self.entity_description = description

@property
def is_on(self):
"""Return the state of the sensor."""
Expand Down
55 changes: 50 additions & 5 deletions custom_components/tahoma/entity.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
"""Parent class for every Overkiz device."""
from __future__ import annotations

from dataclasses import dataclass
import logging
from typing import Any, Dict
from typing import Any, Callable

from homeassistant.components.binary_sensor import BinarySensorEntityDescription
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.const import ATTR_BATTERY_LEVEL
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
Expand Down Expand Up @@ -77,7 +82,7 @@ def assumed_state(self) -> bool:
return not self.device.states

@property
def device_info(self) -> Dict[str, Any]:
def device_info(self) -> dict[str, Any]:
"""Return device registry information for this entity."""
# Some devices, such as the Smart Thermostat have several devices in one physical device,
# with same device url, terminated by '#' and a number.
Expand All @@ -102,17 +107,17 @@ def device_info(self) -> Dict[str, Any]:
)

return {
"identifiers": {(DOMAIN, self.unique_id)},
"identifiers": {(DOMAIN, self.executor.base_device_url)},
"manufacturer": manufacturer,
"name": self.name,
"name": self.device.label,
"model": model,
"sw_version": self.device.controllable_name,
"suggested_area": self.coordinator.areas[self.device.placeoid],
"via_device": self.executor.get_gateway_id(),
}

@property
def device_state_attributes(self) -> Dict[str, Any]:
def device_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes of the device."""
attr = {}

Expand All @@ -136,3 +141,43 @@ def device_state_attributes(self) -> Dict[str, Any]:
attr[state.name] = state.value

return attr


@dataclass
class OverkizSensorDescription(SensorEntityDescription):
"""Class to describe an Overkiz sensor."""

value: Callable[[str | int | float], str | int | float] | None = lambda val: val


@dataclass
class OverkizBinarySensorDescription(BinarySensorEntityDescription):
"""Class to describe an Overkiz binary sensor."""

is_on: Callable[[str], bool] = lambda state: state


class OverkizDescriptiveEntity(OverkizEntity):
"""Representation of a Overkiz device entity based on a description."""

def __init__(
self,
device_url: str,
coordinator: TahomaDataUpdateCoordinator,
description: OverkizSensorDescription | OverkizBinarySensorDescription,
):
"""Initialize the device."""
super().__init__(device_url, coordinator)
self.entity_description = description

@property
def name(self) -> str:
"""Return the name of the device."""
if self.executor.index:
return f"{self.entity_description.name} {self.executor.index}"
return self.entity_description.name

@property
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{super().unique_id}-{self.entity_description.key}"
42 changes: 3 additions & 39 deletions custom_components/tahoma/sensor.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
"""Support for TaHoma sensors."""
from __future__ import annotations

from dataclasses import dataclass
import logging
from typing import Any, Callable

from homeassistant.components import sensor
from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
Expand All @@ -28,19 +22,11 @@
from homeassistant.util.dt import utc_from_timestamp

from .const import DOMAIN
from .coordinator import TahomaDataUpdateCoordinator
from .entity import OverkizEntity
from .entity import OverkizDescriptiveEntity, OverkizSensorDescription

_LOGGER = logging.getLogger(__name__)


@dataclass
class OverkizSensorDescription(SensorEntityDescription):
"""Class to describe a Overkiz sensor."""

value: Callable[[Any], Any] | None = lambda val: val


SENSOR_DESCRIPTIONS = [
OverkizSensorDescription(
key="core:BatteryLevelState",
Expand Down Expand Up @@ -340,19 +326,9 @@ async def async_setup_entry(
async_add_entities(entities)


class TahomaStateSensor(OverkizEntity, SensorEntity):
class TahomaStateSensor(OverkizDescriptiveEntity, SensorEntity):
"""Representation of a TaHoma Sensor."""

def __init__(
self,
device_url: str,
coordinator: TahomaDataUpdateCoordinator,
description: OverkizSensorDescription,
):
"""Initialize the device."""
super().__init__(device_url, coordinator)
self.entity_description = description

@property
def state(self):
"""Return the value of the sensor."""
Expand All @@ -363,15 +339,3 @@ def state(self):
return self.entity_description.value(state.value)

return state.value

@property
def name(self) -> str:
"""Return the name of the device."""
if self.executor.index:
return f"{self.entity_description.name} {self.executor.index}"
return self.entity_description.name

@property
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{super().unique_id}-{self.entity_description.key}"

0 comments on commit 897612f

Please sign in to comment.