forked from richo/homeassistant-franklinwh
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathswitch.py
More file actions
210 lines (169 loc) · 6.7 KB
/
switch.py
File metadata and controls
210 lines (169 loc) · 6.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Switch platform for FranklinWH integration."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from franklinwh import AccessoryType, GridStatus
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import CONF_GATEWAY_ID, DOMAIN, MANUFACTURER, MODEL
from .coordinator import FranklinWHCoordinator
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up FranklinWH switches."""
coordinator: FranklinWHCoordinator = hass.data[DOMAIN][entry.entry_id]
entities: list[SwitchEntity] = [GridSwitch(coordinator, entry)]
await coordinator.async_config_entry_first_refresh()
accessories = await coordinator.client.get_accessories()
_LOGGER.debug("Accessories: %s", accessories)
for accessory in accessories:
try:
match accessory["accessoryType"]:
case AccessoryType.SMART_CIRCUIT_MODULE.value:
entities.extend(
FranklinWHSmartSwitch(coordinator, entry, switch_id)
for switch_id in range(3)
)
except KeyError as err:
_LOGGER.error("Expected key 'accessoryType' not found: %s", err)
async_add_entities(entities)
class FranklinWHSmartSwitch(CoordinatorEntity[FranklinWHCoordinator], SwitchEntity):
"""Representation of a FranklinWH smart circuit switch."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: FranklinWHCoordinator,
entry: ConfigEntry,
switch_id: int,
) -> None:
"""Initialize the switch."""
super().__init__(coordinator)
self._switch_id = switch_id
self._switch_index = switch_id # 0-indexed for API
gateway_id = entry.data[CONF_GATEWAY_ID]
# Set unique ID
self._attr_unique_id = f"{gateway_id}_switch_{switch_id + 1}"
# Set name
self._attr_name = f"Switch {switch_id + 1}"
# Set device info
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, gateway_id)},
name=f"FranklinWH {gateway_id[-6:]}",
manufacturer=MANUFACTURER,
model=MODEL,
sw_version=entry.data.get("sw_version"),
)
@property
def is_on(self) -> bool | None:
"""Return true if the switch is on."""
if self.coordinator.data is None or self.coordinator.data.switch_state is None:
return None
try:
return self.coordinator.data.switch_state[self._switch_index]
except (IndexError, TypeError):
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.coordinator.data is not None
and self.coordinator.data.switch_state is not None
)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
switches = [None, None, None]
switches[self._switch_index] = True
try:
await self.coordinator.async_set_switch_state(switches)
except Exception as err:
_LOGGER.error("Failed to turn on switch %d: %s", self._switch_id + 1, err)
raise
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
switches = [None, None, None]
switches[self._switch_index] = False
try:
await self.coordinator.async_set_switch_state(switches)
except Exception as err:
_LOGGER.error("Failed to turn off switch %d: %s", self._switch_id + 1, err)
raise
@property
def icon(self) -> str:
"""Return the icon for the switch."""
if self.is_on:
return "mdi:electric-switch-closed"
return "mdi:electric-switch"
class GridSwitch(CoordinatorEntity[FranklinWHCoordinator], SwitchEntity):
"""Representation of the grid connection switch."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: FranklinWHCoordinator,
entry: ConfigEntry,
) -> None:
"""Initialize the grid switch."""
super().__init__(coordinator)
gateway_id = entry.data[CONF_GATEWAY_ID]
# Set unique ID
self._attr_unique_id = f"{gateway_id}_grid_switch"
# Set name
self._attr_name = "Grid Connection"
# Set device info
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, gateway_id)},
name=f"FranklinWH {gateway_id[-6:]}",
manufacturer=MANUFACTURER,
model=MODEL,
sw_version=entry.data.get("sw_version"),
)
@property
def is_on(self) -> bool | None:
"""Return true if the grid connection is on."""
if self.coordinator.data is None or self.coordinator.data.stats is None:
return None
match self.coordinator.data.stats.current.grid_status:
case GridStatus.NORMAL:
return True
case GridStatus.OFF:
return False
case _:
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.coordinator.data is not None
and self.coordinator.data.stats is not None
and self.coordinator.data.stats.current.grid_status is not None
)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the grid connection on."""
try:
await self.coordinator.client.set_grid_status(GridStatus.NORMAL)
except Exception as err:
_LOGGER.error("Failed to turn on grid connection: %s", err)
raise
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the grid connection off."""
try:
await self.coordinator.client.set_grid_status(GridStatus.OFF)
except Exception as err:
_LOGGER.error("Failed to turn off grid connection: %s", err)
raise
asyncio.create_task(self.coordinator.async_request_refresh()) # noqa: RUF006
@property
def icon(self) -> str:
"""Return the icon for the switch."""
if self.is_on:
return "mdi:transmission-tower"
return "mdi:transmission-tower-off"