core/homeassistant/components/homematicip_cloud/switch.py

187 lines
6.4 KiB
Python
Raw Normal View History

"""Support for HomematicIP Cloud switches."""
import logging
from typing import Any, Dict
from homematicip.aio.device import (
2019-07-31 19:25:30 +00:00
AsyncBrandSwitchMeasuring,
AsyncFullFlushInputSwitch,
2019-07-31 19:25:30 +00:00
AsyncFullFlushSwitchMeasuring,
AsyncHeatingSwitch2,
2019-07-31 19:25:30 +00:00
AsyncMultiIOBox,
AsyncOpenCollector8Module,
AsyncPlugableSwitch,
AsyncPlugableSwitchMeasuring,
AsyncPrintedCircuitBoardSwitch2,
AsyncPrintedCircuitBoardSwitchBattery,
)
from homematicip.aio.group import AsyncExtendedLinkedSwitchingGroup, AsyncSwitchingGroup
from homeassistant.components.switch import SwitchEntity
2019-04-25 22:13:07 +00:00
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericDevice
from .device import ATTR_GROUP_MEMBER_UNREACHABLE
from .hap import HomematicipHAP
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
async def async_setup_entry(
hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities
2019-07-31 19:25:30 +00:00
) -> None:
Add HomematicIP Cloud Config Flow and Entries loading (#14861) * Add HomematicIP Cloud to config flow * Inititial trial for config_flow * Integrations text files * Load and write config_flow and init homematicip_cloud * Split into dedicated files * Ceanup of text messages * Working config_flow * Move imports inside a function * Enable laoding even no accesspoints are defined * Revert unnecassary changes in CONFIG_SCHEMA * Better error handling * fix flask8 * Migration to async for token generation * A few fixes * Simplify config_flow * Bump version to 9.6 with renamed package * Requirements file * First fixes after review * Implement async_step_import * Cleanup for Config Flow * First tests for homematicip_cloud setup * Remove config_flow tests * Really remove all things * Fix comment * Update picture * Add support for async_setup_entry to switch and climate platform * Update path of the config_flow picture * Refactoring for better tesability * Further tests implemented * Move 3th party lib inside function * Fix lint * Update requirments_test_all.txt file * UPdate of requirments_test_all.txt did not work * Furder cleanup in websocket connection * Remove a test for the hap * Revert "Remove a test for the hap" This reverts commit 968d58cba108e0f371022c7ab540374aa2ab13f4. * First tests implemented for config_flow * Fix lint * Rework of client registration process * Implemented tests for config_flow 100% coverage * Cleanup * Cleanup comments and code * Try to fix import problem * Add homematicip to the test env requirements
2018-07-06 21:05:34 +00:00
"""Set up the HomematicIP switch from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id]
entities = []
for device in hap.home.devices:
if isinstance(device, AsyncBrandSwitchMeasuring):
# BrandSwitchMeasuring inherits PlugableSwitchMeasuring
# This device is implemented in the light platform and will
# not be added in the switch platform
pass
2019-07-31 19:25:30 +00:00
elif isinstance(
device, (AsyncPlugableSwitchMeasuring, AsyncFullFlushSwitchMeasuring)
):
entities.append(HomematicipSwitchMeasuring(hap, device))
2019-07-31 19:25:30 +00:00
elif isinstance(
device,
(
AsyncPlugableSwitch,
AsyncPrintedCircuitBoardSwitchBattery,
AsyncFullFlushInputSwitch,
),
2019-07-31 19:25:30 +00:00
):
entities.append(HomematicipSwitch(hap, device))
elif isinstance(device, AsyncOpenCollector8Module):
for channel in range(1, 9):
entities.append(HomematicipMultiSwitch(hap, device, channel))
elif isinstance(device, AsyncHeatingSwitch2):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel))
elif isinstance(device, AsyncMultiIOBox):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel))
elif isinstance(device, AsyncPrintedCircuitBoardSwitch2):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel))
for group in hap.home.groups:
if isinstance(group, (AsyncExtendedLinkedSwitchingGroup, AsyncSwitchingGroup)):
entities.append(HomematicipGroupSwitch(hap, group))
if entities:
async_add_entities(entities)
class HomematicipSwitch(HomematicipGenericDevice, SwitchEntity):
2018-08-21 19:25:16 +00:00
"""representation of a HomematicIP Cloud switch device."""
def __init__(self, hap: HomematicipHAP, device) -> None:
"""Initialize the switch device."""
super().__init__(hap, device)
@property
2019-04-25 22:13:07 +00:00
def is_on(self) -> bool:
"""Return true if device is on."""
return self._device.on
async def async_turn_on(self, **kwargs) -> None:
"""Turn the device on."""
await self._device.turn_on()
async def async_turn_off(self, **kwargs) -> None:
"""Turn the device off."""
await self._device.turn_off()
class HomematicipGroupSwitch(HomematicipGenericDevice, SwitchEntity):
"""representation of a HomematicIP switching group."""
def __init__(self, hap: HomematicipHAP, device, post: str = "Group") -> None:
"""Initialize switching group."""
device.modelType = f"HmIP-{post}"
super().__init__(hap, device, post)
@property
2019-04-25 22:13:07 +00:00
def is_on(self) -> bool:
"""Return true if group is on."""
return self._device.on
@property
2019-04-25 22:13:07 +00:00
def available(self) -> bool:
"""Switch-Group available."""
# A switch-group must be available, and should not be affected by the
# individual availability of group members.
# This allows switching even when individual group members
# are not available.
return True
@property
def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes of the switch-group."""
state_attr = super().device_state_attributes
if self._device.unreach:
state_attr[ATTR_GROUP_MEMBER_UNREACHABLE] = True
return state_attr
async def async_turn_on(self, **kwargs) -> None:
"""Turn the group on."""
await self._device.turn_on()
async def async_turn_off(self, **kwargs) -> None:
"""Turn the group off."""
await self._device.turn_off()
class HomematicipSwitchMeasuring(HomematicipSwitch):
2018-08-21 19:25:16 +00:00
"""Representation of a HomematicIP measuring switch device."""
@property
2019-04-25 22:13:07 +00:00
def current_power_w(self) -> float:
"""Return the current power usage in W."""
return self._device.currentPowerConsumption
@property
2019-04-25 22:13:07 +00:00
def today_energy_kwh(self) -> int:
"""Return the today total energy usage in kWh."""
if self._device.energyCounter is None:
return 0
return round(self._device.energyCounter)
class HomematicipMultiSwitch(HomematicipGenericDevice, SwitchEntity):
"""Representation of a HomematicIP Cloud multi switch device."""
def __init__(self, hap: HomematicipHAP, device, channel: int) -> None:
"""Initialize the multi switch device."""
self.channel = channel
super().__init__(hap, device, f"Channel{channel}")
@property
def name(self) -> str:
"""Return the name of the multi switch channel."""
label = self._get_label_by_channel(self.channel)
if label:
return label
return super().name
@property
2019-04-25 22:13:07 +00:00
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self.__class__.__name__}_{self.post}_{self._device.id}"
@property
2019-04-25 22:13:07 +00:00
def is_on(self) -> bool:
"""Return true if device is on."""
return self._device.functionalChannels[self.channel].on
async def async_turn_on(self, **kwargs) -> None:
"""Turn the device on."""
await self._device.turn_on(self.channel)
async def async_turn_off(self, **kwargs) -> None:
"""Turn the device off."""
await self._device.turn_off(self.channel)