Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for SCSGate switches."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from scsgate.messages import ScenarioTriggeredMessage, StateMessage
9 from scsgate.tasks import ToggleStatusTask
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SWITCH_PLATFORM_SCHEMA,
14  SwitchEntity,
15 )
16 from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_DEVICES, CONF_NAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 
22 from . import CONF_SCS_ID, DOMAIN, SCSGATE_SCHEMA
23 
24 ATTR_SCENARIO_ID = "scenario_id"
25 
26 CONF_TRADITIONAL = "traditional"
27 CONF_SCENARIO = "scenario"
28 
29 PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
30  {vol.Required(CONF_DEVICES): cv.schema_with_slug_keys(SCSGATE_SCHEMA)}
31 )
32 
33 
35  hass: HomeAssistant,
36  config: ConfigType,
37  add_entities: AddEntitiesCallback,
38  discovery_info: DiscoveryInfoType | None = None,
39 ) -> None:
40  """Set up the SCSGate switches."""
41  logger = logging.getLogger(__name__)
42  scsgate = hass.data[DOMAIN]
43 
45  logger=logger,
46  config=config,
47  scsgate=scsgate,
48  add_entities_callback=add_entities,
49  )
50 
51  _setup_scenario_switches(logger=logger, config=config, scsgate=scsgate, hass=hass)
52 
53 
54 def _setup_traditional_switches(logger, config, scsgate, add_entities_callback):
55  """Add traditional SCSGate switches."""
56  traditional = config.get(CONF_TRADITIONAL)
57  switches = []
58 
59  if traditional:
60  for entity_info in traditional.values():
61  if entity_info[CONF_SCS_ID] in scsgate.devices:
62  continue
63 
64  name = entity_info[CONF_NAME]
65  scs_id = entity_info[CONF_SCS_ID]
66 
67  logger.info("Adding %s scsgate.traditional_switch", name)
68 
69  switch = SCSGateSwitch(
70  name=name, scs_id=scs_id, logger=logger, scsgate=scsgate
71  )
72  switches.append(switch)
73 
74  add_entities_callback(switches)
75  scsgate.add_devices_to_register(switches)
76 
77 
78 def _setup_scenario_switches(logger, config, scsgate, hass):
79  """Add only SCSGate scenario switches."""
80  if scenario := config.get(CONF_SCENARIO):
81  for entity_info in scenario.values():
82  if entity_info[CONF_SCS_ID] in scsgate.devices:
83  continue
84 
85  name = entity_info[CONF_NAME]
86  scs_id = entity_info[CONF_SCS_ID]
87 
88  logger.info("Adding %s scsgate.scenario_switch", name)
89 
90  switch = SCSGateScenarioSwitch(
91  name=name, scs_id=scs_id, logger=logger, hass=hass
92  )
93  scsgate.add_device(switch)
94 
95 
97  """Representation of a SCSGate switch."""
98 
99  _attr_should_poll = False
100 
101  def __init__(self, scs_id, name, logger, scsgate):
102  """Initialize the switch."""
103  self._name_name = name
104  self._scs_id_scs_id = scs_id
105  self._toggled_toggled = False
106  self._logger_logger = logger
107  self._scsgate_scsgate = scsgate
108 
109  @property
110  def scs_id(self):
111  """Return the SCS ID."""
112  return self._scs_id_scs_id
113 
114  @property
115  def name(self):
116  """Return the name of the device if any."""
117  return self._name_name
118 
119  @property
120  def is_on(self):
121  """Return true if switch is on."""
122  return self._toggled_toggled
123 
124  def turn_on(self, **kwargs: Any) -> None:
125  """Turn the device on."""
126 
127  self._scsgate_scsgate.append_task(ToggleStatusTask(target=self._scs_id_scs_id, toggled=True))
128 
129  self._toggled_toggled = True
130  self.schedule_update_ha_stateschedule_update_ha_state()
131 
132  def turn_off(self, **kwargs: Any) -> None:
133  """Turn the device off."""
134 
135  self._scsgate_scsgate.append_task(ToggleStatusTask(target=self._scs_id_scs_id, toggled=False))
136 
137  self._toggled_toggled = False
138  self.schedule_update_ha_stateschedule_update_ha_state()
139 
140  def process_event(self, message):
141  """Handle a SCSGate message related with this switch."""
142  if self._toggled_toggled == message.toggled:
143  self._logger_logger.info(
144  "Switch %s, ignoring message %s because state already active",
145  self._scs_id_scs_id,
146  message,
147  )
148  # Nothing changed, ignoring
149  return
150 
151  self._toggled_toggled = message.toggled
152  self.schedule_update_ha_stateschedule_update_ha_state()
153 
154  command = "off"
155  if self._toggled_toggled:
156  command = "on"
157 
158  self.hasshass.bus.fire(
159  "button_pressed", {ATTR_ENTITY_ID: self._scs_id_scs_id, ATTR_STATE: command}
160  )
161 
162 
164  """Provides a SCSGate scenario switch.
165 
166  This switch is always in an 'off" state, when toggled it's used to trigger
167  events.
168  """
169 
170  def __init__(self, scs_id, name, logger, hass):
171  """Initialize the scenario."""
172  self._name_name = name
173  self._scs_id_scs_id = scs_id
174  self._logger_logger = logger
175  self._hass_hass = hass
176 
177  @property
178  def scs_id(self):
179  """Return the SCS ID."""
180  return self._scs_id_scs_id
181 
182  @property
183  def name(self):
184  """Return the name of the device if any."""
185  return self._name_name
186 
187  def process_event(self, message):
188  """Handle a SCSGate message related with this switch."""
189 
190  if isinstance(message, StateMessage):
191  scenario_id = message.bytes[4]
192  elif isinstance(message, ScenarioTriggeredMessage):
193  scenario_id = message.scenario
194  else:
195  self._logger_logger.warning(
196  "Scenario switch: received unknown message %s", message
197  )
198  return
199 
200  self._hass_hass.bus.fire(
201  "scenario_switch_triggered",
202  {ATTR_ENTITY_ID: int(self._scs_id_scs_id), ATTR_SCENARIO_ID: int(scenario_id, 16)},
203  )
def __init__(self, scs_id, name, logger, hass)
Definition: switch.py:170
def __init__(self, scs_id, name, logger, scsgate)
Definition: switch.py:101
None schedule_update_ha_state(self, bool force_refresh=False)
Definition: entity.py:1244
def _setup_traditional_switches(logger, config, scsgate, add_entities_callback)
Definition: switch.py:54
def _setup_scenario_switches(logger, config, scsgate, hass)
Definition: switch.py:78
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:39