-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathselect.py
More file actions
362 lines (303 loc) · 14.2 KB
/
select.py
File metadata and controls
362 lines (303 loc) · 14.2 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""Select entity for the Span Panel."""
from collections.abc import Callable
import logging
from typing import Any, Final
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceNotFound
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from span_panel_api.exceptions import SpanPanelServerError
from .const import (
COORDINATOR,
DOMAIN,
USE_CIRCUIT_NUMBERS,
USE_DEVICE_PREFIX,
CircuitPriority,
)
from .coordinator import SpanPanelCoordinator
from .helpers import (
async_create_span_notification,
build_select_unique_id_for_entry,
)
from .span_panel import SpanPanel
from .span_panel_circuit import SpanPanelCircuit
from .util import panel_to_device_info
ICON = "mdi:chevron-down"
_LOGGER = logging.getLogger(__name__)
# Sentinel value to distinguish "never synced" from "circuit name is None"
_NAME_UNSET: object = object()
class SpanPanelSelectEntityDescriptionWrapper:
"""Wrapper class for Span Panel Select entities."""
# The wrapper is required because the SelectEntityDescription is frozen
# and we need to pass in the entity_description to the constructor
# Using keyword arguments gives a warning about unexpected arguments
# pylint: disable=R0903
def __init__(
self,
key: str,
name: str,
icon: str,
options_fn: Callable[[SpanPanelCircuit], list[str]] = lambda _: [],
current_option_fn: Callable[[SpanPanelCircuit], str | None] = lambda _: None,
select_option_fn: Callable[[SpanPanelCircuit, str], None] | None = None,
) -> None:
"""Initialize the select entity description wrapper."""
self.entity_description = SelectEntityDescription(key=key, name=name, icon=icon)
self.options_fn = options_fn
self.current_option_fn = current_option_fn
self.select_option_fn = select_option_fn
CIRCUIT_PRIORITY_DESCRIPTION: Final = SpanPanelSelectEntityDescriptionWrapper(
key="circuit_priority",
name="Circuit Priority",
icon=ICON,
options_fn=lambda _: [e.value for e in CircuitPriority if e != CircuitPriority.UNKNOWN],
current_option_fn=lambda circuit: CircuitPriority[circuit.priority].value,
)
class SpanPanelCircuitsSelect(CoordinatorEntity[SpanPanelCoordinator], SelectEntity):
"""Represent a select entity for Span Panel circuits."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: SpanPanelCoordinator,
description: SpanPanelSelectEntityDescriptionWrapper,
circuit_id: str,
name: str,
device_name: str,
) -> None:
"""Initialize the select."""
super().__init__(coordinator)
span_panel: SpanPanel = coordinator.data
# Get the circuit from the span_panel to access its properties
circuit = span_panel.circuits.get(circuit_id)
if not circuit:
raise ValueError(f"Circuit {circuit_id} not found")
self.entity_description = description.entity_description
self.description_wrapper = description # Keep reference to wrapper for custom functions
self.id = circuit_id
self._device_name = device_name
self._attr_unique_id = self._construct_select_unique_id(coordinator, span_panel, self.id)
self._attr_device_info = panel_to_device_info(span_panel, device_name)
# Check if entity already exists in registry
entity_registry = er.async_get(coordinator.hass)
existing_entity_id = entity_registry.async_get_entity_id(
"select", DOMAIN, self._attr_unique_id
)
if existing_entity_id:
# Entity exists - always use panel name for sync
# Return None when panel name is None to let HA use default behavior
if circuit.name is None:
self._attr_name = None
else:
self._attr_name = f"{circuit.name} {description.entity_description.name}"
else:
# Initial install - use flag-based name for entity_id generation
use_circuit_numbers = coordinator.config_entry.options.get(USE_CIRCUIT_NUMBERS, False)
if use_circuit_numbers:
# Use circuit number format: "Circuit 15 Priority"
if circuit.tabs and len(circuit.tabs) == 2:
sorted_tabs = sorted(circuit.tabs)
circuit_identifier = f"Circuit {sorted_tabs[0]} {sorted_tabs[1]}"
elif circuit.tabs and len(circuit.tabs) == 1:
circuit_identifier = f"Circuit {circuit.tabs[0]}"
else:
circuit_identifier = f"Circuit {circuit_id}"
self._attr_name = f"{circuit_identifier} {description.entity_description.name}"
else:
# Use friendly name format: "Kitchen Outlets Priority"
# Return None when panel name is None to let HA use default behavior
if name is None:
self._attr_name = None
else:
self._attr_name = f"{name} {description.entity_description.name}"
circuit = self._get_circuit()
self._attr_options = description.options_fn(circuit)
self._attr_current_option = description.current_option_fn(circuit)
# Store initial circuit name for change detection in auto-sync of names
# Use sentinel to distinguish "never synced" from "circuit name is None"
if not existing_entity_id:
self._previous_circuit_name: str | None | object = _NAME_UNSET
_LOGGER.info("Select entity not in registry, will sync on first update")
else:
self._previous_circuit_name = circuit.name
_LOGGER.info(
"Select entity exists in registry, previous name set to '%s'", circuit.name
)
# Use standard coordinator pattern - entities will update automatically
# when coordinator data changes
def _get_circuit(self) -> SpanPanelCircuit:
"""Get the circuit for this entity."""
circuit = self.coordinator.data.circuits[self.id]
if not isinstance(circuit, SpanPanelCircuit):
raise TypeError(f"Expected SpanPanelCircuit, got {type(circuit)}")
return circuit
async def async_will_remove_from_hass(self) -> None:
"""Clean up when entity is removed."""
# Call parent cleanup
await super().async_will_remove_from_hass()
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
_LOGGER.debug("Selecting option: %s", option)
span_panel: SpanPanel = self.coordinator.data
priority = CircuitPriority(option)
curr_circuit = self._get_circuit()
try:
await span_panel.api.set_priority(curr_circuit, priority)
await self.coordinator.async_request_refresh()
except ServiceNotFound as snf:
_LOGGER.warning("Service not found when setting priority: %s", snf)
await async_create_span_notification(
self.hass,
message="The requested service is not available in the SPAN API.",
title="Service Not Found",
notification_id=f"span_panel_service_not_found_{self.id}",
)
except SpanPanelServerError:
warning_msg = (
f"SPAN API returned a server error attempting "
f"to change the circuit priority for {self._attr_name}. "
f"This typically indicates panel firmware doesn't support "
f"this operation."
)
_LOGGER.warning("SPAN API may not support setting priority")
await async_create_span_notification(
self.hass,
message=warning_msg,
title="SPAN API Error",
notification_id=f"span_panel_api_error_{self.id}",
)
def select_option(self, option: str) -> None:
"""Select an option synchronously."""
_LOGGER.debug("Selecting option synchronously: %s", option)
self.hass.async_add_executor_job(self.async_select_option, option)
@property
def available(self) -> bool:
"""Return entity availability.
Selects become unavailable when panel is offline since they can't change settings.
"""
if getattr(self.coordinator, "panel_offline", False):
return False
return super().available
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
span_panel: SpanPanel = self.coordinator.data
circuit = span_panel.circuits.get(self.id)
if circuit:
current_circuit_name = circuit.name
# Check if user has customized the name in HA registry
# If so, skip sync - user's customization takes precedence
user_has_override = False
if self.entity_id:
entity_registry = er.async_get(self.hass)
entity_entry = entity_registry.async_get(self.entity_id)
if entity_entry and entity_entry.name:
user_has_override = True
_LOGGER.debug(
"User has customized name for %s, skipping sync",
self.entity_id,
)
if user_has_override:
# Track panel name for future comparisons but don't trigger reload
self._previous_circuit_name = current_circuit_name
elif self._previous_circuit_name is _NAME_UNSET:
# First update - sync to panel name
_LOGGER.info(
"First update: syncing entity name to panel name '%s' for select, requesting reload",
current_circuit_name,
)
# Update stored previous name for next comparison
self._previous_circuit_name = current_circuit_name
# Request integration reload to persist name change
self.coordinator.request_reload()
elif current_circuit_name != self._previous_circuit_name:
_LOGGER.info(
"Auto-sync detected circuit name change from '%s' to '%s' for select, requesting integration reload",
self._previous_circuit_name,
current_circuit_name,
)
# Update stored previous name for next comparison
self._previous_circuit_name = current_circuit_name
# Request integration reload for next update cycle
self.coordinator.request_reload()
# Update options and current option based on coordinator data
circuit = self._get_circuit()
self._attr_options = self.description_wrapper.options_fn(circuit)
self._attr_current_option = self.description_wrapper.current_option_fn(circuit)
super()._handle_coordinator_update()
def _construct_select_unique_id(
self,
coordinator: SpanPanelCoordinator,
span_panel: SpanPanel,
select_id: str,
) -> str:
"""Construct unique ID for select entities."""
return build_select_unique_id_for_entry(
coordinator, span_panel, select_id, self._device_name
)
def _construct_select_entity_id(
self,
coordinator: SpanPanelCoordinator,
circuit_name: str,
circuit_number: int | str,
suffix: str,
unique_id: str | None = None,
) -> str | None:
"""Construct entity ID for select entities."""
# Check registry first only if unique_id is provided
if unique_id is not None:
entity_registry = er.async_get(coordinator.hass)
existing_entity_id = entity_registry.async_get_entity_id("select", DOMAIN, unique_id)
if existing_entity_id:
return existing_entity_id
# Construct default entity_id
config_entry = coordinator.config_entry
if not self._device_name:
return None
# Default to False so legacy entries without the flag use friendly names
use_circuit_numbers = config_entry.options.get(USE_CIRCUIT_NUMBERS, False)
use_device_prefix = config_entry.options.get(USE_DEVICE_PREFIX, True)
# Build entity ID components
parts = []
if use_device_prefix:
parts.append(self._device_name.lower().replace(" ", "_"))
if use_circuit_numbers:
parts.append(f"circuit_{circuit_number}")
else:
circuit_name_slug = circuit_name.lower().replace(" ", "_")
parts.append(circuit_name_slug)
# Only add suffix if it's different from the last word in the circuit name
if suffix:
circuit_name_words = circuit_name.lower().split()
last_word = circuit_name_words[-1] if circuit_name_words else ""
last_word_normalized = last_word.replace(" ", "_")
if suffix != last_word_normalized:
parts.append(suffix)
entity_id = f"select.{'_'.join(parts)}"
return entity_id
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up select entities for Span Panel."""
_LOGGER.debug("ASYNC SETUP ENTRY SELECT")
data: dict[str, Any] = hass.data[DOMAIN][config_entry.entry_id]
coordinator: SpanPanelCoordinator = data[COORDINATOR]
span_panel: SpanPanel = coordinator.data
# Get device name from config entry data
device_name = config_entry.data.get("device_name", config_entry.title)
entities: list[SpanPanelCircuitsSelect] = []
for circuit_id, circuit_data in span_panel.circuits.items():
if circuit_data.is_user_controllable:
entities.append(
SpanPanelCircuitsSelect(
coordinator,
CIRCUIT_PRIORITY_DESCRIPTION,
circuit_id,
circuit_data.name,
device_name,
)
)
async_add_entities(entities)