core/homeassistant/components/dlink/switch.py

80 lines
2.3 KiB
Python
Raw Normal View History

2023-01-11 00:10:56 +00:00
"""Support for D-Link Power Plug Switches."""
from __future__ import annotations
2018-10-26 13:45:57 +00:00
from datetime import timedelta
2022-08-19 14:10:45 +00:00
from typing import Any
2023-05-06 22:01:58 +00:00
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
2018-10-26 13:45:57 +00:00
2023-05-06 22:01:58 +00:00
from .const import ATTR_TOTAL_CONSUMPTION, DOMAIN
2023-01-11 00:10:56 +00:00
from .entity import DLinkEntity
2018-10-26 13:45:57 +00:00
SCAN_INTERVAL = timedelta(minutes=2)
2016-08-20 22:25:11 +00:00
SWITCH_TYPE = SwitchEntityDescription(
key="switch",
)
2023-01-11 00:10:56 +00:00
2023-01-11 00:10:56 +00:00
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the D-Link Power Plug switch."""
async_add_entities(
[SmartPlugSwitch(entry, hass.data[DOMAIN][entry.entry_id], SWITCH_TYPE)],
2023-01-11 00:10:56 +00:00
True,
)
class SmartPlugSwitch(DLinkEntity, SwitchEntity):
2018-10-26 13:45:57 +00:00
"""Representation of a D-Link Smart Plug switch."""
2016-03-08 12:35:39 +00:00
2023-07-18 16:51:02 +00:00
_attr_name = None
@property
2023-01-11 00:10:56 +00:00
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes of the device."""
try:
temperature = self.hass.config.units.temperature(
int(self.data.temperature), UnitOfTemperature.CELSIUS
)
except ValueError:
temperature = None
try:
total_consumption = float(self.data.total_consumption)
except ValueError:
total_consumption = None
return {
ATTR_TOTAL_CONSUMPTION: total_consumption,
ATTR_TEMPERATURE: temperature,
}
@property
2023-01-11 00:10:56 +00:00
def is_on(self) -> bool:
2016-03-08 12:35:39 +00:00
"""Return true if switch is on."""
2019-07-31 19:25:30 +00:00
return self.data.state == "ON"
2022-08-19 14:10:45 +00:00
def turn_on(self, **kwargs: Any) -> None:
2016-03-08 12:35:39 +00:00
"""Turn the switch on."""
2019-07-31 19:25:30 +00:00
self.data.smartplug.state = "ON"
2022-08-19 14:10:45 +00:00
def turn_off(self, **kwargs: Any) -> None:
2016-03-08 12:35:39 +00:00
"""Turn the switch off."""
2019-07-31 19:25:30 +00:00
self.data.smartplug.state = "OFF"
2016-11-17 02:55:58 +00:00
2022-08-19 14:10:45 +00:00
def update(self) -> None:
2016-11-17 02:55:58 +00:00
"""Get the latest data from the smart plug and updates the states."""
self.data.update()
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self.data.available