Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """The power switch which can be toggled via the APsystems local API integration."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from aiohttp.client_exceptions import ClientConnectionError
8 from APsystemsEZ1 import InverterReturnedError
9 
10 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 
14 from . import ApSystemsConfigEntry, ApSystemsData
15 from .entity import ApSystemsEntity
16 
17 
19  hass: HomeAssistant,
20  config_entry: ApSystemsConfigEntry,
21  add_entities: AddEntitiesCallback,
22 ) -> None:
23  """Set up the switch platform."""
24 
25  add_entities([ApSystemsInverterSwitch(config_entry.runtime_data)], True)
26 
27 
29  """The switch class for APSystems switches."""
30 
31  _attr_device_class = SwitchDeviceClass.SWITCH
32  _attr_translation_key = "inverter_status"
33 
34  def __init__(self, data: ApSystemsData) -> None:
35  """Initialize the switch."""
36  super().__init__(data)
37  self._api_api = data.coordinator.api
38  self._attr_unique_id_attr_unique_id = f"{data.device_id}_inverter_status"
39 
40  async def async_update(self) -> None:
41  """Update switch status and availability."""
42  try:
43  status = await self._api_api.get_device_power_status()
44  except (TimeoutError, ClientConnectionError, InverterReturnedError):
45  self._attr_available_attr_available = False
46  else:
47  self._attr_available_attr_available = True
48  self._attr_is_on_attr_is_on = status
49 
50  async def async_turn_on(self, **kwargs: Any) -> None:
51  """Turn the switch on."""
52  await self._api_api.set_device_power_status(True)
53 
54  async def async_turn_off(self, **kwargs: Any) -> None:
55  """Turn the switch off."""
56  await self._api_api.set_device_power_status(False)
None async_setup_entry(HomeAssistant hass, ApSystemsConfigEntry config_entry, AddEntitiesCallback add_entities)
Definition: switch.py:22
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)