Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Fully Kiosk Browser switch."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
9 from fullykiosk import FullyKiosk
10 
11 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
12 from homeassistant.const import EntityCategory
13 from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from . import FullyKioskConfigEntry
17 from .coordinator import FullyKioskDataUpdateCoordinator
18 from .entity import FullyKioskEntity
19 
20 
21 @dataclass(frozen=True, kw_only=True)
23  """Fully Kiosk Browser switch entity description."""
24 
25  on_action: Callable[[FullyKiosk], Any]
26  off_action: Callable[[FullyKiosk], Any]
27  is_on_fn: Callable[[dict[str, Any]], Any]
28  mqtt_on_event: str | None
29  mqtt_off_event: str | None
30 
31 
32 SWITCHES: tuple[FullySwitchEntityDescription, ...] = (
34  key="screensaver",
35  translation_key="screensaver",
36  on_action=lambda fully: fully.startScreensaver(),
37  off_action=lambda fully: fully.stopScreensaver(),
38  is_on_fn=lambda data: data.get("isInScreensaver"),
39  mqtt_on_event="onScreensaverStart",
40  mqtt_off_event="onScreensaverStop",
41  ),
43  key="maintenance",
44  translation_key="maintenance",
45  entity_category=EntityCategory.CONFIG,
46  on_action=lambda fully: fully.enableLockedMode(),
47  off_action=lambda fully: fully.disableLockedMode(),
48  is_on_fn=lambda data: data.get("maintenanceMode"),
49  mqtt_on_event=None,
50  mqtt_off_event=None,
51  ),
53  key="kiosk",
54  translation_key="kiosk",
55  entity_category=EntityCategory.CONFIG,
56  on_action=lambda fully: fully.lockKiosk(),
57  off_action=lambda fully: fully.unlockKiosk(),
58  is_on_fn=lambda data: data.get("kioskLocked"),
59  mqtt_on_event=None,
60  mqtt_off_event=None,
61  ),
63  key="motion-detection",
64  translation_key="motion_detection",
65  entity_category=EntityCategory.CONFIG,
66  on_action=lambda fully: fully.enableMotionDetection(),
67  off_action=lambda fully: fully.disableMotionDetection(),
68  is_on_fn=lambda data: data["settings"].get("motionDetection"),
69  mqtt_on_event=None,
70  mqtt_off_event=None,
71  ),
73  key="screenOn",
74  translation_key="screen_on",
75  on_action=lambda fully: fully.screenOn(),
76  off_action=lambda fully: fully.screenOff(),
77  is_on_fn=lambda data: data.get("screenOn"),
78  mqtt_on_event="screenOn",
79  mqtt_off_event="screenOff",
80  ),
81 )
82 
83 
85  hass: HomeAssistant,
86  config_entry: FullyKioskConfigEntry,
87  async_add_entities: AddEntitiesCallback,
88 ) -> None:
89  """Set up the Fully Kiosk Browser switch."""
90  coordinator = config_entry.runtime_data
91 
93  FullySwitchEntity(coordinator, description) for description in SWITCHES
94  )
95 
96 
98  """Fully Kiosk Browser switch entity."""
99 
100  entity_description: FullySwitchEntityDescription
101 
102  def __init__(
103  self,
104  coordinator: FullyKioskDataUpdateCoordinator,
105  description: FullySwitchEntityDescription,
106  ) -> None:
107  """Initialize the Fully Kiosk Browser switch entity."""
108  super().__init__(coordinator)
109  self.entity_descriptionentity_description = description
110  self._attr_unique_id_attr_unique_id = f"{coordinator.data['deviceID']}-{description.key}"
111  self._turned_on_subscription_turned_on_subscription: CALLBACK_TYPE | None = None
112  self._turned_off_subscription_turned_off_subscription: CALLBACK_TYPE | None = None
113 
114  async def async_added_to_hass(self) -> None:
115  """When entity is added to hass."""
116  await super().async_added_to_hass()
117  description = self.entity_descriptionentity_description
118  self._turned_on_subscription_turned_on_subscription = await self.mqtt_subscribemqtt_subscribe(
119  description.mqtt_off_event, self._turn_off_turn_off
120  )
121  self._turned_off_subscription_turned_off_subscription = await self.mqtt_subscribemqtt_subscribe(
122  description.mqtt_on_event, self._turn_on_turn_on
123  )
124 
125  async def async_will_remove_from_hass(self) -> None:
126  """Close MQTT subscriptions when removed."""
127  await super().async_will_remove_from_hass()
128  if self._turned_off_subscription_turned_off_subscription is not None:
129  self._turned_off_subscription_turned_off_subscription()
130  if self._turned_on_subscription_turned_on_subscription is not None:
131  self._turned_on_subscription_turned_on_subscription()
132 
133  async def async_turn_on(self, **kwargs: Any) -> None:
134  """Turn the entity on."""
135  await self.entity_descriptionentity_description.on_action(self.coordinator.fully)
136  await self.coordinator.async_refresh()
137 
138  async def async_turn_off(self, **kwargs: Any) -> None:
139  """Turn the entity off."""
140  await self.entity_descriptionentity_description.off_action(self.coordinator.fully)
141  await self.coordinator.async_refresh()
142 
143  def _turn_off(self, **kwargs: Any) -> None:
144  """Optimistically turn off."""
145  self._attr_is_on_attr_is_on = False
146  self.async_write_ha_stateasync_write_ha_state()
147 
148  def _turn_on(self, **kwargs: Any) -> None:
149  """Optimistically turn on."""
150  self._attr_is_on_attr_is_on = True
151  self.async_write_ha_stateasync_write_ha_state()
152 
153  @callback
154  def _handle_coordinator_update(self) -> None:
155  """Handle updated data from the coordinator."""
156  self._attr_is_on_attr_is_on = bool(self.entity_descriptionentity_description.is_on_fn(self.coordinator.data))
157  self.async_write_ha_stateasync_write_ha_state()
CALLBACK_TYPE|None mqtt_subscribe(self, str|None event, CALLBACK_TYPE event_callback)
Definition: entity.py:65
None __init__(self, FullyKioskDataUpdateCoordinator coordinator, FullySwitchEntityDescription description)
Definition: switch.py:106
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None async_setup_entry(HomeAssistant hass, FullyKioskConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:88