Skip to content

Commit

Permalink
Adds the new api client (#100)
Browse files Browse the repository at this point in the history
* Adds devcontainer

* Fixes in devcontainer

* Added new API client

* Update aiohttp

* Deps

* Get entity data from new api
  • Loading branch information
JohNan authored Aug 9, 2024
1 parent 36a0970 commit bd197df
Show file tree
Hide file tree
Showing 18 changed files with 293 additions and 299 deletions.
41 changes: 41 additions & 0 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "JohNan/homeassistant-wellbeing",
"image": "mcr.microsoft.com/devcontainers/python:1-3.12",
"postCreateCommand": "scripts/setup",
"forwardPorts": [
8123
],
"portsAttributes": {
"8123": {
"label": "Home Assistant",
"onAutoForward": "notify"
}
},
"customizations": {
"vscode": {
"extensions": [
"charliermarsh.ruff",
"github.vscode-pull-request-github",
"ms-python.python",
"ms-python.vscode-pylance",
"ryanluker.vscode-coverage-gutters"
],
"settings": {
"files.eol": "\n",
"editor.tabSize": 4,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": false,
"files.trimTrailingWhitespace": true,
"python.analysis.typeCheckingMode": "basic",
"python.analysis.autoImportCompletions": true,
"python.defaultInterpreterPath": "/usr/local/bin/python",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
}
},
"remoteUser": "vscode",
"features": {}
}
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,7 @@ venv.bak/
dmypy.json

# Pyre type checker
.pyre/
.pyre/

/config
temp_credentials.py
58 changes: 38 additions & 20 deletions custom_components/wellbeing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@
from datetime import timedelta

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_ACCESS_TOKEN
from homeassistant.core import Config
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
from .const import CONF_PASSWORD, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, CONF_REFRESH_TOKEN
from .const import CONF_USERNAME
from .const import DOMAIN
from .const import PLATFORMS
Expand All @@ -40,14 +45,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
else:
update_interval = timedelta(seconds=DEFAULT_SCAN_INTERVAL)

username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD)
token_manager = WellBeingTokenManager(hass, entry)
try:
hub = ElectroluxHubAPI(
session=async_get_clientsession(hass),
token_manager=token_manager
)
except Exception:
raise ConfigEntryAuthFailed

client = WellbeingApiClient(username, password, hass)
client = WellbeingApiClient(hub)

coordinator = WellbeingDataUpdateCoordinator(hass, client=client, update_interval=update_interval)
if not await coordinator.async_login():
raise ConfigEntryAuthFailed

await coordinator.async_config_entry_first_refresh()

Expand All @@ -73,24 +82,11 @@ def __init__(self, hass: HomeAssistant, client: WellbeingApiClient, update_inter

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

async def async_login(self) -> bool:
"""Login to Wellbeing."""
try:
await self.api.async_login()
except Exception as ex:
_LOGGER.error(
"Could not log in to WellBeing, %s. Will try again after %d",
ex,
self.update_interval.seconds
)
return False

return True

async def _async_update_data(self):
"""Update data via library."""
try:
appliances = await self.api.async_get_data()
appliances = await self.api.async_get_appliances()
return {
"appliances": appliances
}
Expand Down Expand Up @@ -120,3 +116,25 @@ 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)

class WellBeingTokenManager(TokenManager):
def __init__(self, hass: HomeAssistant, entry: ConfigEntry):
self._hass = hass
self._entry = entry
api_key = entry.data.get(CONF_API_KEY)
refresh_token = entry.data.get(CONF_REFRESH_TOKEN)
access_token = entry.data.get(CONF_ACCESS_TOKEN)
super().__init__(access_token, refresh_token, api_key)

def update(self, access_token: str, refresh_token: str, api_key: str | None = None):
super().update(access_token, refresh_token, api_key)

self._hass.config_entries.async_update_entry(
self._entry,
data={
**self._entry.data,
CONF_API_KEY: api_key if api_key is not None else api_key,
CONF_REFRESH_TOKEN: refresh_token,
CONF_ACCESS_TOKEN: access_token
},
)
Loading

0 comments on commit bd197df

Please sign in to comment.