Home Assistant Unofficial Reference 2024.12.1
valve.py
Go to the documentation of this file.
1 """Support for switch entities."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from gardena_bluetooth.const import Valve
8 
9 from homeassistant.components.valve import ValveEntity, ValveEntityFeature
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 
13 from . import GardenaBluetoothConfigEntry
14 from .coordinator import GardenaBluetoothCoordinator
15 from .entity import GardenaBluetoothEntity
16 
17 FALLBACK_WATERING_TIME_IN_SECONDS = 60 * 60
18 
19 
21  hass: HomeAssistant,
22  entry: GardenaBluetoothConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Set up switch based on a config entry."""
26  coordinator = entry.runtime_data
27  entities = []
28  if GardenaBluetoothValve.characteristics.issubset(coordinator.characteristics):
29  entities.append(GardenaBluetoothValve(coordinator))
30 
31  async_add_entities(entities)
32 
33 
35  """Representation of a valve switch."""
36 
37  _attr_name = None
38  _attr_is_closed: bool | None = None
39  _attr_reports_position = False
40  _attr_supported_features = ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE
41 
42  characteristics = {
43  Valve.state.uuid,
44  Valve.manual_watering_time.uuid,
45  Valve.remaining_open_time.uuid,
46  }
47 
48  def __init__(
49  self,
50  coordinator: GardenaBluetoothCoordinator,
51  ) -> None:
52  """Initialize the switch."""
53  super().__init__(
54  coordinator, {Valve.state.uuid, Valve.manual_watering_time.uuid}
55  )
56  self._attr_unique_id_attr_unique_id = f"{coordinator.address}-{Valve.state.uuid}"
57 
58  def _handle_coordinator_update(self) -> None:
59  self._attr_is_closed_attr_is_closed = not self.coordinator.get_cached(Valve.state)
61 
62  async def async_open_valve(self, **kwargs: Any) -> None:
63  """Turn the entity on."""
64  value = (
65  self.coordinator.get_cached(Valve.manual_watering_time)
66  or FALLBACK_WATERING_TIME_IN_SECONDS
67  )
68  await self.coordinator.write(Valve.remaining_open_time, value)
69  self._attr_is_closed_attr_is_closed = False
70  self.async_write_ha_stateasync_write_ha_state()
71 
72  async def async_close_valve(self, **kwargs: Any) -> None:
73  """Turn the entity off."""
74  await self.coordinator.write(Valve.remaining_open_time, 0)
75  self._attr_is_closed_attr_is_closed = True
76  self.async_write_ha_stateasync_write_ha_state()
CharacteristicType|None get_cached(self, Characteristic[CharacteristicType] char)
Definition: coordinator.py:80
None write(self, Characteristic[CharacteristicType] char, CharacteristicType value)
Definition: coordinator.py:88
None __init__(self, GardenaBluetoothCoordinator coordinator)
Definition: valve.py:51
None async_setup_entry(HomeAssistant hass, GardenaBluetoothConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: valve.py:24