Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for EZVIZ Switch sensors."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 from typing import Any
7 
8 from pyezviz.constants import DeviceSwitchType, SupportExt
9 from pyezviz.exceptions import HTTPError, PyEzvizError
10 
12  SwitchDeviceClass,
13  SwitchEntity,
14  SwitchEntityDescription,
15 )
16 from homeassistant.config_entries import ConfigEntry
17 from homeassistant.core import HomeAssistant, callback
18 from homeassistant.exceptions import HomeAssistantError
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 
21 from .const import DATA_COORDINATOR, DOMAIN
22 from .coordinator import EzvizDataUpdateCoordinator
23 from .entity import EzvizEntity
24 
25 
26 @dataclass(frozen=True, kw_only=True)
28  """Describe a EZVIZ switch."""
29 
30  supported_ext: str | None
31 
32 
33 SWITCH_TYPES: dict[int, EzvizSwitchEntityDescription] = {
35  key="3",
36  translation_key="status_light",
37  device_class=SwitchDeviceClass.SWITCH,
38  supported_ext=None,
39  ),
41  key="7",
42  translation_key="privacy",
43  device_class=SwitchDeviceClass.SWITCH,
44  supported_ext=str(SupportExt.SupportPtzPrivacy.value),
45  ),
47  key="10",
48  translation_key="infrared_light",
49  device_class=SwitchDeviceClass.SWITCH,
50  supported_ext=str(SupportExt.SupportCloseInfraredLight.value),
51  ),
53  key="21",
54  translation_key="sleep",
55  device_class=SwitchDeviceClass.SWITCH,
56  supported_ext=str(SupportExt.SupportSleep.value),
57  ),
59  key="22",
60  translation_key="audio",
61  device_class=SwitchDeviceClass.SWITCH,
62  supported_ext=str(SupportExt.SupportAudioOnoff.value),
63  ),
65  key="25",
66  translation_key="motion_tracking",
67  device_class=SwitchDeviceClass.SWITCH,
68  supported_ext=str(SupportExt.SupportIntelligentTrack.value),
69  ),
71  key="29",
72  translation_key="all_day_video_recording",
73  device_class=SwitchDeviceClass.SWITCH,
74  supported_ext=str(SupportExt.SupportFulldayRecord.value),
75  ),
77  key="32",
78  translation_key="auto_sleep",
79  device_class=SwitchDeviceClass.SWITCH,
80  supported_ext=str(SupportExt.SupportAutoSleep.value),
81  ),
83  key="301",
84  translation_key="flicker_light_on_movement",
85  device_class=SwitchDeviceClass.SWITCH,
86  supported_ext=str(SupportExt.SupportActiveDefense.value),
87  ),
89  key="305",
90  translation_key="pir_motion_activated_light",
91  device_class=SwitchDeviceClass.SWITCH,
92  supported_ext=str(SupportExt.SupportLightRelate.value),
93  ),
95  key="306",
96  translation_key="tamper_alarm",
97  device_class=SwitchDeviceClass.SWITCH,
98  supported_ext=str(SupportExt.SupportTamperAlarm.value),
99  ),
101  key="650",
102  translation_key="follow_movement",
103  device_class=SwitchDeviceClass.SWITCH,
104  supported_ext=str(SupportExt.SupportTracking.value),
105  ),
106 }
107 
108 
110  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
111 ) -> None:
112  """Set up EZVIZ switch based on a config entry."""
113  coordinator: EzvizDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][
114  DATA_COORDINATOR
115  ]
116 
118  EzvizSwitch(coordinator, camera, switch_number)
119  for camera in coordinator.data
120  for switch_number in coordinator.data[camera]["switches"]
121  if switch_number in SWITCH_TYPES
122  if SWITCH_TYPES[switch_number].supported_ext
123  in coordinator.data[camera]["supportExt"]
124  or SWITCH_TYPES[switch_number].supported_ext is None
125  )
126 
127 
129  """Representation of a EZVIZ sensor."""
130 
131  def __init__(
132  self, coordinator: EzvizDataUpdateCoordinator, serial: str, switch_number: int
133  ) -> None:
134  """Initialize the switch."""
135  super().__init__(coordinator, serial)
136  self._switch_number_switch_number = switch_number
137  self._attr_unique_id_attr_unique_id = (
138  f"{serial}_{self._camera_name}.{DeviceSwitchType(switch_number).name}"
139  )
140  self.entity_descriptionentity_description = SWITCH_TYPES[switch_number]
141  self._attr_is_on_attr_is_on = self.datadatadata["switches"][switch_number]
142 
143  async def async_turn_on(self, **kwargs: Any) -> None:
144  """Change a device switch on the camera."""
145  try:
146  if await self.hasshasshass.async_add_executor_job(
147  self.coordinator.ezviz_client.switch_status,
148  self._serial_serial,
149  self._switch_number_switch_number,
150  1,
151  ):
152  self._attr_is_on_attr_is_on = True
153  self.async_write_ha_stateasync_write_ha_state()
154 
155  except (HTTPError, PyEzvizError) as err:
156  raise HomeAssistantError(f"Failed to turn on switch {self.name}") from err
157 
158  async def async_turn_off(self, **kwargs: Any) -> None:
159  """Change a device switch on the camera."""
160  try:
161  if await self.hasshasshass.async_add_executor_job(
162  self.coordinator.ezviz_client.switch_status,
163  self._serial_serial,
164  self._switch_number_switch_number,
165  0,
166  ):
167  self._attr_is_on_attr_is_on = False
168  self.async_write_ha_stateasync_write_ha_state()
169 
170  except (HTTPError, PyEzvizError) as err:
171  raise HomeAssistantError(f"Failed to turn off switch {self.name}") from err
172 
173  @callback
174  def _handle_coordinator_update(self) -> None:
175  """Handle updated data from the coordinator."""
176  self._attr_is_on_attr_is_on = self.datadatadata["switches"].get(self._switch_number_switch_number)
None __init__(self, EzvizDataUpdateCoordinator coordinator, str serial, int switch_number)
Definition: switch.py:133
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:111