Simplify WLED segment tracking (#52174)

* Simplify WLED segment tracking

* Fix master controls
This commit is contained in:
Franck Nijhof 2021-06-25 10:57:12 +02:00 committed by GitHub
parent e6c850136c
commit b939570c9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 21 deletions

View File

@ -86,9 +86,8 @@ async def async_setup_entry(
update_segments = partial(
async_update_segments,
entry,
coordinator,
{},
set(),
async_add_entities,
)
@ -363,30 +362,24 @@ class WLEDSegmentLight(WLEDEntity, LightEntity):
@callback
def async_update_segments(
entry: ConfigEntry,
coordinator: WLEDDataUpdateCoordinator,
current: dict[int, WLEDSegmentLight | WLEDMasterLight],
current_ids: set[int],
async_add_entities,
) -> None:
"""Update segments."""
segment_ids = {light.segment_id for light in coordinator.data.state.segments}
current_ids = set(current)
new_entities = []
# Discard master (if present)
current_ids.discard(-1)
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current[segment_id] = WLEDSegmentLight(coordinator, segment_id)
new_entities.append(current[segment_id])
new_entities: list[WLEDMasterLight | WLEDSegmentLight] = []
# More than 1 segment now? No master? Add master controls
if not coordinator.keep_master_light and (
len(current_ids) < 2 and len(segment_ids) > 1
):
current[-1] = WLEDMasterLight(coordinator)
new_entities.append(current[-1])
new_entities.append(WLEDMasterLight(coordinator))
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.append(WLEDSegmentLight(coordinator, segment_id))
if new_entities:
async_add_entities(new_entities)

View File

@ -31,7 +31,7 @@ async def async_setup_entry(
update_segments = partial(
async_update_segments,
coordinator,
{},
set(),
async_add_entities,
)
coordinator.async_add_listener(update_segments)
@ -118,19 +118,18 @@ class WLEDPaletteSelect(WLEDEntity, SelectEntity):
@callback
def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current: dict[int, WLEDPaletteSelect],
current_ids: set[int],
async_add_entities,
) -> None:
"""Update segments."""
segment_ids = {segment.segment_id for segment in coordinator.data.state.segments}
current_ids = set(current)
new_entities = []
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current[segment_id] = WLEDPaletteSelect(coordinator, segment_id)
new_entities.append(current[segment_id])
current_ids.add(segment_id)
new_entities.append(WLEDPaletteSelect(coordinator, segment_id))
if new_entities:
async_add_entities(new_entities)