Home Assistant Unofficial Reference 2024.12.1
valve.py
Go to the documentation of this file.
1 """Valve support for switch entities."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
9  DOMAIN as VALVE_DOMAIN,
10  ValveEntity,
11  ValveEntityFeature,
12 )
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.const import (
15  ATTR_ENTITY_ID,
16  CONF_ENTITY_ID,
17  SERVICE_TURN_OFF,
18  SERVICE_TURN_ON,
19  STATE_ON,
20 )
21 from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback
22 from homeassistant.helpers import entity_registry as er
23 from homeassistant.helpers.entity_platform import AddEntitiesCallback
24 
25 from .const import CONF_INVERT
26 from .entity import BaseInvertableEntity
27 
28 
30  hass: HomeAssistant,
31  config_entry: ConfigEntry,
32  async_add_entities: AddEntitiesCallback,
33 ) -> None:
34  """Initialize Valve Switch config entry."""
35  registry = er.async_get(hass)
36  entity_id = er.async_validate_entity_id(
37  registry, config_entry.options[CONF_ENTITY_ID]
38  )
39 
41  [
43  hass,
44  config_entry.title,
45  VALVE_DOMAIN,
46  config_entry.options[CONF_INVERT],
47  entity_id,
48  config_entry.entry_id,
49  )
50  ]
51  )
52 
53 
55  """Represents a Switch as a Valve."""
56 
57  _attr_supported_features = ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE
58  _attr_reports_position = False
59 
60  async def async_open_valve(self, **kwargs: Any) -> None:
61  """Open the valve."""
62  await self.hasshass.services.async_call(
63  SWITCH_DOMAIN,
64  SERVICE_TURN_OFF if self._invert_state_invert_state else SERVICE_TURN_ON,
65  {ATTR_ENTITY_ID: self._switch_entity_id_switch_entity_id},
66  blocking=True,
67  context=self._context_context,
68  )
69 
70  async def async_close_valve(self, **kwargs: Any) -> None:
71  """Close valve."""
72  await self.hasshass.services.async_call(
73  SWITCH_DOMAIN,
74  SERVICE_TURN_ON if self._invert_state_invert_state else SERVICE_TURN_OFF,
75  {ATTR_ENTITY_ID: self._switch_entity_id_switch_entity_id},
76  blocking=True,
77  context=self._context_context,
78  )
79 
80  @callback
82  self, event: Event[EventStateChangedData] | None = None
83  ) -> None:
84  """Handle child updates."""
85  super().async_state_changed_listener(event)
86  if (
87  not self.availableavailable
88  or (state := self.hasshass.states.get(self._switch_entity_id_switch_entity_id)) is None
89  ):
90  return
91 
92  if self._invert_state_invert_state:
93  self._attr_is_closed_attr_is_closed = state.state == STATE_ON
94  else:
95  self._attr_is_closed_attr_is_closed = state.state != STATE_ON
None async_state_changed_listener(self, Event[EventStateChangedData]|None event=None)
Definition: valve.py:83
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: valve.py:33