Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for Powerwall Switches (V2 API only)."""
2 
3 from typing import Any
4 
5 from tesla_powerwall import GridStatus, IslandMode, PowerwallError
6 
7 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
8 from homeassistant.const import EntityCategory
9 from homeassistant.core import HomeAssistant
10 from homeassistant.exceptions import HomeAssistantError
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 
13 from .entity import PowerWallEntity
14 from .models import PowerwallConfigEntry, PowerwallRuntimeData
15 
16 OFF_GRID_STATUSES = {
17  GridStatus.TRANSITION_TO_ISLAND,
18  GridStatus.ISLANDED,
19 }
20 
21 
23  hass: HomeAssistant,
24  entry: PowerwallConfigEntry,
25  async_add_entities: AddEntitiesCallback,
26 ) -> None:
27  """Set up Powerwall switch platform from Powerwall resources."""
29 
30 
32  """Representation of a Switch entity for Powerwall Off-grid operation."""
33 
34  _attr_translation_key = "off_grid_operation"
35  _attr_entity_category = EntityCategory.CONFIG
36  _attr_device_class = SwitchDeviceClass.SWITCH
37 
38  def __init__(self, powerwall_data: PowerwallRuntimeData) -> None:
39  """Initialize powerwall entity and unique id."""
40  super().__init__(powerwall_data)
41  self._attr_unique_id_attr_unique_id = f"{self.base_unique_id}_off_grid_operation"
42 
43  @property
44  def is_on(self) -> bool:
45  """Return true if the powerwall is off-grid."""
46  return self.coordinator.data.grid_status in OFF_GRID_STATUSES
47 
48  async def async_turn_on(self, **kwargs: Any) -> None:
49  """Turn off-grid mode on."""
50  await self._async_set_island_mode_async_set_island_mode(IslandMode.OFFGRID)
51 
52  async def async_turn_off(self, **kwargs: Any) -> None:
53  """Turn off-grid mode off (return to on-grid usage)."""
54  await self._async_set_island_mode_async_set_island_mode(IslandMode.ONGRID)
55 
56  async def _async_set_island_mode(self, island_mode: IslandMode) -> None:
57  """Toggles off-grid mode using the island_mode argument."""
58  try:
59  await self.power_wallpower_wall.set_island_mode(island_mode)
60  except PowerwallError as ex:
61  raise HomeAssistantError(
62  f"Setting off-grid operation to {island_mode} failed: {ex}"
63  ) from ex
64 
65  self._attr_is_on_attr_is_on = island_mode == IslandMode.OFFGRID
66  self.async_write_ha_stateasync_write_ha_state()
67 
68  await self.coordinator.async_request_refresh()
None __init__(self, PowerwallRuntimeData powerwall_data)
Definition: switch.py:38
None async_setup_entry(HomeAssistant hass, PowerwallConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:26