Skip to content

Commit

Permalink
Move session from init to api (#81)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
olanystrom authored Feb 11, 2024
1 parent de4cb36 commit 90a7c3c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 20 deletions.
3 changes: 1 addition & 2 deletions custom_components/wellbeing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
35 changes: 19 additions & 16 deletions custom_components/wellbeing/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
]

Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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'])
Expand All @@ -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}")
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions custom_components/wellbeing/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 90a7c3c

Please sign in to comment.