pyh0n/pyhon/connection/api.py

196 lines
7.3 KiB
Python
Raw Normal View History

2023-02-13 06:11:38 +05:30
import json
import logging
from datetime import datetime
2023-04-14 02:55:49 +05:30
from typing import Dict, Optional
from typing_extensions import Self
2023-02-13 06:11:38 +05:30
2023-04-14 02:55:49 +05:30
from aiohttp import ClientSession
from pyhon import const, exceptions
2023-04-09 21:43:50 +05:30
from pyhon.appliance import HonAppliance
2023-04-14 02:55:49 +05:30
from pyhon.connection.auth import HonAuth
2023-04-15 17:52:04 +05:30
from pyhon.connection.handler.hon import HonConnectionHandler
from pyhon.connection.handler.anonym import HonAnonymousConnectionHandler
2023-02-13 06:11:38 +05:30
_LOGGER = logging.getLogger()
2023-04-09 21:43:50 +05:30
class HonAPI:
2023-04-14 02:55:49 +05:30
def __init__(
self,
email: str = "",
password: str = "",
anonymous: bool = False,
session: Optional[ClientSession] = None,
) -> None:
2023-02-13 06:11:38 +05:30
super().__init__()
2023-04-14 02:55:49 +05:30
self._email: str = email
self._password: str = password
self._anonymous: bool = anonymous
self._hon_handler: Optional[HonConnectionHandler] = None
self._hon_anonymous_handler: Optional[HonAnonymousConnectionHandler] = None
self._session: Optional[ClientSession] = session
async def __aenter__(self) -> Self:
2023-04-10 00:20:28 +05:30
return await self.create()
2023-02-13 06:11:38 +05:30
2023-04-14 02:55:49 +05:30
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
2023-04-10 10:04:19 +05:30
await self.close()
2023-02-13 06:11:38 +05:30
2023-04-14 02:55:49 +05:30
@property
def auth(self) -> HonAuth:
if self._hon is None or self._hon.auth is None:
raise exceptions.NoAuthenticationException
return self._hon.auth
@property
def _hon(self):
if self._hon_handler is None:
raise exceptions.NoAuthenticationException
return self._hon_handler
@property
def _hon_anonymous(self):
if self._hon_anonymous_handler is None:
raise exceptions.NoAuthenticationException
return self._hon_anonymous_handler
async def create(self) -> Self:
self._hon_anonymous_handler = await HonAnonymousConnectionHandler(
2023-04-10 10:04:19 +05:30
self._session
).create()
2023-04-10 03:17:33 +05:30
if not self._anonymous:
2023-04-14 02:55:49 +05:30
self._hon_handler = await HonConnectionHandler(
2023-04-10 10:04:19 +05:30
self._email, self._password, self._session
).create()
2023-04-10 00:20:28 +05:30
return self
2023-02-13 06:11:38 +05:30
2023-04-14 02:55:49 +05:30
async def load_appliances(self) -> Dict:
2023-04-09 21:43:50 +05:30
async with self._hon.get(f"{const.API_URL}/commands/v1/appliance") as resp:
2023-04-10 00:20:28 +05:30
return await resp.json()
2023-04-14 02:55:49 +05:30
async def load_commands(self, appliance: HonAppliance) -> Dict:
params: Dict = {
2023-04-10 00:20:28 +05:30
"applianceType": appliance.appliance_type,
"code": appliance.info["code"],
"applianceModelId": appliance.appliance_model_id,
"firmwareId": appliance.info["eepromId"],
"macAddress": appliance.mac_address,
"fwVersion": appliance.info["fwVersion"],
2023-02-13 06:11:38 +05:30
"os": const.OS,
"appVersion": const.APP_VERSION,
2023-04-10 00:20:28 +05:30
"series": appliance.info["series"],
2023-02-13 06:11:38 +05:30
}
2023-04-14 02:55:49 +05:30
url: str = f"{const.API_URL}/commands/v1/retrieve"
2023-04-09 21:43:50 +05:30
async with self._hon.get(url, params=params) as response:
2023-04-14 02:55:49 +05:30
result: Dict = (await response.json()).get("payload", {})
2023-02-13 06:11:38 +05:30
if not result or result.pop("resultCode") != "0":
return {}
return result
2023-04-14 02:55:49 +05:30
async def command_history(self, appliance: HonAppliance) -> Dict:
url: str = (
f"{const.API_URL}/commands/v1/appliance/{appliance.mac_address}/history"
)
2023-04-09 21:43:50 +05:30
async with self._hon.get(url) as response:
2023-04-14 02:55:49 +05:30
result: Dict = await response.json()
2023-03-11 07:01:56 +05:30
if not result or not result.get("payload"):
return {}
return result["payload"]["history"]
2023-04-14 02:55:49 +05:30
async def last_activity(self, appliance: HonAppliance) -> Dict:
url: str = f"{const.API_URL}/commands/v1/retrieve-last-activity"
params: Dict = {"macAddress": appliance.mac_address}
2023-04-09 21:43:50 +05:30
async with self._hon.get(url, params=params) as response:
2023-04-14 02:55:49 +05:30
result: Dict = await response.json()
2023-03-19 05:38:54 +05:30
if result and (activity := result.get("attributes")):
return activity
return {}
2023-04-14 02:55:49 +05:30
async def load_attributes(self, appliance: HonAppliance) -> Dict:
params: Dict = {
2023-04-10 00:20:28 +05:30
"macAddress": appliance.mac_address,
"applianceType": appliance.appliance_type,
2023-04-10 00:25:36 +05:30
"category": "CYCLE",
2023-02-13 06:11:38 +05:30
}
2023-04-14 02:55:49 +05:30
url: str = f"{const.API_URL}/commands/v1/context"
2023-04-09 21:43:50 +05:30
async with self._hon.get(url, params=params) as response:
2023-02-13 06:11:38 +05:30
return (await response.json()).get("payload", {})
2023-04-14 02:55:49 +05:30
async def load_statistics(self, appliance: HonAppliance) -> Dict:
params: Dict = {
2023-04-10 00:20:28 +05:30
"macAddress": appliance.mac_address,
2023-04-10 00:25:36 +05:30
"applianceType": appliance.appliance_type,
2023-02-13 06:11:38 +05:30
}
2023-04-14 02:55:49 +05:30
url: str = f"{const.API_URL}/commands/v1/statistics"
2023-04-09 21:43:50 +05:30
async with self._hon.get(url, params=params) as response:
2023-02-13 06:11:38 +05:30
return (await response.json()).get("payload", {})
2023-04-14 02:55:49 +05:30
async def send_command(
self,
appliance: HonAppliance,
command: str,
parameters: Dict,
ancillary_parameters: Dict,
) -> bool:
now: str = datetime.utcnow().isoformat()
data: Dict = {
2023-04-10 00:20:28 +05:30
"macAddress": appliance.mac_address,
2023-02-13 06:11:38 +05:30
"timestamp": f"{now[:-3]}Z",
"commandName": command,
2023-04-10 00:20:28 +05:30
"transactionId": f"{appliance.mac_address}_{now[:-3]}Z",
"applianceOptions": appliance.commands_options,
2023-04-15 03:59:24 +05:30
"device": self._hon.device.get(mobile=True),
2023-02-13 06:11:38 +05:30
"attributes": {
"channel": "mobileApp",
"origin": "standardProgram",
2023-04-10 00:25:36 +05:30
"energyLabel": "0",
2023-02-13 06:11:38 +05:30
},
"ancillaryParameters": ancillary_parameters,
"parameters": parameters,
2023-04-10 00:25:36 +05:30
"applianceType": appliance.appliance_type,
2023-02-13 06:11:38 +05:30
}
2023-04-14 02:55:49 +05:30
url: str = f"{const.API_URL}/commands/v1/send"
2023-04-15 03:59:24 +05:30
async with self._hon.post(url, json=data) as response:
json_data: Dict = await response.json()
2023-04-10 00:20:28 +05:30
if json_data.get("payload", {}).get("resultCode") == "0":
2023-02-13 06:11:38 +05:30
return True
2023-04-15 03:59:24 +05:30
_LOGGER.error(await response.text())
2023-02-13 06:11:38 +05:30
return False
2023-04-09 21:43:50 +05:30
2023-04-14 02:55:49 +05:30
async def appliance_configuration(self) -> Dict:
url: str = f"{const.API_URL}/config/v1/appliance-configuration"
2023-04-09 21:43:50 +05:30
async with self._hon_anonymous.get(url) as response:
2023-04-14 02:55:49 +05:30
result: Dict = await response.json()
2023-04-09 21:43:50 +05:30
if result and (data := result.get("payload")):
return data
return {}
2023-04-14 02:55:49 +05:30
async def app_config(self, language: str = "en", beta: bool = True) -> Dict:
url: str = f"{const.API_URL}/app-config"
payload_data: Dict = {
2023-04-09 21:43:50 +05:30
"languageCode": language,
"beta": beta,
"appVersion": const.APP_VERSION,
2023-04-10 00:25:36 +05:30
"os": const.OS,
2023-04-09 21:43:50 +05:30
}
2023-04-14 02:55:49 +05:30
payload: str = json.dumps(payload_data, separators=(",", ":"))
2023-04-09 21:43:50 +05:30
async with self._hon_anonymous.post(url, data=payload) as response:
if (result := await response.json()) and (data := result.get("payload")):
return data
return {}
2023-04-14 02:55:49 +05:30
async def translation_keys(self, language: str = "en") -> Dict:
2023-04-09 21:43:50 +05:30
config = await self.app_config(language=language)
if url := config.get("language", {}).get("jsonPath"):
async with self._hon_anonymous.get(url) as response:
if result := await response.json():
return result
return {}
2023-04-10 00:20:28 +05:30
2023-04-14 02:55:49 +05:30
async def close(self) -> None:
if self._hon_handler is not None:
await self._hon_handler.close()
if self._hon_anonymous_handler is not None:
await self._hon_anonymous_handler.close()