Skip to content

Commit

Permalink
WLED: Fixing entity names and IDs by using device name instead
Browse files Browse the repository at this point in the history
  • Loading branch information
ezcGman committed Dec 27, 2020
1 parent 6d043f2 commit c333613
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 41 deletions.
17 changes: 17 additions & 0 deletions homeassistant/components/wled/__init__.py
Expand Up @@ -109,6 +109,23 @@ async def handler(self, *args, **kwargs):

return handler

async def wled_get_title_base_for_config_entry(entry: ConfigEntry, hass: HomeAssistant):
title_base = entry.title
device_registry = await hass.helpers.device_registry.async_get_registry()
device = device_registry.async_get_device({(DOMAIN, entry.data.get("mac"))}, set())
if device is not None:
_LOGGER.debug("Device: %s", pprint.pformat(device))
title_base = device.name
# I wanted to use the UNDEFINED type, defined in, but I always get an error importing it and I don't understand why:
# from homeassistant.helpers.typing import HomeAssistantType, UNDEFINED
# ERROR (MainThread) [homeassistant.setup] Unable to prepare setup for platform wled.light: Platform not found (cannot import name 'UNDEFINED' from 'homeassistant.helpers.typing' (/usr/src/homeassistant/homeassistant/helpers/typing.py)).
# if device.name_by_user is not UNDEFINED:
if device.name_by_user is not None:
title_base = device.name_by_user
_LOGGER.debug("Title Base: %s", title_base)

return title_base


class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]):
"""Class to manage fetching WLED data from single endpoint."""
Expand Down
27 changes: 18 additions & 9 deletions homeassistant/components/wled/light.py
Expand Up @@ -29,7 +29,7 @@
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.util.color as color_util

from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity, wled_exception_handler
from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity, wled_exception_handler, wled_get_title_base_for_config_entry
from .const import (
ATTR_COLOR_PRIMARY,
ATTR_INTENSITY,
Expand Down Expand Up @@ -84,8 +84,10 @@ async def async_setup_entry(
"async_preset",
)

title_base = await wled_get_title_base_for_config_entry(entry, coordinator.hass)

update_segments = partial(
async_update_segments, entry, coordinator, {}, async_add_entities
async_update_segments, entry, coordinator, {}, async_add_entities, title_base
)

coordinator.async_add_listener(update_segments)
Expand All @@ -95,12 +97,15 @@ async def async_setup_entry(
class WLEDMasterLight(LightEntity, WLEDDeviceEntity):
"""Defines a WLED master light."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator):
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None):
if title_base is None:
title_base = coordinator.data.info.name

"""Initialize WLED master light."""
super().__init__(
entry_id=entry_id,
coordinator=coordinator,
name=f"{coordinator.data.info.name} Master",
name=f"{title_base} Master",
icon="mdi:led-strip-variant",
)

Expand Down Expand Up @@ -154,16 +159,19 @@ class WLEDSegmentLight(LightEntity, WLEDDeviceEntity):
"""Defines a WLED light based on a segment."""

def __init__(
self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, segment: int
self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, segment: int, title_base=None
):
if title_base is None:
title_base = coordinator.data.info.name

"""Initialize WLED segment light."""
self._rgbw = coordinator.data.info.leds.rgbw
self._segment = segment

# If this is the one and only segment, use a simpler name
name = f"{coordinator.data.info.name} Segment {self._segment}"
name = f"{title_base} Segment {self._segment}"
if len(coordinator.data.state.segments) == 1:
name = coordinator.data.info.name
name = title_base

super().__init__(
entry_id=entry_id,
Expand Down Expand Up @@ -400,6 +408,7 @@ def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current: Dict[int, WLEDSegmentLight],
async_add_entities,
title_base=None
) -> None:
"""Update segments."""
segment_ids = {light.segment_id for light in coordinator.data.state.segments}
Expand All @@ -411,12 +420,12 @@ def async_update_segments(
# Process new segments, add them to Home Assistant
new_entities = []
for segment_id in segment_ids - current_ids:
current[segment_id] = WLEDSegmentLight(entry.entry_id, coordinator, segment_id)
current[segment_id] = WLEDSegmentLight(entry.entry_id, coordinator, segment_id, title_base)
new_entities.append(current[segment_id])

# More than 1 segment now? Add master controls
if len(current_ids) < 2 and len(segment_ids) > 1:
current[-1] = WLEDMasterLight(entry.entry_id, coordinator)
current[-1] = WLEDMasterLight(entry.entry_id, coordinator, title_base)
new_entities.append(current[-1])

if new_entities:
Expand Down
67 changes: 45 additions & 22 deletions homeassistant/components/wled/sensor.py
Expand Up @@ -15,7 +15,7 @@
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util.dt import utcnow

from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity
from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity, wled_get_title_base_for_config_entry
from .const import ATTR_LED_COUNT, ATTR_MAX_POWER, CURRENT_MA, DOMAIN


Expand All @@ -27,14 +27,16 @@ async def async_setup_entry(
"""Set up WLED sensor based on a config entry."""
coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

title_base = await wled_get_title_base_for_config_entry(entry, coordinator.hass)

sensors = [
WLEDEstimatedCurrentSensor(entry.entry_id, coordinator),
WLEDUptimeSensor(entry.entry_id, coordinator),
WLEDFreeHeapSensor(entry.entry_id, coordinator),
WLEDWifiBSSIDSensor(entry.entry_id, coordinator),
WLEDWifiChannelSensor(entry.entry_id, coordinator),
WLEDWifiRSSISensor(entry.entry_id, coordinator),
WLEDWifiSignalSensor(entry.entry_id, coordinator),
WLEDEstimatedCurrentSensor(entry.entry_id, coordinator, title_base),
WLEDUptimeSensor(entry.entry_id, coordinator, title_base),
WLEDFreeHeapSensor(entry.entry_id, coordinator, title_base),
WLEDWifiBSSIDSensor(entry.entry_id, coordinator, title_base),
WLEDWifiChannelSensor(entry.entry_id, coordinator, title_base),
WLEDWifiRSSISensor(entry.entry_id, coordinator, title_base),
WLEDWifiSignalSensor(entry.entry_id, coordinator, title_base),
]

async_add_entities(sensors, True)
Expand Down Expand Up @@ -80,14 +82,17 @@ def unit_of_measurement(self) -> str:
class WLEDEstimatedCurrentSensor(WLEDSensor):
"""Defines a WLED estimated current sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED estimated current sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:power",
key="estimated_current",
name=f"{coordinator.data.info.name} Estimated Current",
name=f"{title_base} Estimated Current",
unit_of_measurement=CURRENT_MA,
)

Expand All @@ -113,15 +118,18 @@ def device_class(self) -> Optional[str]:
class WLEDUptimeSensor(WLEDSensor):
"""Defines a WLED uptime sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED uptime sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:clock-outline",
key="uptime",
name=f"{coordinator.data.info.name} Uptime",
name=f"{title_base} Uptime",
)

@property
Expand All @@ -139,15 +147,18 @@ def device_class(self) -> Optional[str]:
class WLEDFreeHeapSensor(WLEDSensor):
"""Defines a WLED free heap sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED free heap sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:memory",
key="free_heap",
name=f"{coordinator.data.info.name} Free Memory",
name=f"{title_base} Free Memory",
unit_of_measurement=DATA_BYTES,
)

Expand All @@ -160,15 +171,18 @@ def state(self) -> int:
class WLEDWifiSignalSensor(WLEDSensor):
"""Defines a WLED Wi-Fi signal sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED Wi-Fi signal sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:wifi",
key="wifi_signal",
name=f"{coordinator.data.info.name} Wi-Fi Signal",
name=f"{title_base} Wi-Fi Signal",
unit_of_measurement=PERCENTAGE,
)

Expand All @@ -181,15 +195,18 @@ def state(self) -> int:
class WLEDWifiRSSISensor(WLEDSensor):
"""Defines a WLED Wi-Fi RSSI sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED Wi-Fi RSSI sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:wifi",
key="wifi_rssi",
name=f"{coordinator.data.info.name} Wi-Fi RSSI",
name=f"{title_base} Wi-Fi RSSI",
unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
)

Expand All @@ -207,15 +224,18 @@ def device_class(self) -> Optional[str]:
class WLEDWifiChannelSensor(WLEDSensor):
"""Defines a WLED Wi-Fi Channel sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED Wi-Fi Channel sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:wifi",
key="wifi_channel",
name=f"{coordinator.data.info.name} Wi-Fi Channel",
name=f"{title_base} Wi-Fi Channel",
)

@property
Expand All @@ -227,15 +247,18 @@ def state(self) -> int:
class WLEDWifiBSSIDSensor(WLEDSensor):
"""Defines a WLED Wi-Fi BSSID sensor."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED Wi-Fi BSSID sensor."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
enabled_default=False,
entry_id=entry_id,
icon="mdi:wifi",
key="wifi_bssid",
name=f"{coordinator.data.info.name} Wi-Fi BSSID",
name=f"{title_base} Wi-Fi BSSID",
)

@property
Expand Down
31 changes: 21 additions & 10 deletions homeassistant/components/wled/switch.py
Expand Up @@ -6,7 +6,7 @@
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType

from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity, wled_exception_handler
from . import WLEDDataUpdateCoordinator, WLEDDeviceEntity, wled_exception_handler, wled_get_title_base_for_config_entry
from .const import (
ATTR_DURATION,
ATTR_FADE,
Expand All @@ -26,10 +26,12 @@ async def async_setup_entry(
"""Set up WLED switch based on a config entry."""
coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

title_base = await wled_get_title_base_for_config_entry(entry, coordinator.hass)

switches = [
WLEDNightlightSwitch(entry.entry_id, coordinator),
WLEDSyncSendSwitch(entry.entry_id, coordinator),
WLEDSyncReceiveSwitch(entry.entry_id, coordinator),
WLEDNightlightSwitch(entry.entry_id, coordinator, title_base),
WLEDSyncSendSwitch(entry.entry_id, coordinator, title_base),
WLEDSyncReceiveSwitch(entry.entry_id, coordinator, title_base),
]
async_add_entities(switches, True)

Expand Down Expand Up @@ -61,14 +63,17 @@ def unique_id(self) -> str:
class WLEDNightlightSwitch(WLEDSwitch):
"""Defines a WLED nightlight switch."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED nightlight switch."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:weather-night",
key="nightlight",
name=f"{coordinator.data.info.name} Nightlight",
name=f"{title_base} Nightlight",
)

@property
Expand Down Expand Up @@ -99,14 +104,17 @@ async def async_turn_on(self, **kwargs: Any) -> None:
class WLEDSyncSendSwitch(WLEDSwitch):
"""Defines a WLED sync send switch."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None) -> None:
"""Initialize WLED sync send switch."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:upload-network-outline",
key="sync_send",
name=f"{coordinator.data.info.name} Sync Send",
name=f"{title_base} Sync Send",
)

@property
Expand All @@ -133,14 +141,17 @@ async def async_turn_on(self, **kwargs: Any) -> None:
class WLEDSyncReceiveSwitch(WLEDSwitch):
"""Defines a WLED sync receive switch."""

def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator):
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, title_base=None):
"""Initialize WLED sync receive switch."""
if title_base is None:
title_base = coordinator.data.info.name

super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:download-network-outline",
key="sync_receive",
name=f"{coordinator.data.info.name} Sync Receive",
name=f"{title_base} Sync Receive",
)

@property
Expand Down

0 comments on commit c333613

Please sign in to comment.