Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Demo platform that has two fake switches."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.core import HomeAssistant
10 from homeassistant.helpers.device_registry import DeviceInfo
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 
13 from . import DOMAIN
14 
15 
17  hass: HomeAssistant,
18  config_entry: ConfigEntry,
19  async_add_entities: AddEntitiesCallback,
20 ) -> None:
21  """Set up the demo switch platform."""
23  [
24  DemoSwitch("switch1", "Decorative Lights", True, True),
25  DemoSwitch(
26  "switch2",
27  "AC",
28  False,
29  False,
30  translation_key="air_conditioner",
31  device_class=SwitchDeviceClass.OUTLET,
32  ),
33  ]
34  )
35 
36 
38  """Representation of a demo switch."""
39 
40  _attr_has_entity_name = True
41  _attr_name = None
42  _attr_should_poll = False
43 
44  def __init__(
45  self,
46  unique_id: str,
47  device_name: str,
48  state: bool,
49  assumed: bool,
50  translation_key: str | None = None,
51  device_class: SwitchDeviceClass | None = None,
52  ) -> None:
53  """Initialize the Demo switch."""
54  self._attr_assumed_state_attr_assumed_state = assumed
55  self._attr_device_class_attr_device_class = device_class
56  self._attr_translation_key_attr_translation_key = translation_key
57  self._attr_is_on_attr_is_on = state
58  self._attr_unique_id_attr_unique_id = unique_id
59  self._attr_device_info_attr_device_info = DeviceInfo(
60  identifiers={(DOMAIN, unique_id)},
61  name=device_name,
62  )
63 
64  def turn_on(self, **kwargs: Any) -> None:
65  """Turn the switch on."""
66  self._attr_is_on_attr_is_on = True
67  self.schedule_update_ha_stateschedule_update_ha_state()
68 
69  def turn_off(self, **kwargs: Any) -> None:
70  """Turn the device off."""
71  self._attr_is_on_attr_is_on = False
72  self.schedule_update_ha_stateschedule_update_ha_state()
None __init__(self, str unique_id, str device_name, bool state, bool assumed, str|None translation_key=None, SwitchDeviceClass|None device_class=None)
Definition: switch.py:52
None schedule_update_ha_state(self, bool force_refresh=False)
Definition: entity.py:1244
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:20