From 90a7c3c70039fc937a4a925ed795c8dae61df1bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Nystr=C3=B6m?= Date: Sun, 11 Feb 2024 20:03:18 +0100 Subject: [PATCH] Move session from init to api (#81) * Move session from init to api Move session from __init__ to api and into WellbeingApiClient to fetch from hass-object when needed instead of written info WellbeingApiClient on init. Might fix the intermittent errors on fetching data. * make self._hass private --- custom_components/wellbeing/__init__.py | 3 +- custom_components/wellbeing/api.py | 35 ++++++++++++---------- custom_components/wellbeing/config_flow.py | 3 +- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/custom_components/wellbeing/__init__.py b/custom_components/wellbeing/__init__.py index 1f26a1c..e91638c 100644 --- a/custom_components/wellbeing/__init__.py +++ b/custom_components/wellbeing/__init__.py @@ -43,8 +43,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) - session = async_get_clientsession(hass) - client = WellbeingApiClient(username, password, session) + client = WellbeingApiClient(username, password, hass) coordinator = WellbeingDataUpdateCoordinator(hass, client=client, update_interval=update_interval) if not await coordinator.async_login(): diff --git a/custom_components/wellbeing/api.py b/custom_components/wellbeing/api.py index d307334..03116df 100644 --- a/custom_components/wellbeing/api.py +++ b/custom_components/wellbeing/api.py @@ -10,10 +10,12 @@ import async_timeout from custom_components.wellbeing.const import SENSOR, FAN, BINARY_SENSOR +from homeassistant.core import HomeAssistant from homeassistant.components.binary_sensor import BinarySensorDeviceClass from homeassistant.components.sensor import SensorDeviceClass from homeassistant.const import UnitOfTemperature, PERCENTAGE, CONCENTRATION_PARTS_PER_MILLION, \ CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER +from homeassistant.helpers.aiohttp_client import async_get_clientsession TIMEOUT = 10 @@ -145,11 +147,11 @@ def _create_entities(data): attr='FilterLife', unit=PERCENTAGE ), - ApplianceSensor( - name="CO2", - attr='CO2', - unit=CONCENTRATION_PARTS_PER_MILLION, - device_class=SensorDeviceClass.CO2 + ApplianceSensor( + name="CO2", + attr='CO2', + unit=CONCENTRATION_PARTS_PER_MILLION, + device_class=SensorDeviceClass.CO2 ) ] @@ -249,7 +251,7 @@ def setup(self, data): @property def speed_range(self) -> tuple: - ## Electrolux Devices: + ## Electrolux Devices: if self.model == "WELLA5": return 1, 5 if self.model == "WELLA7": @@ -279,17 +281,17 @@ def get_appliance(self, pnc_id): class WellbeingApiClient: - def __init__(self, username: str, password: str, session: aiohttp.ClientSession) -> None: + def __init__(self, username: str, password: str, hass: HomeAssistant) -> None: """Sample API Client.""" self._username = username self._password = password - self._session = session self._access_token = None self._token = None + self._hass = hass self._current_access_token = None self._token_expires = datetime.now() self.appliances = None - + async def _get_token(self) -> dict: json = { "clientId": CLIENT_ID, @@ -301,7 +303,7 @@ async def _get_token(self) -> dict: "Accept": "application/json" } return await self.api_wrapper("post", TOKEN_URL, json, headers) - + async def _login(self, access_token: str) -> dict: credentials = { "username": self._username, @@ -362,7 +364,7 @@ async def async_login(self) -> bool: self._current_access_token = None _LOGGER.error("AccessToken 1 is missing") return False - + userToken = await self._login(access_token['accessToken']) if 'idToken' not in userToken: @@ -376,7 +378,7 @@ async def async_login(self) -> bool: self._current_access_token = None _LOGGER.error("AccessToken 2 is missing") return False - + _LOGGER.debug("Received new token sucssfully") self._token_expires = datetime.now() + timedelta(seconds=token['expiresIn']) @@ -402,7 +404,7 @@ async def async_get_data(self) -> Appliances: modelName = appliance['applianceData']['modelName'] applianceId = appliance['applianceId'] applianceName = appliance['applianceData']['applianceName'] - + app = Appliance(applianceName, applianceId, modelName) appliance_info = await self._get_appliance_info(access_token, applianceId) _LOGGER.debug(f"Fetched data: {appliance_info}") @@ -457,16 +459,17 @@ async def _send_command(self, access_token: str, pnc_id: str, command: dict) -> async def api_wrapper(self, method: str, url: str, data: dict = {}, headers: dict = {}) -> dict: """Get information from the API.""" + session = async_get_clientsession(self._hass) try: async with async_timeout.timeout(TIMEOUT): if method == "get": - response = await self._session.get(url, headers=headers) + response = await session.get(url, headers=headers) return await response.json() elif method == "put": - response = await self._session.put(url, headers=headers, json=data) + response = await session.put(url, headers=headers, json=data) return await response.json() elif method == "post": - response = await self._session.post(url, headers=headers, json=data) + response = await session.post(url, headers=headers, json=data) return await response.json() else: raise Exception("Unsupported http method '%s'" % method) diff --git a/custom_components/wellbeing/config_flow.py b/custom_components/wellbeing/config_flow.py index 09ba3ff..0c9a80f 100644 --- a/custom_components/wellbeing/config_flow.py +++ b/custom_components/wellbeing/config_flow.py @@ -91,8 +91,7 @@ async def _show_config_form(self, user_input): # pylint: disable=unused-argumen async def _test_credentials(self, username, password): """Return true if credentials is valid.""" try: - session = async_create_clientsession(self.hass) - client = WellbeingApiClient(username, password, session) + client = WellbeingApiClient(username, password, self.hass) return await client.async_login() except Exception: # pylint: disable=broad-except pass