2024-02-04 15:20:08 +00:00
|
|
|
"""Module for a SMART device."""
|
2023-11-30 12:10:49 +00:00
|
|
|
import base64
|
|
|
|
import logging
|
2024-02-19 17:01:31 +00:00
|
|
|
from datetime import datetime, timedelta
|
2024-02-15 15:25:08 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, cast
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2023-12-19 14:11:59 +00:00
|
|
|
from ..aestransport import AesTransport
|
2024-02-04 15:20:08 +00:00
|
|
|
from ..device import Device, WifiNetwork
|
2024-01-29 16:11:29 +00:00
|
|
|
from ..device_type import DeviceType
|
2023-12-29 19:17:15 +00:00
|
|
|
from ..deviceconfig import DeviceConfig
|
2024-01-03 18:04:34 +00:00
|
|
|
from ..emeterstatus import EmeterStatus
|
2024-02-21 15:52:55 +00:00
|
|
|
from ..exceptions import AuthenticationError, DeviceError, KasaException, SmartErrorCode
|
2024-02-15 15:25:08 +00:00
|
|
|
from ..feature import Feature, FeatureType
|
2023-12-04 18:50:05 +00:00
|
|
|
from ..smartprotocol import SmartProtocol
|
2024-02-19 17:01:31 +00:00
|
|
|
from .modules import ( # noqa: F401
|
2024-02-19 20:11:11 +00:00
|
|
|
AutoOffModule,
|
2024-02-19 17:01:31 +00:00
|
|
|
ChildDeviceModule,
|
2024-02-19 19:59:09 +00:00
|
|
|
CloudModule,
|
2024-02-19 17:01:31 +00:00
|
|
|
DeviceModule,
|
|
|
|
EnergyModule,
|
2024-02-19 19:59:09 +00:00
|
|
|
LedModule,
|
2024-02-19 19:39:20 +00:00
|
|
|
LightTransitionModule,
|
2024-02-19 17:01:31 +00:00
|
|
|
TimeModule,
|
|
|
|
)
|
|
|
|
from .smartmodule import SmartModule
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
if TYPE_CHECKING:
|
2024-02-04 15:20:08 +00:00
|
|
|
from .smartchilddevice import SmartChildDevice
|
2024-02-02 16:29:14 +00:00
|
|
|
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2024-02-04 15:20:08 +00:00
|
|
|
class SmartDevice(Device):
|
|
|
|
"""Base class to represent a SMART protocol based device."""
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
*,
|
2023-12-29 19:17:15 +00:00
|
|
|
config: Optional[DeviceConfig] = None,
|
2024-01-29 16:11:29 +00:00
|
|
|
protocol: Optional[SmartProtocol] = None,
|
2023-11-30 12:10:49 +00:00
|
|
|
) -> None:
|
2023-12-29 19:17:15 +00:00
|
|
|
_protocol = protocol or SmartProtocol(
|
|
|
|
transport=AesTransport(config=config or DeviceConfig(host=host)),
|
|
|
|
)
|
|
|
|
super().__init__(host=host, config=config, protocol=_protocol)
|
2024-01-29 16:11:29 +00:00
|
|
|
self.protocol: SmartProtocol
|
2024-01-03 18:04:34 +00:00
|
|
|
self._components_raw: Optional[Dict[str, Any]] = None
|
2024-02-02 16:29:14 +00:00
|
|
|
self._components: Dict[str, int] = {}
|
2024-02-04 15:20:08 +00:00
|
|
|
self._children: Dict[str, "SmartChildDevice"] = {}
|
2023-11-30 12:10:49 +00:00
|
|
|
self._state_information: Dict[str, Any] = {}
|
2024-02-19 17:01:31 +00:00
|
|
|
self.modules: Dict[str, SmartModule] = {}
|
2024-01-29 16:11:29 +00:00
|
|
|
|
|
|
|
async def _initialize_children(self):
|
2024-02-02 16:29:14 +00:00
|
|
|
"""Initialize children for power strips."""
|
2024-01-29 16:11:29 +00:00
|
|
|
children = self._last_update["child_info"]["child_device_list"]
|
|
|
|
# TODO: Use the type information to construct children,
|
|
|
|
# as hubs can also have them.
|
2024-02-04 15:20:08 +00:00
|
|
|
from .smartchilddevice import SmartChildDevice
|
2024-01-29 16:11:29 +00:00
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
self._children = {
|
2024-02-04 15:20:08 +00:00
|
|
|
child["device_id"]: SmartChildDevice(
|
|
|
|
parent=self, child_id=child["device_id"]
|
|
|
|
)
|
2024-02-02 16:29:14 +00:00
|
|
|
for child in children
|
|
|
|
}
|
2024-01-29 16:11:29 +00:00
|
|
|
self._device_type = DeviceType.Strip
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
@property
|
2024-02-04 15:20:08 +00:00
|
|
|
def children(self) -> Sequence["SmartDevice"]:
|
|
|
|
"""Return list of children."""
|
2024-02-02 16:29:14 +00:00
|
|
|
return list(self._children.values())
|
|
|
|
|
2024-02-15 18:10:34 +00:00
|
|
|
def _try_get_response(self, responses: dict, request: str, default=None) -> dict:
|
|
|
|
response = responses.get(request)
|
|
|
|
if isinstance(response, SmartErrorCode):
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Error %s getting request %s for device %s",
|
|
|
|
response,
|
|
|
|
request,
|
|
|
|
self.host,
|
|
|
|
)
|
|
|
|
response = None
|
|
|
|
if response is not None:
|
|
|
|
return response
|
|
|
|
if default is not None:
|
|
|
|
return default
|
2024-02-21 15:52:55 +00:00
|
|
|
raise KasaException(
|
2024-02-15 18:10:34 +00:00
|
|
|
f"{request} not found in {responses} for device {self.host}"
|
|
|
|
)
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
async def _negotiate(self):
|
|
|
|
resp = await self.protocol.query("component_nego")
|
|
|
|
self._components_raw = resp["component_nego"]
|
|
|
|
self._components = {
|
|
|
|
comp["id"]: int(comp["ver_code"])
|
|
|
|
for comp in self._components_raw["component_list"]
|
|
|
|
}
|
|
|
|
|
2023-11-30 12:10:49 +00:00
|
|
|
async def update(self, update_children: bool = True):
|
|
|
|
"""Update the device."""
|
2024-01-03 21:46:08 +00:00
|
|
|
if self.credentials is None and self.credentials_hash is None:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise AuthenticationError("Tapo plug requires authentication.")
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2024-01-03 18:04:34 +00:00
|
|
|
if self._components_raw is None:
|
2024-02-19 17:01:31 +00:00
|
|
|
await self._negotiate()
|
2024-01-03 18:04:34 +00:00
|
|
|
await self._initialize_modules()
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
req: Dict[str, Any] = {}
|
2023-12-09 23:32:30 +00:00
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
# TODO: this could be optimized by constructing the query only once
|
|
|
|
for module in self.modules.values():
|
|
|
|
req.update(module.query())
|
2024-01-03 18:04:34 +00:00
|
|
|
|
2023-12-20 17:08:04 +00:00
|
|
|
resp = await self.protocol.query(req)
|
2024-01-03 18:04:34 +00:00
|
|
|
|
2024-02-15 18:10:34 +00:00
|
|
|
self._info = self._try_get_response(resp, "get_device_info")
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
self._last_update = {
|
2024-01-03 18:04:34 +00:00
|
|
|
"components": self._components_raw,
|
2024-02-19 17:01:31 +00:00
|
|
|
**resp,
|
2024-02-15 18:10:34 +00:00
|
|
|
"child_info": self._try_get_response(resp, "get_child_device_list", {}),
|
2023-11-30 12:10:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
if child_info := self._last_update.get("child_info"):
|
2024-01-29 16:11:29 +00:00
|
|
|
if not self.children:
|
|
|
|
await self._initialize_children()
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
for info in child_info["child_device_list"]:
|
|
|
|
self._children[info["device_id"]].update_internal_state(info)
|
2024-01-29 16:11:29 +00:00
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
# We can first initialize the features after the first update.
|
|
|
|
# We make here an assumption that every device has at least a single feature.
|
|
|
|
if not self._features:
|
|
|
|
await self._initialize_features()
|
|
|
|
|
2024-02-02 16:29:14 +00:00
|
|
|
_LOGGER.debug("Got an update: %s", self._last_update)
|
2023-11-30 12:10:49 +00:00
|
|
|
|
2024-01-03 18:04:34 +00:00
|
|
|
async def _initialize_modules(self):
|
|
|
|
"""Initialize modules based on component negotiation response."""
|
2024-02-19 17:01:31 +00:00
|
|
|
from .smartmodule import SmartModule
|
|
|
|
|
|
|
|
for mod in SmartModule.REGISTERED_MODULES.values():
|
|
|
|
_LOGGER.debug("%s requires %s", mod, mod.REQUIRED_COMPONENT)
|
|
|
|
if mod.REQUIRED_COMPONENT in self._components:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Found required %s, adding %s to modules.",
|
|
|
|
mod.REQUIRED_COMPONENT,
|
|
|
|
mod.__name__,
|
|
|
|
)
|
|
|
|
module = mod(self, mod.REQUIRED_COMPONENT)
|
|
|
|
self.modules[module.name] = module
|
2024-01-03 18:04:34 +00:00
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
async def _initialize_features(self):
|
|
|
|
"""Initialize device features."""
|
2024-02-19 17:01:31 +00:00
|
|
|
if "device_on" in self._info:
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
self,
|
|
|
|
"State",
|
|
|
|
attribute_getter="is_on",
|
|
|
|
attribute_setter="set_state",
|
|
|
|
type=FeatureType.Switch,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
self,
|
|
|
|
"Signal Level",
|
|
|
|
attribute_getter=lambda x: x._info["signal_level"],
|
|
|
|
icon="mdi:signal",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
self,
|
|
|
|
"RSSI",
|
|
|
|
attribute_getter=lambda x: x._info["rssi"],
|
|
|
|
icon="mdi:signal",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self._add_feature(
|
|
|
|
Feature(device=self, name="SSID", attribute_getter="ssid", icon="mdi:wifi")
|
|
|
|
)
|
|
|
|
|
|
|
|
if "overheated" in self._info:
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
self,
|
|
|
|
"Overheated",
|
|
|
|
attribute_getter=lambda x: x._info["overheated"],
|
|
|
|
icon="mdi:heat-wave",
|
|
|
|
type=FeatureType.BinarySensor,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# We check for the key available, and not for the property truthiness,
|
|
|
|
# as the value is falsy when the device is off.
|
|
|
|
if "on_time" in self._info:
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
device=self,
|
|
|
|
name="On since",
|
|
|
|
attribute_getter="on_since",
|
|
|
|
icon="mdi:clock",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
for module in self.modules.values():
|
|
|
|
for feat in module._module_features.values():
|
|
|
|
self._add_feature(feat)
|
|
|
|
|
2023-11-30 12:10:49 +00:00
|
|
|
@property
|
|
|
|
def sys_info(self) -> Dict[str, Any]:
|
|
|
|
"""Returns the device info."""
|
2023-12-29 19:17:15 +00:00
|
|
|
return self._info # type: ignore
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def model(self) -> str:
|
|
|
|
"""Returns the device model."""
|
|
|
|
return str(self._info.get("model"))
|
|
|
|
|
|
|
|
@property
|
2024-01-11 15:12:02 +00:00
|
|
|
def alias(self) -> Optional[str]:
|
2023-11-30 12:10:49 +00:00
|
|
|
"""Returns the device alias or nickname."""
|
2024-01-11 15:12:02 +00:00
|
|
|
if self._info and (nickname := self._info.get("nickname")):
|
|
|
|
return base64.b64decode(nickname).decode()
|
|
|
|
else:
|
|
|
|
return None
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def time(self) -> datetime:
|
|
|
|
"""Return the time."""
|
2024-02-19 17:01:31 +00:00
|
|
|
_timemod = cast(TimeModule, self.modules["TimeModule"])
|
|
|
|
return _timemod.time
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def timezone(self) -> Dict:
|
|
|
|
"""Return the timezone and time_difference."""
|
|
|
|
ti = self.time
|
|
|
|
return {"timezone": ti.tzname()}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def hw_info(self) -> Dict:
|
|
|
|
"""Return hardware info for the device."""
|
|
|
|
return {
|
|
|
|
"sw_ver": self._info.get("fw_ver"),
|
|
|
|
"hw_ver": self._info.get("hw_ver"),
|
|
|
|
"mac": self._info.get("mac"),
|
|
|
|
"type": self._info.get("type"),
|
|
|
|
"hwId": self._info.get("device_id"),
|
|
|
|
"dev_name": self.alias,
|
|
|
|
"oemId": self._info.get("oem_id"),
|
|
|
|
}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def location(self) -> Dict:
|
|
|
|
"""Return the device location."""
|
|
|
|
loc = {
|
2024-01-24 12:21:37 +00:00
|
|
|
"latitude": cast(float, self._info.get("latitude", 0)) / 10_000,
|
|
|
|
"longitude": cast(float, self._info.get("longitude", 0)) / 10_000,
|
2023-11-30 12:10:49 +00:00
|
|
|
}
|
|
|
|
return loc
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rssi(self) -> Optional[int]:
|
|
|
|
"""Return the rssi."""
|
|
|
|
rssi = self._info.get("rssi")
|
|
|
|
return int(rssi) if rssi else None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def mac(self) -> str:
|
|
|
|
"""Return the mac formatted with colons."""
|
|
|
|
return str(self._info.get("mac")).replace("-", ":")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def device_id(self) -> str:
|
|
|
|
"""Return the device id."""
|
|
|
|
return str(self._info.get("device_id"))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def internal_state(self) -> Any:
|
|
|
|
"""Return all the internal state data."""
|
2024-02-02 16:29:14 +00:00
|
|
|
return self._last_update
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
async def _query_helper(
|
2024-02-04 15:20:08 +00:00
|
|
|
self, method: str, params: Optional[Dict] = None, child_ids=None
|
2023-11-30 12:10:49 +00:00
|
|
|
) -> Any:
|
2024-02-04 15:20:08 +00:00
|
|
|
res = await self.protocol.query({method: params})
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
@property
|
2024-02-15 15:25:08 +00:00
|
|
|
def ssid(self) -> str:
|
|
|
|
"""Return ssid of the connected wifi ap."""
|
2024-02-02 16:29:14 +00:00
|
|
|
ssid = self._info.get("ssid")
|
|
|
|
ssid = base64.b64decode(ssid).decode() if ssid else "No SSID"
|
2024-02-15 15:25:08 +00:00
|
|
|
return ssid
|
2024-02-02 16:29:14 +00:00
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
@property
|
|
|
|
def state_information(self) -> Dict[str, Any]:
|
|
|
|
"""Return the key state information."""
|
2023-11-30 12:10:49 +00:00
|
|
|
return {
|
|
|
|
"overheated": self._info.get("overheated"),
|
|
|
|
"signal_level": self._info.get("signal_level"),
|
2024-02-15 15:25:08 +00:00
|
|
|
"SSID": self.ssid,
|
2023-11-30 12:10:49 +00:00
|
|
|
}
|
|
|
|
|
2024-01-03 18:04:34 +00:00
|
|
|
@property
|
|
|
|
def has_emeter(self) -> bool:
|
|
|
|
"""Return if the device has emeter."""
|
2024-02-19 17:01:31 +00:00
|
|
|
return "EnergyModule" in self.modules
|
2024-01-03 18:04:34 +00:00
|
|
|
|
2023-11-30 12:10:49 +00:00
|
|
|
@property
|
|
|
|
def is_on(self) -> bool:
|
|
|
|
"""Return true if the device is on."""
|
|
|
|
return bool(self._info.get("device_on"))
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
async def set_state(self, on: bool): # TODO: better name wanted.
|
|
|
|
"""Set the device state.
|
|
|
|
|
|
|
|
See :meth:`is_on`.
|
|
|
|
"""
|
|
|
|
return await self.protocol.query({"set_device_info": {"device_on": on}})
|
|
|
|
|
2023-11-30 12:10:49 +00:00
|
|
|
async def turn_on(self, **kwargs):
|
|
|
|
"""Turn on the device."""
|
2024-02-19 17:01:31 +00:00
|
|
|
await self.set_state(True)
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
async def turn_off(self, **kwargs):
|
|
|
|
"""Turn off the device."""
|
2024-02-19 17:01:31 +00:00
|
|
|
await self.set_state(False)
|
2023-11-30 12:10:49 +00:00
|
|
|
|
|
|
|
def update_from_discover_info(self, info):
|
|
|
|
"""Update state from info from the discover call."""
|
|
|
|
self._discovery_info = info
|
2023-12-29 19:17:15 +00:00
|
|
|
self._info = info
|
2024-01-03 18:04:34 +00:00
|
|
|
|
|
|
|
async def get_emeter_realtime(self) -> EmeterStatus:
|
|
|
|
"""Retrieve current energy readings."""
|
2024-02-19 17:01:31 +00:00
|
|
|
_LOGGER.warning("Deprecated, use `emeter_realtime`.")
|
2024-02-04 15:20:08 +00:00
|
|
|
if not self.has_emeter:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise KasaException("Device has no emeter")
|
2024-02-19 17:01:31 +00:00
|
|
|
return self.emeter_realtime
|
2024-02-04 15:20:08 +00:00
|
|
|
|
2024-01-03 18:04:34 +00:00
|
|
|
@property
|
|
|
|
def emeter_realtime(self) -> EmeterStatus:
|
|
|
|
"""Get the emeter status."""
|
2024-02-19 17:01:31 +00:00
|
|
|
energy = cast(EnergyModule, self.modules["EnergyModule"])
|
|
|
|
return energy.emeter_realtime
|
2024-01-03 18:04:34 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def emeter_this_month(self) -> Optional[float]:
|
|
|
|
"""Get the emeter value for this month."""
|
2024-02-19 17:01:31 +00:00
|
|
|
energy = cast(EnergyModule, self.modules["EnergyModule"])
|
|
|
|
return energy.emeter_this_month
|
2024-01-03 18:04:34 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def emeter_today(self) -> Optional[float]:
|
|
|
|
"""Get the emeter value for today."""
|
2024-02-19 17:01:31 +00:00
|
|
|
energy = cast(EnergyModule, self.modules["EnergyModule"])
|
|
|
|
return energy.emeter_today
|
2024-01-03 21:45:16 +00:00
|
|
|
|
2024-02-04 15:20:08 +00:00
|
|
|
@property
|
|
|
|
def on_since(self) -> Optional[datetime]:
|
|
|
|
"""Return the time that the device was turned on or None if turned off."""
|
|
|
|
if (
|
|
|
|
not self._info.get("device_on")
|
|
|
|
or (on_time := self._info.get("on_time")) is None
|
|
|
|
):
|
|
|
|
return None
|
|
|
|
on_time = cast(float, on_time)
|
2024-02-19 17:01:31 +00:00
|
|
|
if (timemod := self.modules.get("TimeModule")) is not None:
|
|
|
|
timemod = cast(TimeModule, timemod)
|
|
|
|
return timemod.time - timedelta(seconds=on_time)
|
|
|
|
else: # We have no device time, use current local time.
|
|
|
|
return datetime.now().replace(microsecond=0) - timedelta(seconds=on_time)
|
2024-02-04 15:20:08 +00:00
|
|
|
|
2024-01-03 21:45:16 +00:00
|
|
|
async def wifi_scan(self) -> List[WifiNetwork]:
|
|
|
|
"""Scan for available wifi networks."""
|
|
|
|
|
|
|
|
def _net_for_scan_info(res):
|
|
|
|
return WifiNetwork(
|
|
|
|
ssid=base64.b64decode(res["ssid"]).decode(),
|
|
|
|
cipher_type=res["cipher_type"],
|
|
|
|
key_type=res["key_type"],
|
|
|
|
channel=res["channel"],
|
|
|
|
signal_level=res["signal_level"],
|
|
|
|
bssid=res["bssid"],
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _query_networks(networks=None, start_index=0):
|
|
|
|
_LOGGER.debug("Querying networks using start_index=%s", start_index)
|
|
|
|
if networks is None:
|
|
|
|
networks = []
|
|
|
|
|
|
|
|
resp = await self.protocol.query(
|
|
|
|
{"get_wireless_scan_info": {"start_index": start_index}}
|
|
|
|
)
|
|
|
|
network_list = [
|
|
|
|
_net_for_scan_info(net)
|
|
|
|
for net in resp["get_wireless_scan_info"]["ap_list"]
|
|
|
|
]
|
|
|
|
networks.extend(network_list)
|
|
|
|
|
2024-01-10 19:37:43 +00:00
|
|
|
if resp["get_wireless_scan_info"].get("sum", 0) > start_index + 10:
|
2024-01-03 21:45:16 +00:00
|
|
|
return await _query_networks(networks, start_index=start_index + 10)
|
|
|
|
|
|
|
|
return networks
|
|
|
|
|
|
|
|
return await _query_networks()
|
|
|
|
|
|
|
|
async def wifi_join(self, ssid: str, password: str, keytype: str = "wpa2_psk"):
|
|
|
|
"""Join the given wifi network.
|
|
|
|
|
|
|
|
This method returns nothing as the device tries to activate the new
|
|
|
|
settings immediately instead of responding to the request.
|
|
|
|
|
|
|
|
If joining the network fails, the device will return to the previous state
|
|
|
|
after some delay.
|
|
|
|
"""
|
|
|
|
if not self.credentials:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise AuthenticationError("Device requires authentication.")
|
2024-01-03 21:45:16 +00:00
|
|
|
|
|
|
|
payload = {
|
|
|
|
"account": {
|
|
|
|
"username": base64.b64encode(
|
|
|
|
self.credentials.username.encode()
|
|
|
|
).decode(),
|
|
|
|
"password": base64.b64encode(
|
|
|
|
self.credentials.password.encode()
|
|
|
|
).decode(),
|
|
|
|
},
|
|
|
|
"wireless": {
|
|
|
|
"key_type": keytype,
|
|
|
|
"password": base64.b64encode(password.encode()).decode(),
|
|
|
|
"ssid": base64.b64encode(ssid.encode()).decode(),
|
|
|
|
},
|
2024-02-19 17:01:31 +00:00
|
|
|
"time": self.internal_state["get_device_time"],
|
2024-01-03 21:45:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
# The device does not respond to the request but changes the settings
|
|
|
|
# immediately which causes us to timeout.
|
|
|
|
# Thus, We limit retries and suppress the raised exception as useless.
|
|
|
|
try:
|
|
|
|
return await self.protocol.query({"set_qs_info": payload}, retry_count=0)
|
2024-02-21 15:52:55 +00:00
|
|
|
except DeviceError:
|
|
|
|
raise # Re-raise on device-reported errors
|
|
|
|
except KasaException:
|
2024-01-03 21:45:16 +00:00
|
|
|
_LOGGER.debug("Received an expected for wifi join, but this is expected")
|
2024-01-05 01:25:15 +00:00
|
|
|
|
|
|
|
async def update_credentials(self, username: str, password: str):
|
|
|
|
"""Update device credentials.
|
|
|
|
|
|
|
|
This will replace the existing authentication credentials on the device.
|
|
|
|
"""
|
2024-02-19 17:01:31 +00:00
|
|
|
time_data = self.internal_state["get_device_time"]
|
2024-01-05 01:25:15 +00:00
|
|
|
payload = {
|
|
|
|
"account": {
|
|
|
|
"username": base64.b64encode(username.encode()).decode(),
|
|
|
|
"password": base64.b64encode(password.encode()).decode(),
|
|
|
|
},
|
2024-02-19 17:01:31 +00:00
|
|
|
"time": time_data,
|
2024-01-05 01:25:15 +00:00
|
|
|
}
|
|
|
|
return await self.protocol.query({"set_qs_info": payload})
|
2024-01-23 13:26:47 +00:00
|
|
|
|
2024-01-29 10:57:32 +00:00
|
|
|
async def set_alias(self, alias: str):
|
|
|
|
"""Set the device name (alias)."""
|
|
|
|
return await self.protocol.query(
|
|
|
|
{"set_device_info": {"nickname": base64.b64encode(alias.encode()).decode()}}
|
|
|
|
)
|
|
|
|
|
2024-01-23 13:26:47 +00:00
|
|
|
async def reboot(self, delay: int = 1) -> None:
|
|
|
|
"""Reboot the device.
|
|
|
|
|
|
|
|
Note that giving a delay of zero causes this to block,
|
|
|
|
as the device reboots immediately without responding to the call.
|
|
|
|
"""
|
|
|
|
await self.protocol.query({"device_reboot": {"delay": delay}})
|
|
|
|
|
|
|
|
async def factory_reset(self) -> None:
|
|
|
|
"""Reset device back to factory settings.
|
|
|
|
|
|
|
|
Note, this does not downgrade the firmware.
|
|
|
|
"""
|
|
|
|
await self.protocol.query("device_reset")
|
2024-02-22 13:34:55 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def device_type(self) -> DeviceType:
|
|
|
|
"""Return the device type."""
|
|
|
|
if self._device_type is not DeviceType.Unknown:
|
|
|
|
return self._device_type
|
|
|
|
|
|
|
|
if self.children:
|
|
|
|
if "SMART.TAPOHUB" in self.sys_info["type"]:
|
|
|
|
pass # TODO: placeholder for future hub PR
|
|
|
|
else:
|
|
|
|
self._device_type = DeviceType.Strip
|
|
|
|
elif "light_strip" in self._components:
|
|
|
|
self._device_type = DeviceType.LightStrip
|
|
|
|
elif "dimmer_calibration" in self._components:
|
|
|
|
self._device_type = DeviceType.Dimmer
|
|
|
|
elif "brightness" in self._components:
|
|
|
|
self._device_type = DeviceType.Bulb
|
|
|
|
elif "PLUG" in self.sys_info["type"]:
|
|
|
|
self._device_type = DeviceType.Plug
|
|
|
|
else:
|
|
|
|
_LOGGER.warning("Unknown device type, falling back to plug")
|
|
|
|
self._device_type = DeviceType.Plug
|
|
|
|
|
|
|
|
return self._device_type
|