Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for D-Link Power Plug Switches."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 from typing import Any
7 
8 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
9 from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 
13 from . import DLinkConfigEntry
14 from .const import ATTR_TOTAL_CONSUMPTION
15 from .entity import DLinkEntity
16 
17 SCAN_INTERVAL = timedelta(minutes=2)
18 
20  key="switch",
21 )
22 
23 
25  hass: HomeAssistant,
26  entry: DLinkConfigEntry,
27  async_add_entities: AddEntitiesCallback,
28 ) -> None:
29  """Set up the D-Link Power Plug switch."""
30  async_add_entities([SmartPlugSwitch(entry, SWITCH_TYPE)], True)
31 
32 
34  """Representation of a D-Link Smart Plug switch."""
35 
36  _attr_name = None
37 
38  @property
39  def extra_state_attributes(self) -> dict[str, Any]:
40  """Return the state attributes of the device."""
41  try:
42  temperature = self.hasshass.config.units.temperature(
43  int(self.datadata.temperature), UnitOfTemperature.CELSIUS
44  )
45  except ValueError:
46  temperature = None
47 
48  try:
49  total_consumption = float(self.datadata.total_consumption)
50  except ValueError:
51  total_consumption = None
52 
53  return {
54  ATTR_TOTAL_CONSUMPTION: total_consumption,
55  ATTR_TEMPERATURE: temperature,
56  }
57 
58  @property
59  def is_on(self) -> bool:
60  """Return true if switch is on."""
61  return self.datadata.state == "ON"
62 
63  def turn_on(self, **kwargs: Any) -> None:
64  """Turn the switch on."""
65  self.datadata.smartplug.state = "ON"
66 
67  def turn_off(self, **kwargs: Any) -> None:
68  """Turn the switch off."""
69  self.datadata.smartplug.state = "OFF"
70 
71  def update(self) -> None:
72  """Get the latest data from the smart plug and updates the states."""
73  self.datadata.update()
74 
75  @property
76  def available(self) -> bool:
77  """Return True if entity is available."""
78  return self.datadata.available