pyh0n/pyhon/hon.py

64 lines
1.9 KiB
Python
Raw Normal View History

2023-04-10 00:20:28 +05:30
import asyncio
2023-04-15 19:25:22 +05:30
from typing import List, Optional, Dict, Any
2023-04-10 00:20:28 +05:30
2023-04-14 02:55:49 +05:30
from aiohttp import ClientSession
2023-04-16 02:32:37 +05:30
from typing_extensions import Self
2023-04-14 02:55:49 +05:30
from pyhon import HonAPI, exceptions
2023-04-10 00:20:28 +05:30
from pyhon.appliance import HonAppliance
class Hon:
2023-04-14 02:55:49 +05:30
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-10 00:20:28 +05:30
async def __aenter__(self):
2023-04-10 10:04:19 +05:30
return await self.create()
2023-04-10 00:20:28 +05:30
async def __aexit__(self, exc_type, exc_val, exc_tb):
2023-04-10 10:04:19 +05:30
await self.close()
2023-04-14 02:55:49 +05:30
@property
def api(self) -> HonAPI:
if self._api is None:
raise exceptions.NoAuthenticationException
return self._api
async def create(self) -> Self:
2023-04-10 10:04:19 +05:30
self._api = await HonAPI(
self._email, self._password, session=self._session
).create()
await self.setup()
return self
2023-04-10 00:20:28 +05:30
@property
def appliances(self) -> List[HonAppliance]:
return self._appliances
2023-04-15 19:25:22 +05:30
async def _create_appliance(self, appliance_data: Dict[str, Any], zone=0) -> None:
appliance = HonAppliance(self._api, appliance_data, zone=zone)
2023-04-15 07:42:38 +05:30
if appliance.mac_address is None:
return
await asyncio.gather(
*[
appliance.load_attributes(),
appliance.load_commands(),
appliance.load_statistics(),
]
)
self._appliances.append(appliance)
2023-04-10 00:20:28 +05:30
async def setup(self):
2023-04-16 01:28:20 +05:30
appliance: Dict
2023-04-10 00:20:28 +05:30
for appliance in (await self._api.load_appliances())["payload"]["appliances"]:
2023-04-15 07:42:38 +05:30
for zone in range(int(appliance.get("zone", "0"))):
2023-04-16 01:28:20 +05:30
await self._create_appliance(appliance.copy(), zone=zone + 1)
2023-04-15 07:42:38 +05:30
await self._create_appliance(appliance)
2023-04-10 10:04:19 +05:30
async def close(self):
await self._api.close()