Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Switch platform for Ecoforest."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Awaitable, Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
9 from pyecoforest.api import EcoforestApi
10 from pyecoforest.models.device import Device
11 
12 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers.entity_platform import AddEntitiesCallback
16 
17 from .const import DOMAIN
18 from .coordinator import EcoforestCoordinator
19 from .entity import EcoforestEntity
20 
21 
22 @dataclass(frozen=True, kw_only=True)
24  """Describes an Ecoforest switch entity."""
25 
26  value_fn: Callable[[Device], bool]
27  switch_fn: Callable[[EcoforestApi, bool], Awaitable[Device]]
28 
29 
30 SWITCH_TYPES: tuple[EcoforestSwitchEntityDescription, ...] = (
32  key="status",
33  name=None,
34  value_fn=lambda data: data.on,
35  switch_fn=lambda api, status: api.turn(status),
36  ),
37 )
38 
39 
41  hass: HomeAssistant,
42  config_entry: ConfigEntry,
43  async_add_entities: AddEntitiesCallback,
44 ) -> None:
45  """Set up Ecoforest switch platform."""
46  coordinator: EcoforestCoordinator = hass.data[DOMAIN][config_entry.entry_id]
47 
48  entities = [
49  EcoforestSwitchEntity(coordinator, description) for description in SWITCH_TYPES
50  ]
51 
52  async_add_entities(entities)
53 
54 
56  """Representation of an Ecoforest switch entity."""
57 
58  entity_description: EcoforestSwitchEntityDescription
59 
60  @property
61  def is_on(self) -> bool:
62  """Return the state of the ecoforest device."""
63  return self.entity_descriptionentity_description.value_fn(self.datadatadata)
64 
65  async def async_turn_on(self, **kwargs: Any) -> None:
66  """Turn on the ecoforest device."""
67  await self.entity_descriptionentity_description.switch_fn(self.coordinator.api, True)
68  await self.coordinator.async_request_refresh()
69 
70  async def async_turn_off(self, **kwargs: Any) -> None:
71  """Turn off the ecoforest device."""
72  await self.entity_descriptionentity_description.switch_fn(self.coordinator.api, False)
73  await self.coordinator.async_request_refresh()
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:44