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

92 lines
2.7 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.entity import Entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
2015-08-12 13:00:47 +02:00
from . import VerisureDataUpdateCoordinator
from .const import CONF_SMARTPLUGS, DOMAIN
2015-08-12 13:00:47 +02:00
def setup_platform(
hass: HomeAssistant,
config: dict[str, Any],
add_entities: Callable[[list[Entity], bool], 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, device_label)
for device_label in coordinator.get("$.smartPlugs[*].deviceLabel")
]
)
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, device_id: str
) -> None:
2016-03-08 13:35:39 +01:00
"""Initialize the Verisure device."""
super().__init__(coordinator)
self._device_label = device_id
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.get_first(
2019-07-31 12:25:30 -07:00
"$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label
)
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.get_first(
2019-07-31 12:25:30 -07:00
"$.smartPlugs[?(@.deviceLabel == '%s')].currentState",
self._device_label,
)
== "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 (
self.coordinator.get_first(
"$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label
)
2019-07-31 12:25:30 -07:00
is not None
)
def turn_on(self, **kwargs) -> None:
2016-03-08 13:35:39 +01:00
"""Set smartplug status on."""
self.coordinator.session.set_smartplug_state(self._device_label, 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.session.set_smartplug_state(self._device_label, False)
self._state = False
self._change_timestamp = monotonic()