Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Component provides support for the Foscam Switch."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import SwitchEntity
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.core import HomeAssistant, callback
10 from homeassistant.exceptions import HomeAssistantError
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 
13 from . import FoscamCoordinator
14 from .const import DOMAIN, LOGGER
15 from .entity import FoscamEntity
16 
17 
19  hass: HomeAssistant,
20  config_entry: ConfigEntry,
21  async_add_entities: AddEntitiesCallback,
22 ) -> None:
23  """Set up foscam switch from a config entry."""
24 
25  coordinator: FoscamCoordinator = hass.data[DOMAIN][config_entry.entry_id]
26 
27  await coordinator.async_config_entry_first_refresh()
28 
29  if coordinator.data["is_asleep"]["supported"]:
30  async_add_entities([FoscamSleepSwitch(coordinator, config_entry)])
31 
32 
34  """An implementation for Sleep Switch."""
35 
36  def __init__(
37  self,
38  coordinator: FoscamCoordinator,
39  config_entry: ConfigEntry,
40  ) -> None:
41  """Initialize a Foscam Sleep Switch."""
42  super().__init__(coordinator, config_entry.entry_id)
43 
44  self._attr_unique_id_attr_unique_id = "sleep_switch"
45  self._attr_translation_key_attr_translation_key = "sleep_switch"
46  self._attr_has_entity_name_attr_has_entity_name = True
47 
48  self.is_asleepis_asleep = self.coordinator.data["is_asleep"]["status"]
49 
50  @property
51  def is_on(self):
52  """Return true if camera is asleep."""
53  return self.is_asleepis_asleep
54 
55  async def async_turn_off(self, **kwargs: Any) -> None:
56  """Wake camera."""
57  LOGGER.debug("Wake camera")
58 
59  ret, _ = await self.hasshasshass.async_add_executor_job(
60  self.coordinator.session.wake_up
61  )
62 
63  if ret != 0:
64  raise HomeAssistantError(f"Error waking up: {ret}")
65 
66  await self.coordinator.async_request_refresh()
67 
68  async def async_turn_on(self, **kwargs: Any) -> None:
69  """But camera is sleep."""
70  LOGGER.debug("Sleep camera")
71 
72  ret, _ = await self.hasshasshass.async_add_executor_job(self.coordinator.session.sleep)
73 
74  if ret != 0:
75  raise HomeAssistantError(f"Error sleeping: {ret}")
76 
77  await self.coordinator.async_request_refresh()
78 
79  @callback
80  def _handle_coordinator_update(self) -> None:
81  """Handle updated data from the coordinator."""
82 
83  self.is_asleepis_asleep = self.coordinator.data["is_asleep"]["status"]
84 
85  self.async_write_ha_stateasync_write_ha_state()
None __init__(self, FoscamCoordinator coordinator, ConfigEntry config_entry)
Definition: switch.py:40
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:22