Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for Litter-Robot switches."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from dataclasses import dataclass
7 from typing import Any, Generic
8 
9 from pylitterbot import FeederRobot, LitterRobot
10 
11 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
12 from homeassistant.const import EntityCategory
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from . import LitterRobotConfigEntry
17 from .entity import LitterRobotEntity, _RobotT
18 
19 
20 @dataclass(frozen=True)
21 class RequiredKeysMixin(Generic[_RobotT]):
22  """A class that describes robot switch entity required keys."""
23 
24  set_fn: Callable[[_RobotT, bool], Coroutine[Any, Any, bool]]
25 
26 
27 @dataclass(frozen=True)
29  """A class that describes robot switch entities."""
30 
31  entity_category: EntityCategory = EntityCategory.CONFIG
32 
33 
34 ROBOT_SWITCHES = [
35  RobotSwitchEntityDescription[LitterRobot | FeederRobot](
36  key="night_light_mode_enabled",
37  translation_key="night_light_mode",
38  set_fn=lambda robot, value: robot.set_night_light(value),
39  ),
40  RobotSwitchEntityDescription[LitterRobot | FeederRobot](
41  key="panel_lock_enabled",
42  translation_key="panel_lockout",
43  set_fn=lambda robot, value: robot.set_panel_lockout(value),
44  ),
45 ]
46 
47 
48 class RobotSwitchEntity(LitterRobotEntity[_RobotT], SwitchEntity):
49  """Litter-Robot switch entity."""
50 
51  entity_description: RobotSwitchEntityDescription[_RobotT]
52 
53  @property
54  def is_on(self) -> bool | None:
55  """Return true if switch is on."""
56  return bool(getattr(self.robotrobot, self.entity_descriptionentity_description.key))
57 
58  async def async_turn_on(self, **kwargs: Any) -> None:
59  """Turn the switch on."""
60  await self.entity_descriptionentity_description.set_fn(self.robotrobot, True)
61 
62  async def async_turn_off(self, **kwargs: Any) -> None:
63  """Turn the switch off."""
64  await self.entity_descriptionentity_description.set_fn(self.robotrobot, False)
65 
66 
68  hass: HomeAssistant,
69  entry: LitterRobotConfigEntry,
70  async_add_entities: AddEntitiesCallback,
71 ) -> None:
72  """Set up Litter-Robot switches using config entry."""
73  hub = entry.runtime_data
74  entities = [
75  RobotSwitchEntity(robot=robot, hub=hub, description=description)
76  for description in ROBOT_SWITCHES
77  for robot in hub.account.robots
78  if isinstance(robot, (LitterRobot, FeederRobot))
79  ]
80  async_add_entities(entities)
None async_setup_entry(HomeAssistant hass, LitterRobotConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:71