pyh0n/pyhon/appliance.py

207 lines
6.7 KiB
Python
Raw Normal View History

2023-03-05 23:16:51 +05:30
import importlib
from contextlib import suppress
2023-04-15 19:25:22 +05:30
from typing import Optional, Dict, Any
from typing import TYPE_CHECKING
2023-03-05 23:16:51 +05:30
2023-04-12 01:44:36 +05:30
from pyhon import helper
2023-02-13 08:06:09 +05:30
from pyhon.commands import HonCommand
from pyhon.parameter import HonParameterFixed
2023-02-13 06:11:38 +05:30
2023-04-15 19:25:22 +05:30
if TYPE_CHECKING:
from pyhon import HonAPI
2023-02-13 06:11:38 +05:30
2023-04-09 21:43:50 +05:30
class HonAppliance:
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-04-15 19:25:22 +05:30
self._info: Dict = info
self._api: Optional[HonAPI] = api
self._appliance_model: Dict = {}
2023-02-13 06:11:38 +05:30
2023-04-15 19:25:22 +05:30
self._commands: Dict = {}
self._statistics: Dict = {}
self._attributes: Dict = {}
2023-04-15 07:42:38 +05:30
self._zone = zone
2023-02-13 06:11:38 +05:30
2023-03-08 05:28:25 +05:30
try:
2023-04-10 00:25:36 +05:30
self._extra = importlib.import_module(
f"pyhon.appliances.{self.appliance_type.lower()}"
).Appliance()
2023-03-08 05:28:25 +05:30
except ModuleNotFoundError:
self._extra = None
def __getitem__(self, item):
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:
result = self.data
for key in item.split("."):
2023-04-15 07:42:38 +05:30
if all(k in "0123456789" for k in key) and isinstance(result, list):
2023-03-08 05:28:25 +05:30
result = result[int(key)]
else:
result = result[key]
return result
2023-04-15 07:42:38 +05:30
if item in self.data:
return self.data[item]
if item in self.attributes["parameters"]:
return self.attributes["parameters"].get(item)
return self.info[item]
2023-02-13 06:11:38 +05:30
2023-03-09 02:23:53 +05:30
def get(self, item, default=None):
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:
middle = " Z" if frontend else "_z"
if (attribute := self._info.get(name, "")) and self._zone:
return f"{attribute}{middle}{self._zone}"
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-04-15 07:42:38 +05:30
return self._check_name_zone("macAddress", frontend=False)
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
@property
2023-04-15 07:42:38 +05:30
def nick_name(self) -> str:
return self._check_name_zone("nickName")
2023-02-13 06:11:38 +05:30
@property
def commands_options(self):
return self._appliance_model.get("options")
@property
def commands(self):
return self._commands
@property
def attributes(self):
2023-03-05 01:57:10 +05:30
return self._attributes
2023-02-13 06:11:38 +05:30
@property
def statistics(self):
return self._statistics
2023-03-05 23:16:51 +05:30
@property
2023-04-10 00:20:28 +05:30
def info(self):
return self._info
2023-03-05 23:16:51 +05:30
2023-03-11 07:01:56 +05:30
async def _recover_last_command_states(self, commands):
2023-04-10 00:20:28 +05:30
command_history = await self._api.command_history(self)
2023-03-11 07:01:56 +05:30
for name, command in commands.items():
2023-04-10 00:25:36 +05:30
last = next(
(
index
for (index, d) in enumerate(command_history)
if d.get("command", {}).get("commandName") == name
),
None,
)
2023-03-11 07:01:56 +05:30
if last is None:
continue
parameters = command_history[last].get("command", {}).get("parameters", {})
if command._multi and parameters.get("program"):
command.set_program(parameters.pop("program").split(".")[-1].lower())
command = self.commands[name]
for key, data in command.settings.items():
2023-04-10 00:25:36 +05:30
if (
not isinstance(data, HonParameterFixed)
and parameters.get(key) is not None
):
with suppress(ValueError):
data.value = parameters.get(key)
2023-03-11 07:01:56 +05:30
2023-02-13 06:11:38 +05:30
async def load_commands(self):
2023-04-10 00:20:28 +05:30
raw = await self._api.load_commands(self)
2023-02-13 06:11:38 +05:30
self._appliance_model = raw.pop("applianceModel")
for item in ["settings", "options", "dictionaryId"]:
raw.pop(item)
commands = {}
for command, attr in raw.items():
if "parameters" in attr:
2023-04-10 00:20:28 +05:30
commands[command] = HonCommand(command, attr, self._api, self)
2023-02-13 06:11:38 +05:30
elif "parameters" in attr[list(attr)[0]]:
multi = {}
2023-03-11 05:40:27 +05:30
for program, attr2 in attr.items():
program = program.split(".")[-1].lower()
2023-04-10 00:25:36 +05:30
cmd = HonCommand(
command, attr2, self._api, self, multi=multi, program=program
)
2023-03-11 05:40:27 +05:30
multi[program] = cmd
2023-02-13 06:11:38 +05:30
commands[command] = cmd
self._commands = commands
2023-03-11 07:01:56 +05:30
await self._recover_last_command_states(commands)
2023-02-13 06:11:38 +05:30
2023-02-19 02:55:51 +05:30
@property
def settings(self):
result = {}
2023-02-20 00:13:41 +05:30
for name, command in self._commands.items():
for key, setting in command.settings.items():
result[f"{name}.{key}"] = setting
2023-04-08 07:36:36 +05:30
if self._extra:
return self._extra.settings(result)
2023-02-20 00:13:41 +05:30
return result
@property
def parameters(self):
result = {}
for name, command in self._commands.items():
for key, parameter in command.parameters.items():
2023-03-08 05:28:25 +05:30
result.setdefault(name, {})[key] = parameter.value
2023-02-19 02:55:51 +05:30
return result
2023-02-13 06:11:38 +05:30
async def load_attributes(self):
2023-04-10 00:20:28 +05:30
self._attributes = await self._api.load_attributes(self)
2023-03-08 05:28:25 +05:30
for name, values in self._attributes.pop("shadow").get("parameters").items():
self._attributes.setdefault("parameters", {})[name] = values["parNewVal"]
2023-02-13 06:11:38 +05:30
async def load_statistics(self):
2023-04-10 00:20:28 +05:30
self._statistics = await self._api.load_statistics(self)
2023-02-13 08:06:09 +05:30
async def update(self):
await self.load_attributes()
2023-03-03 22:54:19 +05:30
@property
def data(self):
2023-04-10 00:25:36 +05:30
result = {
"attributes": self.attributes,
"appliance": self.info,
"statistics": self.statistics,
**self.parameters,
}
2023-03-08 05:28:25 +05:30
if self._extra:
2023-04-08 07:36:36 +05:30
return self._extra.data(result)
2023-03-08 05:28:25 +05:30
return result
2023-04-12 01:44:36 +05:30
@property
def diagnose(self):
data = self.data.copy()
2023-04-15 02:54:31 +05:30
for sensible in ["PK", "SK", "serialNumber", "code", "coords"]:
2023-04-12 01:44:36 +05:30
data["appliance"].pop(sensible, None)
result = helper.pretty_print({"data": self.data}, whitespace="\u200B \u200B ")
result += helper.pretty_print(
{"commands": helper.create_command(self.commands)},
whitespace="\u200B \u200B ",
)
return result.replace(self.mac_address, "12-34-56-78-90-ab")