<commit_before>"""Support for WLED sensors."""
from __future__ import annotations

from dataclasses import dataclass
from datetime import timedelta
from typing import Callable

from wled import Device as WLEDDevice

from homeassistant.components.sensor import (
    DEVICE_CLASS_CURRENT,
    STATE_CLASS_MEASUREMENT,
    SensorEntity,
    SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    DATA_BYTES,
    DEVICE_CLASS_SIGNAL_STRENGTH,
    DEVICE_CLASS_TIMESTAMP,
    ELECTRIC_CURRENT_MILLIAMPERE,
    ENTITY_CATEGORY_DIAGNOSTIC,
    PERCENTAGE,
    SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util.dt import utcnow

from .const import DOMAIN
from .coordinator import WLEDDataUpdateCoordinator
from .models import WLEDEntity


@dataclass
class WLEDSensorEntityDescriptionMixin:
    """Mixin for required keys."""

    value_fn: Callable[[WLEDDevice], StateType]


@dataclass
class WLEDSensorEntityDescription(
    SensorEntityDescription, WLEDSensorEntityDescriptionMixin
):
    """Describes WLED sensor entity."""


SENSORS: tuple[WLEDSensorEntityDescription, ...] = (
    WLEDSensorEntityDescription(
        key="estimated_current",
        name="Estimated Current",
        native_unit_of_measurement=ELECTRIC_CURRENT_MILLIAMPERE,
        device_class=DEVICE_CLASS_CURRENT,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        value_fn=lambda device: device.info.leds.power,
    ),
    WLEDSensorEntityDescription(
        key="info_leds_count",
        name="LED Count",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        value_fn=lambda device: device.info.leds.count,
    ),
    WLEDSensorEntityDescription(
        key="info_leds_max_power",
        name="Max Current",
        native_unit_of_measurement=ELECTRIC_CURRENT_MILLIAMPERE,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        device_class=DEVICE_CLASS_CURRENT,
        value_fn=lambda device: device.info.leds.max_power,
    ),
    WLEDSensorEntityDescription(
        key="uptime",
        name="Uptime",
        device_class=DEVICE_CLASS_TIMESTAMP,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: (utcnow() - timedelta(seconds=device.info.uptime))
        .replace(microsecond=0)
        .isoformat(),
    ),
    WLEDSensorEntityDescription(
        key="free_heap",
        name="Free Memory",
        icon="mdi:memory",
        native_unit_of_measurement=DATA_BYTES,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.free_heap,
    ),
    WLEDSensorEntityDescription(
        key="wifi_signal",
        name="Wi-Fi Signal",
        icon="mdi:wifi",
        native_unit_of_measurement=PERCENTAGE,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.signal if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_rssi",
        name="Wi-Fi RSSI",
        native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
        device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.rssi if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_channel",
        name="Wi-Fi Channel",
        icon="mdi:wifi",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.channel if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_bssid",
        name="Wi-Fi BSSID",
        icon="mdi:wifi",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.bssid if device.info.wifi else None,
    ),
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up WLED sensor based on a config entry."""
    coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    async_add_entities(
        WLEDSensorEntity(coordinator, description) for description in SENSORS
    )


class WLEDSensorEntity(WLEDEntity, SensorEntity):
    """Defines a WLED sensor entity."""

    entity_description: WLEDSensorEntityDescription

    def __init__(
        self,
        coordinator: WLEDDataUpdateCoordinator,
        description: WLEDSensorEntityDescription,
    ) -> None:
        """Initialize a WLED sensor entity."""
        super().__init__(coordinator=coordinator)
        self.entity_description = description
        self._attr_name = f"{coordinator.data.info.name} {description.name}"
        self._attr_unique_id = f"{coordinator.data.info.mac_address}_{description.key}"

    @property
    def native_value(self) -> StateType:
        """Return the state of the sensor."""
        return self.entity_description.value_fn(self.coordinator.data)<commit_msg>Use native datetime value in WLED sensors (#59907)<commit_after>"""Support for WLED sensors."""
from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Callable

from wled import Device as WLEDDevice

from homeassistant.components.sensor import (
    DEVICE_CLASS_CURRENT,
    STATE_CLASS_MEASUREMENT,
    SensorEntity,
    SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    DATA_BYTES,
    DEVICE_CLASS_SIGNAL_STRENGTH,
    DEVICE_CLASS_TIMESTAMP,
    ELECTRIC_CURRENT_MILLIAMPERE,
    ENTITY_CATEGORY_DIAGNOSTIC,
    PERCENTAGE,
    SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util.dt import utcnow

from .const import DOMAIN
from .coordinator import WLEDDataUpdateCoordinator
from .models import WLEDEntity


@dataclass
class WLEDSensorEntityDescriptionMixin:
    """Mixin for required keys."""

    value_fn: Callable[[WLEDDevice], datetime | StateType]


@dataclass
class WLEDSensorEntityDescription(
    SensorEntityDescription, WLEDSensorEntityDescriptionMixin
):
    """Describes WLED sensor entity."""


SENSORS: tuple[WLEDSensorEntityDescription, ...] = (
    WLEDSensorEntityDescription(
        key="estimated_current",
        name="Estimated Current",
        native_unit_of_measurement=ELECTRIC_CURRENT_MILLIAMPERE,
        device_class=DEVICE_CLASS_CURRENT,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        value_fn=lambda device: device.info.leds.power,
    ),
    WLEDSensorEntityDescription(
        key="info_leds_count",
        name="LED Count",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        value_fn=lambda device: device.info.leds.count,
    ),
    WLEDSensorEntityDescription(
        key="info_leds_max_power",
        name="Max Current",
        native_unit_of_measurement=ELECTRIC_CURRENT_MILLIAMPERE,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        device_class=DEVICE_CLASS_CURRENT,
        value_fn=lambda device: device.info.leds.max_power,
    ),
    WLEDSensorEntityDescription(
        key="uptime",
        name="Uptime",
        device_class=DEVICE_CLASS_TIMESTAMP,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: (utcnow() - timedelta(seconds=device.info.uptime)),
    ),
    WLEDSensorEntityDescription(
        key="free_heap",
        name="Free Memory",
        icon="mdi:memory",
        native_unit_of_measurement=DATA_BYTES,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.free_heap,
    ),
    WLEDSensorEntityDescription(
        key="wifi_signal",
        name="Wi-Fi Signal",
        icon="mdi:wifi",
        native_unit_of_measurement=PERCENTAGE,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.signal if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_rssi",
        name="Wi-Fi RSSI",
        native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
        device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.rssi if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_channel",
        name="Wi-Fi Channel",
        icon="mdi:wifi",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.channel if device.info.wifi else None,
    ),
    WLEDSensorEntityDescription(
        key="wifi_bssid",
        name="Wi-Fi BSSID",
        icon="mdi:wifi",
        entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
        entity_registry_enabled_default=False,
        value_fn=lambda device: device.info.wifi.bssid if device.info.wifi else None,
    ),
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up WLED sensor based on a config entry."""
    coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    async_add_entities(
        WLEDSensorEntity(coordinator, description) for description in SENSORS
    )


class WLEDSensorEntity(WLEDEntity, SensorEntity):
    """Defines a WLED sensor entity."""

    entity_description: WLEDSensorEntityDescription

    def __init__(
        self,
        coordinator: WLEDDataUpdateCoordinator,
        description: WLEDSensorEntityDescription,
    ) -> None:
        """Initialize a WLED sensor entity."""
        super().__init__(coordinator=coordinator)
        self.entity_description = description
        self._attr_name = f"{coordinator.data.info.name} {description.name}"
        self._attr_unique_id = f"{coordinator.data.info.mac_address}_{description.key}"

    @property
    def native_value(self) -> datetime | StateType:
        """Return the state of the sensor."""
        return self.entity_description.value_fn(self.coordinator.data)
{'fraction_non_alphanumeric': 0.07965328467153285, 'fraction_numerical': 0.0005474452554744526, 'mean_word_length': 3.763581051716645, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3939412', 'n_tokens_mistral': 3479, 'n_tokens_neox': 3429, 'n_words': 565}