Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for TPLink switch entities."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 import logging
7 from typing import Any, cast
8 
9 from kasa import Feature
10 
11 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from . import TPLinkConfigEntry
16 from .entity import (
17  CoordinatedTPLinkFeatureEntity,
18  TPLinkFeatureEntityDescription,
19  async_refresh_after,
20 )
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 
25 @dataclass(frozen=True, kw_only=True)
27  SwitchEntityDescription, TPLinkFeatureEntityDescription
28 ):
29  """Base class for a TPLink feature based sensor entity description."""
30 
31 
32 SWITCH_DESCRIPTIONS: tuple[TPLinkSwitchEntityDescription, ...] = (
34  key="state",
35  ),
37  key="led",
38  ),
40  key="auto_update_enabled",
41  ),
43  key="auto_off_enabled",
44  ),
46  key="smooth_transitions",
47  ),
49  key="fan_sleep_mode",
50  ),
52  key="child_lock",
53  ),
55  key="pir_enabled",
56  ),
57 )
58 
59 SWITCH_DESCRIPTIONS_MAP = {desc.key: desc for desc in SWITCH_DESCRIPTIONS}
60 
61 
63  hass: HomeAssistant,
64  config_entry: TPLinkConfigEntry,
65  async_add_entities: AddEntitiesCallback,
66 ) -> None:
67  """Set up switches."""
68  data = config_entry.runtime_data
69  parent_coordinator = data.parent_coordinator
70  device = parent_coordinator.device
71 
72  entities = CoordinatedTPLinkFeatureEntity.entities_for_device_and_its_children(
73  hass=hass,
74  device=device,
75  coordinator=parent_coordinator,
76  feature_type=Feature.Switch,
77  entity_class=TPLinkSwitch,
78  descriptions=SWITCH_DESCRIPTIONS_MAP,
79  )
80 
81  async_add_entities(entities)
82 
83 
85  """Representation of a feature-based TPLink switch."""
86 
87  entity_description: TPLinkSwitchEntityDescription
88 
89  @async_refresh_after
90  async def async_turn_on(self, **kwargs: Any) -> None:
91  """Turn the switch on."""
92  await self._feature_feature.set_value(True)
93 
94  @async_refresh_after
95  async def async_turn_off(self, **kwargs: Any) -> None:
96  """Turn the switch off."""
97  await self._feature_feature.set_value(False)
98 
99  @callback
100  def _async_update_attrs(self) -> None:
101  """Update the entity's attributes."""
102  self._attr_is_on_attr_is_on = cast(bool | None, self._feature_feature.value)
None async_turn_off(self, **Any kwargs)
Definition: entity.py:1709