Skip to content

Commit

Permalink
feat: Refactors and adds required integration code
Browse files Browse the repository at this point in the history
  • Loading branch information
MislavMandaric committed Sep 11, 2021
1 parent bbce0ec commit ad34ebf
Show file tree
Hide file tree
Showing 8 changed files with 227 additions and 389 deletions.
109 changes: 35 additions & 74 deletions custom_components/vaillant_vsmart/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,106 +4,67 @@
For more details about this integration, please refer to
https://github.com/MislavMandaric/home-assistant-vaillant-vsmart
"""
import asyncio
from datetime import timedelta
import logging
from __future__ import annotations

from authlib.oauth2.rfc6749.wrappers import OAuth2Token
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_TOKEN
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .api import VaillantApiClient
from vaillant_netatmo_api import ThermostatClient, deserialize_token, serialize_token

from .const import (
CONF_PASSWORD,
CONF_USERNAME,
DOMAIN,
PLATFORMS,
STARTUP_MESSAGE,
)
from .entity import VaillantCoordinator

SCAN_INTERVAL = timedelta(seconds=30)

_LOGGER: logging.Logger = logging.getLogger(__package__)
async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Set up Vaillant vSMART component."""

hass.data.setdefault(DOMAIN, {})

async def async_setup(hass: HomeAssistant, config: Config):
"""Set up this integration using YAML is not supported."""
return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(STARTUP_MESSAGE)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Vaillant vSMART from a config entry."""

async def async_token_updater(
token: OAuth2Token, refresh_token: str = None, access_token: str = None
) -> None:
data = entry.data.copy()
data[CONF_TOKEN] = serialize_token(token)

username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD)
hass.config_entries.async_update_entry(entry, data=data)

session = async_get_clientsession(hass)
client = VaillantApiClient(username, password, session)
client_id = entry.data.get(CONF_CLIENT_ID)
client_secret = entry.data.get(CONF_CLIENT_SECRET)
token = deserialize_token(entry.data.get(CONF_TOKEN))

coordinator = VaillantDataUpdateCoordinator(hass, client=client)
await coordinator.async_refresh()
client = ThermostatClient(
client_id,
client_secret,
token,
async_token_updater,
)

if not coordinator.last_update_success:
raise ConfigEntryNotReady
coordinator = VaillantCoordinator(hass, client)
await coordinator.async_config_entry_first_refresh()

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

for platform in PLATFORMS:
if entry.options.get(platform, True):
coordinator.platforms.append(platform)
hass.async_add_job(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
hass.config_entries.async_setup_platforms(entry, PLATFORMS)

entry.add_update_listener(async_reload_entry)
return True


class VaillantDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(
self, hass: HomeAssistant, client: VaillantApiClient
) -> None:
"""Initialize."""
self.api = client
self.platforms = []

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

async def _async_update_data(self):
"""Update data via library."""
try:
return await self.api.async_get_data()
except Exception as exception:
raise UpdateFailed() from exception


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:
hass.data[DOMAIN].pop(entry.entry_id)

return unloaded
"""Unload a config entry."""

unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
coordinator: VaillantCoordinator = hass.data[DOMAIN].pop(entry.entry_id)
await coordinator.async_close()

async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
return unload_ok
75 changes: 0 additions & 75 deletions custom_components/vaillant_vsmart/api.py

This file was deleted.

35 changes: 0 additions & 35 deletions custom_components/vaillant_vsmart/binary_sensor.py

This file was deleted.

Loading

0 comments on commit ad34ebf

Please sign in to comment.