pyh0n/pyhon/appliance.py

297 lines
10 KiB
Python
Raw Normal View History

2023-03-05 23:16:51 +05:30
import importlib
2023-04-23 23:44:52 +05:30
import logging
2023-06-28 23:12:21 +05:30
import re
2023-05-07 03:58:24 +05:30
from datetime import datetime, timedelta
2023-05-11 04:13:48 +05:30
from pathlib import Path
2023-06-28 22:32:11 +05:30
from typing import Optional, Dict, Any, TYPE_CHECKING, List
2023-03-05 23:16:51 +05:30
2023-06-28 22:32:11 +05:30
from pyhon import diagnose, exceptions
2023-07-01 18:29:09 +05:30
from pyhon.appliances.base import ApplianceBase
2023-06-13 03:42:29 +05:30
from pyhon.attributes import HonAttribute
2023-06-15 05:46:03 +05:30
from pyhon.command_loader import HonCommandLoader
2023-02-13 08:06:09 +05:30
from pyhon.commands import HonCommand
2023-05-08 05:53:48 +05:30
from pyhon.parameter.base import HonParameter
2023-07-11 03:28:24 +05:30
from pyhon.parameter.enum import HonParameterEnum
2023-05-28 21:04:32 +05:30
from pyhon.parameter.range import HonParameterRange
2023-06-28 22:32:11 +05:30
from pyhon.typedefs import Parameter
2023-02-13 06:11:38 +05:30
2023-04-15 19:25:22 +05:30
if TYPE_CHECKING:
from pyhon import HonAPI
2023-04-23 23:44:52 +05:30
_LOGGER = logging.getLogger(__name__)
2023-07-16 09:23:23 +05:30
# pylint: disable=too-many-public-methods,too-many-instance-attributes
2023-04-09 21:43:50 +05:30
class HonAppliance:
2023-05-07 03:58:24 +05:30
_MINIMAL_UPDATE_INTERVAL = 5 # seconds
2023-04-15 19:25:22 +05:30
def __init__(
self, api: Optional["HonAPI"], info: Dict[str, Any], zone: int = 0
) -> None:
2023-04-10 00:20:28 +05:30
if attributes := info.get("attributes"):
info["attributes"] = {v["parName"]: v["parValue"] for v in attributes}
2023-06-28 22:32:11 +05:30
self._info: Dict[str, Any] = info
2023-04-15 19:25:22 +05:30
self._api: Optional[HonAPI] = api
2023-06-28 22:32:11 +05:30
self._appliance_model: Dict[str, Any] = {}
2023-02-13 06:11:38 +05:30
2023-06-21 23:23:36 +05:30
self._commands: Dict[str, HonCommand] = {}
2023-06-28 22:32:11 +05:30
self._statistics: Dict[str, Any] = {}
self._attributes: Dict[str, Any] = {}
2023-04-16 01:55:34 +05:30
self._zone: int = zone
2023-05-06 23:30:13 +05:30
self._additional_data: Dict[str, Any] = {}
2023-06-28 22:32:11 +05:30
self._last_update: Optional[datetime] = None
2023-05-08 05:53:48 +05:30
self._default_setting = HonParameter("", {}, "")
2023-02-13 06:11:38 +05:30
2023-03-08 05:28:25 +05:30
try:
2023-07-01 18:29:09 +05:30
self._extra: Optional[ApplianceBase] = importlib.import_module(
2023-04-10 00:25:36 +05:30
f"pyhon.appliances.{self.appliance_type.lower()}"
2023-04-24 01:12:44 +05:30
).Appliance(self)
2023-03-08 05:28:25 +05:30
except ModuleNotFoundError:
self._extra = None
2023-07-21 03:22:07 +05:30
def _get_nested_item(self, item: str) -> Any:
result: List[Any] | Dict[str, Any] = self.data
for key in item.split("."):
if all(k in "0123456789" for k in key) and isinstance(result, list):
result = result[int(key)]
elif isinstance(result, dict):
result = result[key]
return result
2023-06-28 22:32:11 +05:30
def __getitem__(self, item: str) -> Any:
2023-04-15 07:42:38 +05:30
if self._zone:
item += f"Z{self._zone}"
2023-03-08 05:28:25 +05:30
if "." in item:
2023-07-21 03:22:07 +05:30
return self._get_nested_item(item)
2023-04-15 07:42:38 +05:30
if item in self.data:
return self.data[item]
if item in self.attributes["parameters"]:
2023-06-13 03:42:29 +05:30
return self.attributes["parameters"][item].value
2023-04-15 07:42:38 +05:30
return self.info[item]
2023-02-13 06:11:38 +05:30
2023-06-28 22:32:11 +05:30
def get(self, item: str, default: Any = None) -> Any:
2023-03-09 02:23:53 +05:30
try:
return self[item]
2023-03-09 02:48:44 +05:30
except (KeyError, IndexError):
2023-03-09 02:23:53 +05:30
return default
2023-04-15 07:42:38 +05:30
def _check_name_zone(self, name: str, frontend: bool = True) -> str:
2023-06-28 23:12:21 +05:30
zone = " Z" if frontend else "_z"
2023-07-01 18:29:09 +05:30
attribute: str = self._info.get(name, "")
if attribute and self._zone:
2023-06-28 23:12:21 +05:30
return f"{attribute}{zone}{self._zone}"
2023-04-15 07:42:38 +05:30
return attribute
2023-02-13 06:11:38 +05:30
@property
2023-04-15 07:42:38 +05:30
def appliance_model_id(self) -> str:
2023-04-15 19:25:22 +05:30
return self._info.get("applianceModelId", "")
2023-02-13 06:11:38 +05:30
@property
2023-04-15 07:42:38 +05:30
def appliance_type(self) -> str:
2023-04-15 19:25:22 +05:30
return self._info.get("applianceTypeName", "")
2023-02-13 06:11:38 +05:30
@property
2023-04-15 07:42:38 +05:30
def mac_address(self) -> str:
2023-04-16 01:28:20 +05:30
return self.info.get("macAddress", "")
@property
def unique_id(self) -> str:
2023-06-28 23:12:21 +05:30
default_mac = "xx-xx-xx-xx-xx-xx"
import_name = f"{self.appliance_type.lower()}_{self.appliance_model_id}"
result = self._check_name_zone("macAddress", frontend=False)
result = result.replace(default_mac, import_name)
return result
2023-02-13 06:11:38 +05:30
@property
2023-04-15 07:42:38 +05:30
def model_name(self) -> str:
return self._check_name_zone("modelName")
2023-02-13 06:11:38 +05:30
2023-06-25 20:59:04 +05:30
@property
def brand(self) -> str:
2023-07-01 19:34:34 +05:30
brand = self._check_name_zone("brand")
return brand[0].upper() + brand[1:]
2023-06-25 20:59:04 +05:30
2023-02-13 06:11:38 +05:30
@property
2023-04-15 07:42:38 +05:30
def nick_name(self) -> str:
2023-06-28 23:12:21 +05:30
result = self._check_name_zone("nickName")
2023-07-10 03:28:55 +05:30
if not result or re.findall("^[xX1\\s-]+$", result):
2023-06-28 23:12:21 +05:30
return self.model_name
return result
2023-02-13 06:11:38 +05:30
2023-05-20 16:54:24 +05:30
@property
def code(self) -> str:
2023-07-01 18:29:09 +05:30
code: str = self.info.get("code", "")
if code:
2023-05-20 16:54:24 +05:30
return code
2023-07-01 18:29:09 +05:30
serial_number: str = self.info.get("serialNumber", "")
2023-05-20 16:54:24 +05:30
return serial_number[:8] if len(serial_number) < 18 else serial_number[:11]
2023-06-25 20:59:04 +05:30
@property
def model_id(self) -> int:
return self._info.get("applianceModelId", 0)
2023-02-13 06:11:38 +05:30
@property
2023-06-28 22:32:11 +05:30
def options(self) -> Dict[str, Any]:
2023-05-21 05:55:43 +05:30
return self._appliance_model.get("options", {})
2023-02-13 06:11:38 +05:30
@property
2023-06-21 23:23:36 +05:30
def commands(self) -> Dict[str, HonCommand]:
2023-02-13 06:11:38 +05:30
return self._commands
@property
2023-06-28 22:32:11 +05:30
def attributes(self) -> Dict[str, Any]:
2023-03-05 01:57:10 +05:30
return self._attributes
2023-02-13 06:11:38 +05:30
@property
2023-06-28 22:32:11 +05:30
def statistics(self) -> Dict[str, Any]:
2023-02-13 06:11:38 +05:30
return self._statistics
2023-03-05 23:16:51 +05:30
@property
2023-06-28 22:32:11 +05:30
def info(self) -> Dict[str, Any]:
2023-04-10 00:20:28 +05:30
return self._info
2023-03-05 23:16:51 +05:30
2023-05-06 19:37:28 +05:30
@property
2023-06-28 22:32:11 +05:30
def additional_data(self) -> Dict[str, Any]:
2023-05-06 19:37:28 +05:30
return self._additional_data
2023-04-16 01:55:34 +05:30
@property
def zone(self) -> int:
return self._zone
2023-05-06 23:30:13 +05:30
@property
2023-06-28 22:32:11 +05:30
def api(self) -> "HonAPI":
"""api connection object"""
if self._api is None:
raise exceptions.NoAuthenticationException("Missing hOn login")
2023-05-06 23:30:13 +05:30
return self._api
2023-06-28 22:32:11 +05:30
async def load_commands(self) -> None:
2023-06-15 05:46:03 +05:30
command_loader = HonCommandLoader(self.api, self)
2023-06-25 20:59:04 +05:30
await command_loader.load_commands()
2023-06-15 05:46:03 +05:30
self._commands = command_loader.commands
self._additional_data = command_loader.additional_data
self._appliance_model = command_loader.appliance_data
2023-07-01 19:34:34 +05:30
self.sync_params_to_command("settings")
2023-05-28 22:54:02 +05:30
2023-06-28 22:32:11 +05:30
async def load_attributes(self) -> None:
2023-07-01 19:57:50 +05:30
attributes = await self.api.load_attributes(self)
2023-07-01 19:58:18 +05:30
for name, values in attributes.pop("shadow", {}).get("parameters", {}).items():
2023-06-13 03:42:29 +05:30
if name in self._attributes.get("parameters", {}):
self._attributes["parameters"][name].update(values)
else:
2023-06-15 05:46:03 +05:30
self._attributes.setdefault("parameters", {})[name] = HonAttribute(
values
)
2023-07-01 19:57:50 +05:30
self._attributes |= attributes
2023-06-08 23:20:56 +05:30
if self._extra:
self._attributes = self._extra.attributes(self._attributes)
2023-02-13 06:11:38 +05:30
2023-06-28 22:32:11 +05:30
async def load_statistics(self) -> None:
2023-05-06 23:30:13 +05:30
self._statistics = await self.api.load_statistics(self)
2023-05-13 03:46:52 +05:30
self._statistics |= await self.api.load_maintenance(self)
2023-02-13 08:06:09 +05:30
2023-06-28 22:32:11 +05:30
async def update(self, force: bool = False) -> None:
2023-05-07 03:58:24 +05:30
now = datetime.now()
min_age = now - timedelta(seconds=self._MINIMAL_UPDATE_INTERVAL)
if force or not self._last_update or self._last_update < min_age:
2023-05-07 03:58:24 +05:30
self._last_update = now
await self.load_attributes()
2023-07-01 19:34:34 +05:30
self.sync_params_to_command("settings")
2023-03-03 22:54:19 +05:30
2023-05-06 19:37:28 +05:30
@property
2023-06-28 22:32:11 +05:30
def command_parameters(self) -> Dict[str, Dict[str, str | float]]:
2023-05-06 23:30:13 +05:30
return {n: c.parameter_value for n, c in self._commands.items()}
2023-05-06 19:37:28 +05:30
@property
2023-06-28 22:32:11 +05:30
def settings(self) -> Dict[str, Parameter]:
2023-07-01 18:29:09 +05:30
result: Dict[str, Parameter] = {}
2023-05-06 19:37:28 +05:30
for name, command in self._commands.items():
for key in command.setting_keys:
2023-05-08 05:53:48 +05:30
setting = command.settings.get(key, self._default_setting)
2023-05-06 19:37:28 +05:30
result[f"{name}.{key}"] = setting
if self._extra:
return self._extra.settings(result)
return result
2023-05-07 03:58:24 +05:30
@property
2023-06-28 22:32:11 +05:30
def available_settings(self) -> List[str]:
2023-05-07 03:58:24 +05:30
result = []
for name, command in self._commands.items():
for key in command.setting_keys:
result.append(f"{name}.{key}")
return result
2023-03-03 22:54:19 +05:30
@property
2023-06-28 22:32:11 +05:30
def data(self) -> Dict[str, Any]:
2023-04-10 00:25:36 +05:30
result = {
"attributes": self.attributes,
"appliance": self.info,
"statistics": self.statistics,
2023-05-06 19:37:28 +05:30
"additional_data": self._additional_data,
2023-05-06 23:30:13 +05:30
**self.command_parameters,
2023-06-08 23:20:56 +05:30
**self.attributes,
2023-04-10 00:25:36 +05:30
}
2023-03-08 05:28:25 +05:30
return result
2023-04-12 01:44:36 +05:30
2023-06-25 20:59:04 +05:30
@property
def diagnose(self) -> str:
return diagnose.yaml_export(self, anonymous=True)
async def data_archive(self, path: Path) -> str:
return await diagnose.zip_archive(self, path, anonymous=True)
2023-05-11 04:13:48 +05:30
2023-07-01 19:34:34 +05:30
def sync_command_to_params(self, command_name: str) -> None:
2023-06-28 22:32:11 +05:30
if not (command := self.commands.get(command_name)):
return
2023-07-01 19:34:34 +05:30
for key in self.attributes.get("parameters", {}):
2023-07-01 18:01:37 +05:30
if new := command.parameters.get(key):
2023-06-15 05:46:03 +05:30
self.attributes["parameters"][key].update(
str(new.intern_value), shield=True
)
2023-06-08 23:20:56 +05:30
2023-07-01 19:34:34 +05:30
def sync_params_to_command(self, command_name: str) -> None:
if not (command := self.commands.get(command_name)):
return
for key in command.setting_keys:
2023-07-19 23:22:21 +05:30
if (
new := self.attributes.get("parameters", {}).get(key)
) is None or new.value == "":
2023-07-01 19:34:34 +05:30
continue
setting = command.settings[key]
try:
if not isinstance(setting, HonParameterRange):
command.settings[key].value = str(new.value)
else:
command.settings[key].value = float(new.value)
except ValueError as error:
_LOGGER.info("Can't set %s - %s", key, error)
continue
2023-07-01 18:01:37 +05:30
def sync_command(self, main: str, target: Optional[List[str] | str] = None) -> None:
2023-06-21 23:23:36 +05:30
base: Optional[HonCommand] = self.commands.get(main)
if not base:
return
2023-05-28 09:47:43 +05:30
for command, data in self.commands.items():
if command == main or target and command not in target:
continue
for name, target_param in data.parameters.items():
if not (base_param := base.parameters.get(name)):
return
self.sync_parameter(base_param, target_param)
def sync_parameter(self, main: Parameter, target: Parameter) -> None:
if isinstance(main, HonParameterRange) and isinstance(
target, HonParameterRange
):
target.max = main.max
target.min = main.min
target.step = main.step
elif isinstance(target, HonParameterRange):
target.max = int(main.value)
target.min = int(main.value)
target.step = 1
elif isinstance(target, HonParameterEnum):
target.values = main.values
target.value = main.value