Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for Tractive switches."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 import logging
7 from typing import Any, Literal, cast
8 
9 from aiotractive.exceptions import TractiveError
10 
11 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
12 from homeassistant.const import EntityCategory
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from . import Trackables, TractiveClient, TractiveConfigEntry
17 from .const import (
18  ATTR_BUZZER,
19  ATTR_LED,
20  ATTR_LIVE_TRACKING,
21  TRACKER_SWITCH_STATUS_UPDATED,
22 )
23 from .entity import TractiveEntity
24 
25 _LOGGER = logging.getLogger(__name__)
26 
27 
28 @dataclass(frozen=True, kw_only=True)
30  """Class describing Tractive switch entities."""
31 
32  method: Literal["async_set_buzzer", "async_set_led", "async_set_live_tracking"]
33 
34 
35 SWITCH_TYPES: tuple[TractiveSwitchEntityDescription, ...] = (
37  key=ATTR_BUZZER,
38  translation_key="tracker_buzzer",
39  method="async_set_buzzer",
40  entity_category=EntityCategory.CONFIG,
41  ),
43  key=ATTR_LED,
44  translation_key="tracker_led",
45  method="async_set_led",
46  entity_category=EntityCategory.CONFIG,
47  ),
49  key=ATTR_LIVE_TRACKING,
50  translation_key="live_tracking",
51  method="async_set_live_tracking",
52  entity_category=EntityCategory.CONFIG,
53  ),
54 )
55 
56 
58  hass: HomeAssistant,
59  entry: TractiveConfigEntry,
60  async_add_entities: AddEntitiesCallback,
61 ) -> None:
62  """Set up Tractive switches."""
63  client = entry.runtime_data.client
64  trackables = entry.runtime_data.trackables
65 
66  entities = [
67  TractiveSwitch(client, item, description)
68  for description in SWITCH_TYPES
69  for item in trackables
70  ]
71 
72  async_add_entities(entities)
73 
74 
76  """Tractive switch."""
77 
78  entity_description: TractiveSwitchEntityDescription
79 
80  def __init__(
81  self,
82  client: TractiveClient,
83  item: Trackables,
84  description: TractiveSwitchEntityDescription,
85  ) -> None:
86  """Initialize switch entity."""
87  super().__init__(
88  client,
89  item.trackable,
90  item.tracker_details,
91  f"{TRACKER_SWITCH_STATUS_UPDATED}-{item.tracker_details['_id']}",
92  )
93 
94  self._attr_unique_id_attr_unique_id = f"{item.trackable['_id']}_{description.key}"
95  self._tracker_tracker = item.tracker
96  self._method_method = getattr(self, description.method)
97  self.entity_descriptionentity_description = description
98 
99  @callback
100  def handle_status_update(self, event: dict[str, Any]) -> None:
101  """Handle status update."""
102  if self.entity_descriptionentity_description.key not in event:
103  return
104 
105  # We received an event, so the service is online and the switch entities should
106  # be available.
107  self._attr_available_attr_available_attr_available = True
108  self._attr_is_on_attr_is_on = event[self.entity_descriptionentity_description.key]
109 
110  self.async_write_ha_stateasync_write_ha_state()
111 
112  async def async_turn_on(self, **kwargs: Any) -> None:
113  """Turn on a switch."""
114  try:
115  result = await self._method_method(True)
116  except TractiveError as error:
117  _LOGGER.error(error)
118  return
119  # Write state back to avoid switch flips with a slow response
120  if result["pending"]:
121  self._attr_is_on_attr_is_on = True
122  self.async_write_ha_stateasync_write_ha_state()
123 
124  async def async_turn_off(self, **kwargs: Any) -> None:
125  """Turn off a switch."""
126  try:
127  result = await self._method_method(False)
128  except TractiveError as error:
129  _LOGGER.error(error)
130  return
131  # Write state back to avoid switch flips with a slow response
132  if result["pending"]:
133  self._attr_is_on_attr_is_on = False
134  self.async_write_ha_stateasync_write_ha_state()
135 
136  async def async_set_buzzer(self, active: bool) -> dict[str, Any]:
137  """Set the buzzer on/off."""
138  return cast(dict[str, Any], await self._tracker_tracker.set_buzzer_active(active))
139 
140  async def async_set_led(self, active: bool) -> dict[str, Any]:
141  """Set the LED on/off."""
142  return cast(dict[str, Any], await self._tracker_tracker.set_led_active(active))
143 
144  async def async_set_live_tracking(self, active: bool) -> dict[str, Any]:
145  """Set the live tracking on/off."""
146  return cast(
147  dict[str, Any], await self._tracker_tracker.set_live_tracking_active(active)
148  )
dict[str, Any] async_set_buzzer(self, bool active)
Definition: switch.py:136
None __init__(self, TractiveClient client, Trackables item, TractiveSwitchEntityDescription description)
Definition: switch.py:85
dict[str, Any] async_set_led(self, bool active)
Definition: switch.py:140
dict[str, Any] async_set_live_tracking(self, bool active)
Definition: switch.py:144
None handle_status_update(self, dict[str, Any] event)
Definition: switch.py:100
None async_setup_entry(HomeAssistant hass, TractiveConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:61