2020-08-24 10:43:31 +00:00
|
|
|
"""Switch for Shelly."""
|
2020-08-28 15:33:34 +00:00
|
|
|
from aioshelly import RelayBlock
|
|
|
|
|
2020-08-24 10:43:31 +00:00
|
|
|
from homeassistant.components.switch import SwitchEntity
|
|
|
|
from homeassistant.core import callback
|
|
|
|
|
2020-09-07 12:13:20 +00:00
|
|
|
from . import ShellyDeviceWrapper
|
2020-08-24 10:43:31 +00:00
|
|
|
from .const import DOMAIN
|
2020-09-07 12:13:20 +00:00
|
|
|
from .entity import ShellyBlockEntity
|
2020-08-24 10:43:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def async_setup_entry(hass, config_entry, async_add_entities):
|
|
|
|
"""Set up switches for device."""
|
|
|
|
wrapper = hass.data[DOMAIN][config_entry.entry_id]
|
|
|
|
|
2020-08-28 15:33:34 +00:00
|
|
|
relay_blocks = [block for block in wrapper.device.blocks if block.type == "relay"]
|
|
|
|
|
|
|
|
if not relay_blocks:
|
2020-08-24 10:43:31 +00:00
|
|
|
return
|
|
|
|
|
2020-09-06 14:05:10 +00:00
|
|
|
async_add_entities(RelaySwitch(wrapper, block) for block in relay_blocks)
|
2020-08-24 10:43:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RelaySwitch(ShellyBlockEntity, SwitchEntity):
|
|
|
|
"""Switch that controls a relay block on Shelly devices."""
|
|
|
|
|
2020-09-06 14:05:10 +00:00
|
|
|
def __init__(self, wrapper: ShellyDeviceWrapper, block: RelayBlock) -> None:
|
2020-08-24 10:43:31 +00:00
|
|
|
"""Initialize relay switch."""
|
2020-08-28 15:33:34 +00:00
|
|
|
super().__init__(wrapper, block)
|
2020-08-24 10:43:31 +00:00
|
|
|
self.control_result = None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_on(self) -> bool:
|
|
|
|
"""If switch is on."""
|
|
|
|
if self.control_result:
|
|
|
|
return self.control_result["ison"]
|
|
|
|
|
|
|
|
return self.block.output
|
|
|
|
|
|
|
|
async def async_turn_on(self, **kwargs):
|
|
|
|
"""Turn on relay."""
|
2020-08-28 15:33:34 +00:00
|
|
|
self.control_result = await self.block.set_state(turn="on")
|
2020-08-24 10:43:31 +00:00
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
|
|
async def async_turn_off(self, **kwargs):
|
|
|
|
"""Turn off relay."""
|
2020-08-28 15:33:34 +00:00
|
|
|
self.control_result = await self.block.set_state(turn="off")
|
2020-08-24 10:43:31 +00:00
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def _update_callback(self):
|
|
|
|
"""When device updates, clear control result that overrides state."""
|
|
|
|
self.control_result = None
|
|
|
|
super()._update_callback()
|