hass-core/homeassistant/components/verisure/switch.py

84 lines
2.5 KiB
Python
Raw Normal View History

"""Support for Verisure Smartplugs."""
from __future__ import annotations
from time import monotonic
from typing import Any, Callable
2015-08-12 13:00:47 +02:00
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import CoordinatorEntity
2015-08-12 13:00:47 +02:00
from .const import CONF_SMARTPLUGS, DOMAIN
from .coordinator import VerisureDataUpdateCoordinator
2015-08-12 13:00:47 +02:00
def setup_platform(
hass: HomeAssistant,
config: dict[str, Any],
add_entities: Callable[[list[CoordinatorEntity]], None],
discovery_info: dict[str, Any] | None = None,
) -> None:
"""Set up the Verisure switch platform."""
coordinator = hass.data[DOMAIN]
2015-08-12 13:00:47 +02:00
if not int(coordinator.config.get(CONF_SMARTPLUGS, 1)):
return
add_entities(
[
VerisureSmartplug(coordinator, serial_number)
for serial_number in coordinator.data["smart_plugs"]
]
)
2015-08-12 13:00:47 +02:00
class VerisureSmartplug(CoordinatorEntity, SwitchEntity):
2016-03-08 13:35:39 +01:00
"""Representation of a Verisure smartplug."""
coordinator: VerisureDataUpdateCoordinator
def __init__(
self, coordinator: VerisureDataUpdateCoordinator, serial_number: str
) -> None:
2016-03-08 13:35:39 +01:00
"""Initialize the Verisure device."""
super().__init__(coordinator)
self.serial_number = serial_number
self._change_timestamp = 0
self._state = False
2015-08-12 13:00:47 +02:00
@property
def name(self) -> str:
2016-03-08 13:35:39 +01:00
"""Return the name or location of the smartplug."""
return self.coordinator.data["smart_plugs"][self.serial_number]["area"]
2015-08-12 13:00:47 +02:00
@property
def is_on(self) -> bool:
2016-03-08 13:35:39 +01:00
"""Return true if on."""
if monotonic() - self._change_timestamp < 10:
return self._state
2019-07-31 12:25:30 -07:00
self._state = (
self.coordinator.data["smart_plugs"][self.serial_number]["currentState"]
2019-07-31 12:25:30 -07:00
== "ON"
)
return self._state
2015-08-12 13:00:47 +02:00
@property
def available(self) -> bool:
"""Return True if entity is available."""
2019-07-31 12:25:30 -07:00
return (
super().available
and self.serial_number in self.coordinator.data["smart_plugs"]
2019-07-31 12:25:30 -07:00
)
def turn_on(self, **kwargs) -> None:
2016-03-08 13:35:39 +01:00
"""Set smartplug status on."""
self.coordinator.verisure.set_smartplug_state(self.serial_number, True)
self._state = True
self._change_timestamp = monotonic()
2015-08-12 13:00:47 +02:00
def turn_off(self, **kwargs) -> None:
2016-03-08 13:35:39 +01:00
"""Set smartplug status off."""
self.coordinator.verisure.set_smartplug_state(self.serial_number, False)
self._state = False
self._change_timestamp = monotonic()