pyhOn/pyhon/hon.py

58 lines
1.7 KiB
Python
Raw Normal View History

2023-04-09 18:50:28 +00:00
import asyncio
2023-04-13 21:25:49 +00:00
from typing import List, Optional
from typing_extensions import Self
2023-04-09 18:50:28 +00:00
2023-04-13 21:25:49 +00:00
from aiohttp import ClientSession
from pyhon import HonAPI, exceptions
2023-04-09 18:50:28 +00:00
from pyhon.appliance import HonAppliance
class Hon:
2023-04-13 21:25:49 +00:00
def __init__(self, email: str, password: str, session: ClientSession | None = None):
self._email: str = email
self._password: str = password
self._session: ClientSession | None = session
self._appliances: List[HonAppliance] = []
self._api: Optional[HonAPI] = None
2023-04-09 18:50:28 +00:00
async def __aenter__(self):
2023-04-10 04:34:19 +00:00
return await self.create()
2023-04-09 18:50:28 +00:00
async def __aexit__(self, exc_type, exc_val, exc_tb):
2023-04-10 04:34:19 +00:00
await self.close()
2023-04-13 21:25:49 +00:00
@property
def api(self) -> HonAPI:
if self._api is None:
raise exceptions.NoAuthenticationException
return self._api
async def create(self) -> Self:
2023-04-10 04:34:19 +00:00
self._api = await HonAPI(
self._email, self._password, session=self._session
).create()
await self.setup()
return self
2023-04-09 18:50:28 +00:00
@property
def appliances(self) -> List[HonAppliance]:
return self._appliances
async def setup(self):
for appliance in (await self._api.load_appliances())["payload"]["appliances"]:
appliance = HonAppliance(self._api, appliance)
if appliance.mac_address is None:
continue
2023-04-09 18:55:36 +00:00
await asyncio.gather(
*[
appliance.load_attributes(),
appliance.load_commands(),
appliance.load_statistics(),
]
)
2023-04-09 18:50:28 +00:00
self._appliances.append(appliance)
2023-04-10 04:34:19 +00:00
async def close(self):
await self._api.close()