Add base entity to switchbee (#78987)

* Add base entity to switchbee

* Adjust coverage

* Add SwitchBeeDeviceEntity

* Don't move available

* Update homeassistant/components/switchbee/entity.py

Co-authored-by: Joakim Plate <elupus@ecce.se>

* Update homeassistant/components/switchbee/entity.py

Co-authored-by: Joakim Plate <elupus@ecce.se>

Co-authored-by: Joakim Plate <elupus@ecce.se>
This commit is contained in:
epenet 2022-09-23 22:34:49 +02:00 committed by GitHub
parent 21b91f75ba
commit 26d9962fe5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 67 additions and 47 deletions

View File

@ -1222,8 +1222,8 @@ omit =
homeassistant/components/swisscom/device_tracker.py homeassistant/components/swisscom/device_tracker.py
homeassistant/components/switchbee/__init__.py homeassistant/components/switchbee/__init__.py
homeassistant/components/switchbee/button.py homeassistant/components/switchbee/button.py
homeassistant/components/switchbee/const.py
homeassistant/components/switchbee/coordinator.py homeassistant/components/switchbee/coordinator.py
homeassistant/components/switchbee/entity.py
homeassistant/components/switchbee/switch.py homeassistant/components/switchbee/switch.py
homeassistant/components/switchbot/__init__.py homeassistant/components/switchbot/__init__.py
homeassistant/components/switchbot/binary_sensor.py homeassistant/components/switchbot/binary_sensor.py

View File

@ -1,17 +1,17 @@
"""Support for SwitchBee scenario button.""" """Support for SwitchBee scenario button."""
from switchbee.api import SwitchBeeError from switchbee.api import SwitchBeeError
from switchbee.device import ApiStateCommand, DeviceType, SwitchBeeBaseDevice from switchbee.device import ApiStateCommand, DeviceType
from homeassistant.components.button import ButtonEntity from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN from .const import DOMAIN
from .coordinator import SwitchBeeCoordinator from .coordinator import SwitchBeeCoordinator
from .entity import SwitchBeeEntity
async def async_setup_entry( async def async_setup_entry(
@ -26,24 +26,13 @@ async def async_setup_entry(
) )
class SwitchBeeButton(CoordinatorEntity[SwitchBeeCoordinator], ButtonEntity): class SwitchBeeButton(SwitchBeeEntity, ButtonEntity):
"""Representation of an Switchbee button.""" """Representation of an Switchbee button."""
def __init__(
self,
device: SwitchBeeBaseDevice,
coordinator: SwitchBeeCoordinator,
) -> None:
"""Initialize the Switchbee switch."""
super().__init__(coordinator)
self._attr_name = device.name
self._device_id = device.id
self._attr_unique_id = f"{coordinator.mac_formated}-{device.id}"
async def async_press(self) -> None: async def async_press(self) -> None:
"""Fire the scenario in the SwitchBee hub.""" """Fire the scenario in the SwitchBee hub."""
try: try:
await self.coordinator.api.set_state(self._device_id, ApiStateCommand.ON) await self.coordinator.api.set_state(self._device.id, ApiStateCommand.ON)
except SwitchBeeError as exp: except SwitchBeeError as exp:
raise HomeAssistantError( raise HomeAssistantError(
f"Failed to fire scenario {self.name}, {str(exp)}" f"Failed to fire scenario {self.name}, {str(exp)}"

View File

@ -0,0 +1,54 @@
"""Support for SwitchBee entity."""
from switchbee import SWITCHBEE_BRAND
from switchbee.device import SwitchBeeBaseDevice
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import SwitchBeeCoordinator
class SwitchBeeEntity(CoordinatorEntity[SwitchBeeCoordinator]):
"""Representation of a Switchbee entity."""
_attr_has_entity_name = True
def __init__(
self,
device: SwitchBeeBaseDevice,
coordinator: SwitchBeeCoordinator,
) -> None:
"""Initialize the Switchbee entity."""
super().__init__(coordinator)
self._device = device
self._attr_name = device.name
self._attr_unique_id = f"{coordinator.mac_formated}-{device.id}"
class SwitchBeeDeviceEntity(SwitchBeeEntity):
"""Representation of a Switchbee device entity."""
def __init__(
self,
device: SwitchBeeBaseDevice,
coordinator: SwitchBeeCoordinator,
) -> None:
"""Initialize the Switchbee device."""
super().__init__(device, coordinator)
self._attr_device_info = DeviceInfo(
name=f"SwitchBee {device.unit_id}",
identifiers={
(
DOMAIN,
f"{device.unit_id}-{coordinator.mac_formated}",
)
},
manufacturer=SWITCHBEE_BRAND,
model=coordinator.api.module_display(device.unit_id),
suggested_area=device.zone,
via_device=(
DOMAIN,
f"{coordinator.api.name} ({coordinator.api.mac})",
),
)

View File

@ -2,7 +2,6 @@
import logging import logging
from typing import Any from typing import Any
from switchbee import SWITCHBEE_BRAND
from switchbee.api import SwitchBeeDeviceOfflineError, SwitchBeeError from switchbee.api import SwitchBeeDeviceOfflineError, SwitchBeeError
from switchbee.device import ApiStateCommand, DeviceType, SwitchBeeBaseDevice from switchbee.device import ApiStateCommand, DeviceType, SwitchBeeBaseDevice
@ -10,12 +9,11 @@ from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN from .const import DOMAIN
from .coordinator import SwitchBeeCoordinator from .coordinator import SwitchBeeCoordinator
from .entity import SwitchBeeDeviceEntity
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -39,8 +37,8 @@ async def async_setup_entry(
) )
class SwitchBeeSwitchEntity(CoordinatorEntity[SwitchBeeCoordinator], SwitchEntity): class SwitchBeeSwitchEntity(SwitchBeeDeviceEntity, SwitchEntity):
"""Representation of an Switchbee switch.""" """Representation of a Switchbee switch."""
def __init__( def __init__(
self, self,
@ -48,30 +46,9 @@ class SwitchBeeSwitchEntity(CoordinatorEntity[SwitchBeeCoordinator], SwitchEntit
coordinator: SwitchBeeCoordinator, coordinator: SwitchBeeCoordinator,
) -> None: ) -> None:
"""Initialize the Switchbee switch.""" """Initialize the Switchbee switch."""
super().__init__(coordinator) super().__init__(device, coordinator)
self._attr_name = f"{device.name}"
self._device_id = device.id
self._attr_unique_id = f"{coordinator.mac_formated}-{device.id}"
self._attr_is_on = False self._attr_is_on = False
self._is_online = True self._is_online = True
self._attr_has_entity_name = True
self._device = device
self._attr_device_info = DeviceInfo(
name=f"SwitchBee_{str(device.unit_id)}",
identifiers={
(
DOMAIN,
f"{str(device.unit_id)}-{coordinator.mac_formated}",
)
},
manufacturer=SWITCHBEE_BRAND,
model=coordinator.api.module_display(device.unit_id),
suggested_area=device.zone,
via_device=(
DOMAIN,
f"{coordinator.api.name} ({coordinator.api.mac})",
),
)
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -101,13 +78,13 @@ class SwitchBeeSwitchEntity(CoordinatorEntity[SwitchBeeCoordinator], SwitchEntit
""" """
try: try:
await self.coordinator.api.set_state(self._device_id, "dummy") await self.coordinator.api.set_state(self._device.id, "dummy")
except SwitchBeeDeviceOfflineError: except SwitchBeeDeviceOfflineError:
return return
except SwitchBeeError: except SwitchBeeError:
return return
if self.coordinator.data[self._device_id].state == -1: if self.coordinator.data[self._device.id].state == -1:
# This specific call will refresh the state of the device in the CU # This specific call will refresh the state of the device in the CU
self.hass.async_create_task(async_refresh_state()) self.hass.async_create_task(async_refresh_state())
@ -132,7 +109,7 @@ class SwitchBeeSwitchEntity(CoordinatorEntity[SwitchBeeCoordinator], SwitchEntit
# timed power switch state is an integer representing the number of minutes left until it goes off # timed power switch state is an integer representing the number of minutes left until it goes off
# regulare switches state is ON/OFF (1/0 respectively) # regulare switches state is ON/OFF (1/0 respectively)
self._attr_is_on = ( self._attr_is_on = (
self.coordinator.data[self._device_id].state != ApiStateCommand.OFF self.coordinator.data[self._device.id].state != ApiStateCommand.OFF
) )
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:
@ -145,7 +122,7 @@ class SwitchBeeSwitchEntity(CoordinatorEntity[SwitchBeeCoordinator], SwitchEntit
async def _async_set_state(self, state: ApiStateCommand) -> None: async def _async_set_state(self, state: ApiStateCommand) -> None:
try: try:
await self.coordinator.api.set_state(self._device_id, state) await self.coordinator.api.set_state(self._device.id, state)
except (SwitchBeeError, SwitchBeeDeviceOfflineError) as exp: except (SwitchBeeError, SwitchBeeDeviceOfflineError) as exp:
await self.coordinator.async_refresh() await self.coordinator.async_refresh()
raise HomeAssistantError( raise HomeAssistantError(