Skip to content

Commit

Permalink
added more tests and diagnostic feature
Browse files Browse the repository at this point in the history
  • Loading branch information
petretiandrea committed Apr 6, 2024
1 parent 0b3a7fa commit 13b66e2
Show file tree
Hide file tree
Showing 36 changed files with 669 additions and 1,864 deletions.
1 change: 0 additions & 1 deletion custom_components/tapo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
except DeviceNotSupported as error:
raise error
except Exception as error:
print(error)
raise ConfigEntryNotReady from error


Expand Down
33 changes: 20 additions & 13 deletions custom_components/tapo/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async def async_step_dhcp(
) -> data_entry_flow.FlowResult:
"""Handle discovery via dhcp."""
mac_address = dr.format_mac(discovery_info.macaddress)
if discovered_device := await discover_tapo_device(self.hass, mac_address):
if discovered_device := await discover_tapo_device(discovery_info.ip):
return await self._async_handle_discovery(
discovery_info.ip, mac_address, discovered_device
)
Expand All @@ -140,7 +140,7 @@ async def async_step_user(

if user_input is not None:
try:
device = await self._async_get_device_info(user_input)
device = await self._async_get_device(user_input)
await self.async_set_unique_id(dr.format_mac(device.mac))
self._abort_if_unique_id_configured()
self._async_abort_entries_match({CONF_HOST: device.host})
Expand Down Expand Up @@ -228,7 +228,7 @@ async def async_step_discovery_auth_confirm(

if user_input:
try:
device = await self._async_get_device_info_from_discovered(
device = await self._async_get_device_from_discovered(
self._discovered_info, user_input
)
await self.async_set_unique_id(dr.format_mac(device.mac))
Expand Down Expand Up @@ -288,24 +288,31 @@ async def _async_create_config_entry_from_device_info(
},
)

async def _async_get_device_info_from_discovered(
async def _async_get_device_from_discovered(
self, discovered: DiscoveredDevice, config: dict[str, Any]
) -> TapoDevice:
return await self._async_get_device_info(config | {CONF_HOST: discovered.ip})
return await self._async_get_device(config | {CONF_HOST: discovered.ip}, discovered)

async def _async_get_device_info(self, config: dict[str, Any]) -> TapoDevice:
async def _async_get_device(
self,
config: dict[str, Any],
discovered_device: DiscoveredDevice | None = None,
) -> TapoDevice:
if not config[CONF_HOST]:
raise InvalidHost
try:
session = create_aiohttp_session(self.hass)
credential = AuthCredential(config[CONF_USERNAME], config[CONF_PASSWORD])
host, port = get_host_port(config[CONF_HOST])
config = DeviceConnectConfiguration(
credentials=credential,
host=host,
port=port,
)
device = await connect(config=config, session=session)
if discovered_device is None:
host, port = get_host_port(config[CONF_HOST])
config = DeviceConnectConfiguration(
credentials=credential,
host=host,
port=port,
)
device = await connect(config=config, session=session)
else:
device = await discovered_device.get_tapo_device(credential, session)
await device.update()
return device
except TapoException as error:
Expand Down
13 changes: 1 addition & 12 deletions custom_components/tapo/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,4 @@
If you have any issues with this you need to open an issue here:
{ISSUE_URL}
-------------------------------------------------------------------
"""

#TapoDevice = Union[LightDevice, PlugDevice, LedStripDevice, HubDevice, PowerStripDevice]


class Component(Enum):
COLOR_TEMPERATURE = "color_temperature"
BRIGHTNESS = "brightness"
COLOR = "color"
LIGHT_STRIP = "light_strip"
LIGHT_STRIP_EFFECTS = "light_strip_lighting_effect"
ALARM = "alarm"
"""
27 changes: 27 additions & 0 deletions custom_components/tapo/diagnostics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Any, cast

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import format_mac

from . import HassTapoDeviceData
from .const import DOMAIN


async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
data = cast(HassTapoDeviceData, hass.data[DOMAIN][entry.entry_id])
oui = format_mac(data.coordinator.device.mac)[:8].upper()
children_diagnostics = []
if len(data.child_coordinators) > 0:
children_diagnostics = [
{ 'nickname': child.device.nickname, 'raw_state': child.device.raw_state }
for child in data.child_coordinators
]
return {
'oui': oui,
'protocol_name': data.coordinator.device.protocol_version,
'raw_state': data.coordinator.device.raw_state,
'children': children_diagnostics
}
12 changes: 7 additions & 5 deletions custom_components/tapo/discovery.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import logging
from itertools import chain
from typing import Optional

Expand All @@ -25,9 +26,10 @@ async def discovery_tapo_devices(hass: HomeAssistant) -> dict[str, DiscoveredDev


async def discover_tapo_device(
hass: HomeAssistant, mac: str
ip: str,
) -> Optional[DiscoveredDevice]:
found_devices = await discovery_tapo_devices(hass)
return next(
filter(lambda x: dr.format_mac(x.mac) == mac, found_devices.values()), None
)
try:
return await TapoDiscovery.single_scan(ip, DISCOVERY_TIMEOUT)
except:
logging.error("Faild during discovery of device with ip {}", ip)
return None
1 change: 1 addition & 0 deletions custom_components/tapo/hass_tapo.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ async def _initialize_device(
child_coordinators=[],
device=device,
)

await hass.config_entries.async_forward_entry_setups(self.entry, PLATFORMS)
return True

Expand Down
1 change: 0 additions & 1 deletion custom_components/tapo/hub/hass_tapo_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ async def initialize_hub(self, hass: HomeAssistant):
child_coordinators = await self.setup_children(
hass, registry, self.hub.children, polling_rate
)
print("Coordinators", child_coordinators)
hass.data[DOMAIN][self.entry.entry_id] = HassTapoDeviceData(
coordinator=hub_coordinator,
config_entry_update_unsub=self.entry.add_update_listener(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/tapo/hub/siren.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async def async_setup_entry(
):
data = cast(HassTapoDeviceData, hass.data[DOMAIN][entry.entry_id])
if isinstance(data.device, TapoHub):
if data.coordinator.device.has_component(AlarmComponent):
if data.coordinator.device.has_alarm:
available_tones = (
(await data.device.get_supported_alarm_tones())
.get_or_raise()
Expand Down
9 changes: 3 additions & 6 deletions custom_components/tapo/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
color_temperature_kelvin_to_mired as kelvin_to_mired,
)
from plugp100.api.light_effect_preset import LightEffectPreset
from plugp100.new.components.light_component import LightComponent
from plugp100.new.components.light_effect_component import LightEffectComponent
from plugp100.new.tapobulb import TapoBulb

from custom_components.tapo.const import Component
from custom_components.tapo.const import DOMAIN
from custom_components.tapo.coordinators import HassTapoDeviceData, TapoDataCoordinator
from custom_components.tapo.entity import CoordinatedTapoEntity
Expand Down Expand Up @@ -194,14 +192,13 @@ async def _change_brightness(self, new_brightness, apply_to_effect: str = None):
).get_or_raise()


# TODO: split to more componenets on TapoBulb library
def _components_to_color_modes(device: TapoBulb) -> set[ColorMode]:
color_modes = [ColorMode.ONOFF]
if device.has_component(LightComponent) and device.components.has(Component.COLOR_TEMPERATURE.value):
if device.is_color_temperature:
color_modes.append(ColorMode.COLOR_TEMP)
if device.has_component(LightComponent) and device.components.has(Component.BRIGHTNESS.value):
if device.is_brightness:
color_modes.append(ColorMode.BRIGHTNESS)
if device.has_component(LightComponent) and device.components.has(Component.COLOR.value):
if device.is_color:
color_modes.append(ColorMode.HS)
return set(color_modes)

Expand Down
2 changes: 1 addition & 1 deletion custom_components/tapo/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"iot_class": "local_polling",
"documentation": "https://github.com/petretiandrea/home-assistant-tapo-p100",
"issue_tracker": "https://github.com/petretiandrea/home-assistant-tapo-p100/issues",
"requirements": ["plugp100==5.0.0.dev2"],
"requirements": ["plugp100==5.0.0.dev4"],
"dependencies": ["network"],
"dhcp": [
{
Expand Down
2 changes: 1 addition & 1 deletion custom_components/tapo/sensors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,4 @@ def get_config(self) -> SensorConfig:
def get_value(self, coordinator: TapoDataCoordinator) -> StateType:
if energy := coordinator.device.get_component(EnergyComponent):
return energy.energy_info.month_runtime if energy.energy_info else None
return None
return None
2 changes: 1 addition & 1 deletion custom_components/tapo/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async def async_setup_device_switch(

class TapoPlugEntity(CoordinatedTapoEntity, SwitchEntity):
_attr_device_class = SwitchDeviceClass.OUTLET
_attr_has_entity_name = True
_attr_has_entity_name = False

def __init__(
self,
Expand Down
2 changes: 1 addition & 1 deletion requirements_dev.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
homeassistant==2024.2.0
plugp100==5.0.0.dev2
plugp100==5.0.0.dev4
pre-commit==3.3.3
reorder-python-imports==3.10.0
flake8==6.1.0
Expand Down
Loading

0 comments on commit 13b66e2

Please sign in to comment.