Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for Switchbot bot."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 import switchbot
8 
9 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
10 from homeassistant.const import STATE_ON
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 from homeassistant.helpers.restore_state import RestoreEntity
14 
15 from .coordinator import SwitchbotConfigEntry, SwitchbotDataUpdateCoordinator
16 from .entity import SwitchbotSwitchedEntity
17 
18 PARALLEL_UPDATES = 0
19 
20 
22  hass: HomeAssistant,
23  entry: SwitchbotConfigEntry,
24  async_add_entities: AddEntitiesCallback,
25 ) -> None:
26  """Set up Switchbot based on a config entry."""
27  async_add_entities([SwitchBotSwitch(entry.runtime_data)])
28 
29 
31  """Representation of a Switchbot switch."""
32 
33  _attr_device_class = SwitchDeviceClass.SWITCH
34  _attr_translation_key = "bot"
35  _attr_name = None
36  _device: switchbot.Switchbot
37 
38  def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None:
39  """Initialize the Switchbot."""
40  super().__init__(coordinator)
41  self._attr_is_on_attr_is_on_attr_is_on = False
42 
43  async def async_added_to_hass(self) -> None:
44  """Run when entity about to be added."""
45  await super().async_added_to_hass()
46  if not (last_state := await self.async_get_last_stateasync_get_last_state()):
47  return
48  self._attr_is_on_attr_is_on_attr_is_on = last_state.state == STATE_ON
49  self._last_run_success_last_run_success_last_run_success = last_state.attributes.get("last_run_success")
50 
51  @property
52  def assumed_state(self) -> bool:
53  """Return true if unable to access real state of entity."""
54  return not self._device_device.switch_mode()
55 
56  @property
57  def is_on(self) -> bool | None:
58  """Return true if device is on."""
59  if not self._device_device.switch_mode():
60  return self._attr_is_on_attr_is_on_attr_is_on
61  return self._device_device.is_on()
62 
63  @property
64  def extra_state_attributes(self) -> dict[str, Any]:
65  """Return the state attributes."""
66  return {
67  **super().extra_state_attributes,
68  "switch_mode": self._device_device.switch_mode(),
69  }
None __init__(self, SwitchbotDataUpdateCoordinator coordinator)
Definition: switch.py:38
None async_setup_entry(HomeAssistant hass, SwitchbotConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:25