Skip to content

Commit

Permalink
Address late review of SwitchBee (#78412)
Browse files Browse the repository at this point in the history
  • Loading branch information
jafar-atili committed Sep 16, 2022
1 parent 383c83d commit 491177e
Show file tree
Hide file tree
Showing 14 changed files with 313 additions and 428 deletions.
1 change: 1 addition & 0 deletions .coveragerc
Expand Up @@ -1215,6 +1215,7 @@ omit =
homeassistant/components/swisscom/device_tracker.py
homeassistant/components/switchbee/__init__.py
homeassistant/components/switchbee/const.py
homeassistant/components/switchbee/coordinator.py
homeassistant/components/switchbee/switch.py
homeassistant/components/switchbot/__init__.py
homeassistant/components/switchbot/binary_sensor.py
Expand Down
115 changes: 8 additions & 107 deletions homeassistant/components/switchbee/__init__.py
Expand Up @@ -2,29 +2,16 @@

from __future__ import annotations

from datetime import timedelta
import logging

from switchbee.api import CentralUnitAPI, SwitchBeeError
from switchbee.device import DeviceType

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
CONF_DEFUALT_ALLOWED,
CONF_DEVICES,
CONF_SWITCHES_AS_LIGHTS,
DOMAIN,
SCAN_INTERVAL_SEC,
)

_LOGGER = logging.getLogger(__name__)

from .const import DOMAIN
from .coordinator import SwitchBeeCoordinator

PLATFORMS: list[Platform] = [Platform.SWITCH]

Expand All @@ -35,30 +22,24 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
central_unit = entry.data[CONF_HOST]
user = entry.data[CONF_USERNAME]
password = entry.data[CONF_PASSWORD]
devices_map: dict[str, DeviceType] = {s.display: s for s in DeviceType}
allowed_devices = [
devices_map[device]
for device in entry.options.get(CONF_DEVICES, CONF_DEFUALT_ALLOWED)
]

websession = async_get_clientsession(hass, verify_ssl=False)
api = CentralUnitAPI(central_unit, user, password, websession)
try:
await api.connect()
except SwitchBeeError:
return False
except SwitchBeeError as exp:
raise ConfigEntryNotReady("Failed to connect to the Central Unit") from exp

coordinator = SwitchBeeCoordinator(
hass,
api,
SCAN_INTERVAL_SEC,
allowed_devices,
entry.data[CONF_SWITCHES_AS_LIGHTS],
)

await coordinator.async_config_entry_first_refresh()
entry.async_on_unload(entry.add_update_listener(update_listener))
hass.data[DOMAIN][entry.entry_id] = coordinator

hass.config_entries.async_setup_platforms(entry, PLATFORMS)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True

Expand All @@ -74,83 +55,3 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def update_listener(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Update listener."""
await hass.config_entries.async_reload(config_entry.entry_id)


class SwitchBeeCoordinator(DataUpdateCoordinator):
"""Class to manage fetching Freedompro data API."""

def __init__(
self,
hass,
swb_api,
scan_interval,
devices: list[DeviceType],
switch_as_light: bool,
):
"""Initialize."""
self._api: CentralUnitAPI = swb_api
self._reconnect_counts: int = 0
self._devices_to_include: list[DeviceType] = devices
self._prev_devices_to_include_to_include: list[DeviceType] = []
self._mac_addr_fmt: str = format_mac(swb_api.mac)
self._switch_as_light = switch_as_light
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=scan_interval),
)

@property
def api(self) -> CentralUnitAPI:
"""Return SwitchBee API object."""
return self._api

@property
def mac_formated(self) -> str:
"""Return formatted MAC address."""
return self._mac_addr_fmt

@property
def switch_as_light(self) -> bool:
"""Return switch_as_ligh config."""
return self._switch_as_light

async def _async_update_data(self):

if self._reconnect_counts != self._api.reconnect_count:
self._reconnect_counts = self._api.reconnect_count
_LOGGER.debug(
"Central Unit re-connected again due to invalid token, total %i",
self._reconnect_counts,
)

config_changed = False

if set(self._prev_devices_to_include_to_include) != set(
self._devices_to_include
):
self._prev_devices_to_include_to_include = self._devices_to_include
config_changed = True

# The devices are loaded once during the config_entry
if not self._api.devices or config_changed:
# Try to load the devices from the CU for the first time
try:
await self._api.fetch_configuration(self._devices_to_include)
except SwitchBeeError as exp:
raise UpdateFailed(
f"Error communicating with API: {exp}"
) from SwitchBeeError
else:
_LOGGER.debug("Loaded devices")

# Get the state of the devices
try:
await self._api.fetch_states()
except SwitchBeeError as exp:
raise UpdateFailed(
f"Error communicating with API: {exp}"
) from SwitchBeeError
else:
return self._api.devices
51 changes: 4 additions & 47 deletions homeassistant/components/switchbee/config_flow.py
Expand Up @@ -5,19 +5,18 @@
from typing import Any

from switchbee.api import CentralUnitAPI, SwitchBeeError
from switchbee.device import DeviceType
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.device_registry import format_mac

from .const import CONF_DEFUALT_ALLOWED, CONF_DEVICES, CONF_SWITCHES_AS_LIGHTS, DOMAIN
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand All @@ -26,7 +25,6 @@
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_SWITCHES_AS_LIGHTS, default=False): cv.boolean,
}
)

Expand All @@ -43,9 +41,9 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]):
except SwitchBeeError as exp:
_LOGGER.error(exp)
if "LOGIN_FAILED" in str(exp):
raise InvalidAuth from SwitchBeeError
raise InvalidAuth from exp

raise CannotConnect from SwitchBeeError
raise CannotConnect from exp

return format_mac(api.mac)

Expand Down Expand Up @@ -83,47 +81,6 @@ async def async_step_user(self, user_input=None) -> FlowResult:
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)

@staticmethod
@callback
def async_get_options_flow(
config_entry: config_entries.ConfigEntry,
) -> OptionsFlowHandler:
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)


class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a option flow for AEMET."""

def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry

async def async_step_init(self, user_input=None) -> FlowResult:
"""Handle options flow."""

if user_input is not None:
return self.async_create_entry(title="", data=user_input)

all_devices = [
DeviceType.Switch,
DeviceType.TimedSwitch,
DeviceType.GroupSwitch,
DeviceType.TimedPowerSwitch,
]

data_schema = {
vol.Required(
CONF_DEVICES,
default=self.config_entry.options.get(
CONF_DEVICES,
CONF_DEFUALT_ALLOWED,
),
): cv.multi_select([device.display for device in all_devices]),
}

return self.async_show_form(step_id="init", data_schema=vol.Schema(data_schema))


class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect."""
Expand Down
10 changes: 0 additions & 10 deletions homeassistant/components/switchbee/const.py
@@ -1,14 +1,4 @@
"""Constants for the SwitchBee Smart Home integration."""

from switchbee.device import DeviceType

DOMAIN = "switchbee"
SCAN_INTERVAL_SEC = 5
CONF_SCAN_INTERVAL = "scan_interval"
CONF_SWITCHES_AS_LIGHTS = "switch_as_light"
CONF_DEVICES = "devices"
CONF_DEFUALT_ALLOWED = [
DeviceType.Switch.display,
DeviceType.TimedPowerSwitch.display,
DeviceType.TimedSwitch.display,
]
74 changes: 74 additions & 0 deletions homeassistant/components/switchbee/coordinator.py
@@ -0,0 +1,74 @@
"""SwitchBee integration Coordinator."""

from datetime import timedelta
import logging

from switchbee.api import CentralUnitAPI, SwitchBeeError
from switchbee.device import DeviceType, SwitchBeeBaseDevice

from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DOMAIN, SCAN_INTERVAL_SEC

_LOGGER = logging.getLogger(__name__)


class SwitchBeeCoordinator(DataUpdateCoordinator[dict[int, SwitchBeeBaseDevice]]):
"""Class to manage fetching Freedompro data API."""

def __init__(
self,
hass: HomeAssistant,
swb_api: CentralUnitAPI,
) -> None:
"""Initialize."""
self.api: CentralUnitAPI = swb_api
self._reconnect_counts: int = 0
self.mac_formated: str = format_mac(swb_api.mac)
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=SCAN_INTERVAL_SEC),
)

async def _async_update_data(self) -> dict[int, SwitchBeeBaseDevice]:
"""Update data via library."""

if self._reconnect_counts != self.api.reconnect_count:
self._reconnect_counts = self.api.reconnect_count
_LOGGER.debug(
"Central Unit re-connected again due to invalid token, total %i",
self._reconnect_counts,
)

# The devices are loaded once during the config_entry
if not self.api.devices:
# Try to load the devices from the CU for the first time
try:
await self.api.fetch_configuration(
[
DeviceType.Switch,
DeviceType.TimedSwitch,
DeviceType.GroupSwitch,
DeviceType.TimedPowerSwitch,
]
)
except SwitchBeeError as exp:
raise UpdateFailed(
f"Error communicating with API: {exp}"
) from SwitchBeeError
else:
_LOGGER.debug("Loaded devices")

# Get the state of the devices
try:
await self.api.fetch_states()
except SwitchBeeError as exp:
raise UpdateFailed(
f"Error communicating with API: {exp}"
) from SwitchBeeError

return self.api.devices
2 changes: 1 addition & 1 deletion homeassistant/components/switchbee/manifest.json
Expand Up @@ -3,7 +3,7 @@
"name": "SwitchBee",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/switchbee",
"requirements": ["pyswitchbee==1.4.7"],
"requirements": ["pyswitchbee==1.4.8"],
"codeowners": ["@jafar-atili"],
"iot_class": "local_polling"
}
12 changes: 1 addition & 11 deletions homeassistant/components/switchbee/strings.json
Expand Up @@ -6,8 +6,7 @@
"data": {
"host": "[%key:common::config_flow::data::host%]",
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]",
"switch_as_light": "Initialize switches as light entities"
"password": "[%key:common::config_flow::data::password%]"
}
}
},
Expand All @@ -19,14 +18,5 @@
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
}
},
"options": {
"step": {
"init": {
"data": {
"devices": "Devices to include"
}
}
}
}
}

0 comments on commit 491177e

Please sign in to comment.