Skip to content

Commit

Permalink
Code clean up and refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
JohNan committed Aug 14, 2024
1 parent 823996a commit 663a4c4
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 49 deletions.
48 changes: 15 additions & 33 deletions custom_components/wellbeing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,25 @@
For more details about this integration, please refer to
https://github.com/JohNan/homeassistant-wellbeing
"""
import asyncio
import logging
from datetime import timedelta

from pyelectroluxgroup.api import ElectroluxHubAPI
from pyelectroluxgroup.token_manager import TokenManager

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_ACCESS_TOKEN
from homeassistant.core import Config
from homeassistant.const import CONF_API_KEY, CONF_ACCESS_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady, ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.helpers.update_coordinator import UpdateFailed
from homeassistant.util.hass_dict import HassKey
from pyelectroluxgroup.api import ElectroluxHubAPI
from pyelectroluxgroup.token_manager import TokenManager

from .api import WellbeingApiClient
from .const import CONF_PASSWORD, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, CONF_REFRESH_TOKEN
from .const import CONF_USERNAME
from .const import CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, CONF_REFRESH_TOKEN
from .const import DOMAIN
from .const import PLATFORMS

_LOGGER: logging.Logger = logging.getLogger(__package__)

PLATFORMS = [Platform.SENSOR, Platform.FAN, Platform.BINARY_SENSOR, Platform.SWITCH]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up this integration using UI."""
Expand All @@ -45,8 +40,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
session=async_get_clientsession(hass),
token_manager=token_manager
)
except Exception:
raise ConfigEntryAuthFailed
except Exception as exception:
raise ConfigEntryAuthFailed("Failed to setup API") from exception

client = WellbeingApiClient(hub)

Expand All @@ -55,33 +50,23 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
await coordinator.async_config_entry_first_refresh()

if not coordinator.last_update_success:
raise ConfigEntryNotReady
raise ConfigEntryNotReady from coordinator.last_exception

hass.data[DOMAIN][entry.entry_id] = coordinator

coordinator.platforms.extend(PLATFORMS)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

entry.add_update_listener(async_reload_entry)
return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Handle removal of an entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
unloaded = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
if platform in coordinator.platforms
]
)
)
if unloaded:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)

return unloaded
return unload_ok


async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
Expand All @@ -95,11 +80,8 @@ class WellbeingDataUpdateCoordinator(DataUpdateCoordinator):
def __init__(self, hass: HomeAssistant, client: WellbeingApiClient, update_interval: timedelta) -> None:
"""Initialize."""
self.api = client
self.platforms = []

super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)


async def _async_update_data(self):
"""Update data via library."""
try:
Expand All @@ -108,7 +90,7 @@ async def _async_update_data(self):
"appliances": appliances
}
except Exception as exception:
raise UpdateFailed() from exception
raise UpdateFailed(exception) from exception


class WellBeingTokenManager(TokenManager):
Expand All @@ -126,7 +108,7 @@ def update(self, access_token: str, refresh_token: str, api_key: str | None = No
_LOGGER.debug(f"Api key: {api_key} : {self.api_key}")
_LOGGER.debug(f"Access token: {access_token}")
_LOGGER.debug(f"Refresh token: {refresh_token}")

self._hass.config_entries.async_update_entry(
self._entry,
data={
Expand Down
16 changes: 1 addition & 15 deletions custom_components/wellbeing/const.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,14 @@
"""Constants for Wellbeing."""

# Base component constants
CONFIG_FLOW_TITLE = "Electrolux Wellbeing"
NAME = "Wellbeing"
DOMAIN = "wellbeing"
DOMAIN_DATA = f"{DOMAIN}_data"

# Icons
ICON = "mdi:format-quote-close"

# Device classes
BINARY_SENSOR_DEVICE_CLASS = "connectivity"

# Platforms
BINARY_SENSOR = "binary_sensor"
SENSOR = "sensor"
SWITCH = "switch"
FAN = "fan"
SWITCH = "switch"
PLATFORMS = [SENSOR, FAN, BINARY_SENSOR, SWITCH]

# Configuration and options
CONF_ENABLED = "enabled"
CONF_USERNAME = "username"
CONF_PASSWORD = "password"
CONF_SCAN_INTERVAL = "scan_interval"
CONF_REFRESH_TOKEN = "refresh_token"

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
homeassistant==2024.8.0
aiohttp
pyelectroluxgroup @ git+https://github.com/JohNan/pyelectroluxgroup@johnan/update-project
pyelectroluxgroup==0.2.0

0 comments on commit 663a4c4

Please sign in to comment.