Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Platform for switch integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from triggercmd import client, ha
8 
9 from homeassistant.components.switch import SwitchEntity
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers.device_registry import DeviceInfo
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 
14 from . import TriggercmdConfigEntry
15 from .const import DOMAIN
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
21  hass: HomeAssistant,
22  config_entry: TriggercmdConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Add switch for passed config_entry in HA."""
26  hub = config_entry.runtime_data
27  async_add_entities(TRIGGERcmdSwitch(trigger) for trigger in hub.triggers)
28 
29 
31  """Representation of a Switch."""
32 
33  _attr_has_entity_name = True
34  _attr_assumed_state = True
35  _attr_should_poll = False
36 
37  computer_id: str
38  trigger_id: str
39  firmware_version: str
40  model: str
41  hub: ha.Hub
42 
43  def __init__(self, trigger: TRIGGERcmdSwitch) -> None:
44  """Initialize the switch."""
45  self._switch_switch = trigger
46  self._attr_is_on_attr_is_on = False
47  self._attr_unique_id_attr_unique_id = f"{trigger.computer_id}.{trigger.trigger_id}"
48  self._attr_name_attr_name = trigger.trigger_id
49  self._attr_device_info_attr_device_info = DeviceInfo(
50  identifiers={(DOMAIN, trigger.computer_id)},
51  name=trigger.computer_id.capitalize(),
52  sw_version=trigger.firmware_version,
53  model=trigger.model,
54  manufacturer=trigger.hub.manufacturer,
55  )
56 
57  @property
58  def available(self) -> bool:
59  """Return True if hub is available."""
60  return self._switch_switch.hub.online
61 
62  async def async_turn_on(self, **kwargs):
63  """Turn the switch on."""
64  await self.triggertrigger("on")
65  self._attr_is_on_attr_is_on = True
66  self.async_write_ha_stateasync_write_ha_state()
67 
68  async def async_turn_off(self, **kwargs):
69  """Turn the switch off."""
70  await self.triggertrigger("off")
71  self._attr_is_on_attr_is_on = False
72  self.async_write_ha_stateasync_write_ha_state()
73 
74  async def trigger(self, params: str):
75  """Trigger the command."""
76  r = await client.async_trigger(
77  self._switch_switch.hub.token,
78  {
79  "computer": self._switch_switch.computer_id,
80  "trigger": self._switch_switch.trigger_id,
81  "params": params,
82  "sender": "Home Assistant",
83  },
84  )
85  _LOGGER.debug("TRIGGERcmd trigger response: %s", r.json())
None __init__(self, TRIGGERcmdSwitch trigger)
Definition: switch.py:43
None async_setup_entry(HomeAssistant hass, TriggercmdConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:24