| 1 |
from .feature import Feature |
| 2 |
from typing import TYPE_CHECKING, Optional, Any, Union |
| 3 |
|
| 4 |
if TYPE_CHECKING: |
| 5 |
from .box import Box |
| 6 |
|
| 7 |
|
| 8 |
class Switch(Feature): |
| 9 |
_is_on: Optional[bool] |
| 10 |
|
| 11 |
def __init__( |
| 12 |
self, |
| 13 |
product: "Box", |
| 14 |
alias: str, |
| 15 |
methods: dict, |
| 16 |
dev_class: str, |
| 17 |
unit_id: Union[str, int, None] = 0, |
| 18 |
name: Optional[str] = None, |
| 19 |
): |
| 20 |
methods = self.resolve_access_method_paths(methods, str(unit_id)) |
| 21 |
super().__init__(product, alias, methods) |
| 22 |
self._device_class = dev_class |
| 23 |
self._unit_id = unit_id |
| 24 |
self._name = name |
| 25 |
|
| 26 |
@classmethod |
| 27 |
def many_from_config( |
| 28 |
cls, product, box_type_config, extended_state |
| 29 |
) -> list["Switch"]: |
| 30 |
""" |
| 31 |
:param product: Object hosting device with specific feature. |
| 32 |
:param box_type_config: Default configuration providing following data |
| 33 |
[ |
| 34 |
[feature_alias, {method_name: method_path_or_method_path_callable}, relay_type, unit_id] |
| 35 |
] |
| 36 |
:param extended_state: Object hosting extended state recieved from device |
| 37 |
:return: List of class objects instances |
| 38 |
""" |
| 39 |
if extended_state: |
| 40 |
relay_list = list() |
| 41 |
alias, methods, relay_type, *rest = box_type_config[0] |
| 42 |
for relay in extended_state.get("relays", []): |
| 43 |
relay_id = relay.get("relay") |
| 44 |
relay_list.append( |
| 45 |
cls( |
| 46 |
product, |
| 47 |
alias + "_" + str(relay_id), |
| 48 |
methods, |
| 49 |
relay_type, |
| 50 |
relay_id, |
| 51 |
name=relay.get("name"), |
| 52 |
) |
| 53 |
) |
| 54 |
|
| 55 |
return relay_list |
| 56 |
else: |
| 57 |
return [cls(product, *args) for args in box_type_config] |
| 58 |
|
| 59 |
def after_update(self) -> None: |
| 60 |
self._is_on = self._read_is_on() |
| 61 |
|
| 62 |
def _read_is_on(self) -> Optional[bool]: |
| 63 |
product = self._product |
| 64 |
if product.last_data is not None: |
| 65 |
raw = self.raw_value("state") |
| 66 |
if raw is not None: |
| 67 |
alias = self._alias |
| 68 |
return 1 == product.expect_int(alias, raw, 1, 0) |
| 69 |
return None |
| 70 |
|
| 71 |
@property |
| 72 |
def is_on(self) -> Optional[bool]: |
| 73 |
return self._is_on |
| 74 |
|
| 75 |
@property |
| 76 |
def _unit_args(self) -> list: |
| 77 |
unit = self._unit_id |
| 78 |
return [] if unit is None else [unit] |
| 79 |
|
| 80 |
@property |
| 81 |
def index(self) -> Optional[int]: |
| 82 |
return self._unit_id |
| 83 |
|
| 84 |
@property |
| 85 |
def name(self) -> Optional[str]: |
| 86 |
return self._name |
| 87 |
|
| 88 |
async def async_turn_on(self, **kwargs: Any) -> None: |
| 89 |
await self.async_api_command("on", *self._unit_args) |
| 90 |
|
| 91 |
async def async_turn_off(self, **kwargs: Any) -> None: |
| 92 |
await self.async_api_command("off", *self._unit_args) |