Add night light brightness level setting to VeSync (#137544)

This commit is contained in:
Indu Prakash 2025-02-13 05:45:09 -06:00 committed by GitHub
parent a8f4ab73ae
commit 6a26d59142
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 249 additions and 1 deletions

View File

@ -27,6 +27,7 @@ PLATFORMS = [
Platform.HUMIDIFIER,
Platform.LIGHT,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
]

View File

@ -29,6 +29,10 @@ VS_HUMIDIFIER_MODE_HUMIDITY = "humidity"
VS_HUMIDIFIER_MODE_MANUAL = "manual"
VS_HUMIDIFIER_MODE_SLEEP = "sleep"
NIGHT_LIGHT_LEVEL_BRIGHT = "bright"
NIGHT_LIGHT_LEVEL_DIM = "dim"
NIGHT_LIGHT_LEVEL_OFF = "off"
VeSyncHumidifierDevice = VeSyncHumid200300S | VeSyncSuperior6000S
"""Humidifier device types"""

View File

@ -0,0 +1,133 @@
"""Support for VeSync numeric entities."""
from collections.abc import Callable
from dataclasses import dataclass
import logging
from pyvesync.vesyncbasedevice import VeSyncBaseDevice
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .common import rgetattr
from .const import (
DOMAIN,
NIGHT_LIGHT_LEVEL_BRIGHT,
NIGHT_LIGHT_LEVEL_DIM,
NIGHT_LIGHT_LEVEL_OFF,
VS_COORDINATOR,
VS_DEVICES,
VS_DISCOVERY,
)
from .coordinator import VeSyncDataCoordinator
from .entity import VeSyncBaseEntity
_LOGGER = logging.getLogger(__name__)
VS_TO_HA_NIGHT_LIGHT_LEVEL_MAP = {
100: NIGHT_LIGHT_LEVEL_BRIGHT,
50: NIGHT_LIGHT_LEVEL_DIM,
0: NIGHT_LIGHT_LEVEL_OFF,
}
HA_TO_VS_NIGHT_LIGHT_LEVEL_MAP = {
v: k for k, v in VS_TO_HA_NIGHT_LIGHT_LEVEL_MAP.items()
}
@dataclass(frozen=True, kw_only=True)
class VeSyncSelectEntityDescription(SelectEntityDescription):
"""Class to describe a Vesync select entity."""
exists_fn: Callable[[VeSyncBaseDevice], bool]
current_option_fn: Callable[[VeSyncBaseDevice], str]
select_option_fn: Callable[[VeSyncBaseDevice, str], bool]
SELECT_DESCRIPTIONS: list[VeSyncSelectEntityDescription] = [
VeSyncSelectEntityDescription(
key="night_light_level",
translation_key="night_light_level",
options=list(VS_TO_HA_NIGHT_LIGHT_LEVEL_MAP.values()),
icon="mdi:brightness-6",
exists_fn=lambda device: rgetattr(device, "night_light"),
# The select_option service framework ensures that only options specified are
# accepted. ServiceValidationError gets raised for invalid value.
select_option_fn=lambda device, value: device.set_night_light_brightness(
HA_TO_VS_NIGHT_LIGHT_LEVEL_MAP.get(value, 0)
),
# Reporting "off" as the choice for unhandled level.
current_option_fn=lambda device: VS_TO_HA_NIGHT_LIGHT_LEVEL_MAP.get(
device.details.get("night_light_brightness"), NIGHT_LIGHT_LEVEL_OFF
),
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up select entities."""
coordinator = hass.data[DOMAIN][VS_COORDINATOR]
@callback
def discover(devices):
"""Add new devices to platform."""
_setup_entities(devices, async_add_entities, coordinator)
config_entry.async_on_unload(
async_dispatcher_connect(hass, VS_DISCOVERY.format(VS_DEVICES), discover)
)
_setup_entities(hass.data[DOMAIN][VS_DEVICES], async_add_entities, coordinator)
@callback
def _setup_entities(
devices: list[VeSyncBaseDevice],
async_add_entities: AddConfigEntryEntitiesCallback,
coordinator: VeSyncDataCoordinator,
):
"""Add select entities."""
async_add_entities(
VeSyncSelectEntity(dev, description, coordinator)
for dev in devices
for description in SELECT_DESCRIPTIONS
if description.exists_fn(dev)
)
class VeSyncSelectEntity(VeSyncBaseEntity, SelectEntity):
"""A class to set numeric options on Vesync device."""
entity_description: VeSyncSelectEntityDescription
def __init__(
self,
device: VeSyncBaseDevice,
description: VeSyncSelectEntityDescription,
coordinator: VeSyncDataCoordinator,
) -> None:
"""Initialize the VeSync select device."""
super().__init__(device, coordinator)
self.entity_description = description
self._attr_unique_id = f"{super().unique_id}-{description.key}"
@property
def current_option(self) -> str | None:
"""Return an option."""
return self.entity_description.current_option_fn(self.device)
async def async_select_option(self, option: str) -> None:
"""Set an option."""
if await self.hass.async_add_executor_job(
self.entity_description.select_option_fn, self.device, option
):
await self.coordinator.async_request_refresh()

View File

@ -56,6 +56,16 @@
"name": "Mist level"
}
},
"select": {
"night_light_level": {
"name": "Night light level",
"state": {
"bright": "Bright",
"dim": "Dim",
"off": "[%key:common::state::off%]"
}
}
},
"fan": {
"vesync": {
"state_attributes": {

View File

@ -13,6 +13,7 @@ from tests.common import load_fixture, load_json_object_fixture
ENTITY_HUMIDIFIER = "humidifier.humidifier_200s"
ENTITY_HUMIDIFIER_MIST_LEVEL = "number.humidifier_200s_mist_level"
ENTITY_HUMIDIFIER_HUMIDITY = "sensor.humidifier_200s_humidity"
ENTITY_HUMIDIFIER_300S_NIGHT_LIGHT_SELECT = "select.humidifier_300s_night_light_level"
ALL_DEVICES = load_json_object_fixture("vesync-devices.json", DOMAIN)
ALL_DEVICE_NAMES: list[str] = [

View File

@ -107,7 +107,7 @@ def outlet_fixture():
@pytest.fixture(name="humidifier")
def humidifier_fixture():
"""Create a mock VeSync humidifier fixture."""
"""Create a mock VeSync Classic200S humidifier fixture."""
return Mock(
VeSyncHumid200300S,
cid="200s-humidifier",
@ -135,6 +135,34 @@ def humidifier_fixture():
)
@pytest.fixture(name="humidifier_300s")
def humidifier_300s_fixture():
"""Create a mock VeSync Classic300S humidifier fixture."""
return Mock(
VeSyncHumid200300S,
cid="300s-humidifier",
config={
"auto_target_humidity": 40,
"display": "true",
"automatic_stop": "true",
},
details={"humidity": 35, "mode": "manual", "night_light_brightness": 50},
device_type="Classic300S",
device_name="Humidifier 300s",
device_status="on",
mist_level=6,
mist_modes=["auto", "manual"],
mode=None,
night_light=True,
sub_device_no=0,
config_module="configModule",
connection_status="online",
current_firm_version="1.0.0",
water_lacks=False,
water_tank_lifted=False,
)
@pytest.fixture(name="humidifier_config_entry")
async def humidifier_config_entry(
hass: HomeAssistant, requests_mock: requests_mock.Mocker, config
@ -155,6 +183,21 @@ async def humidifier_config_entry(
return entry
@pytest.fixture
async def install_humidifier_device(
hass: HomeAssistant,
config_entry: ConfigEntry,
manager,
request: pytest.FixtureRequest,
) -> None:
"""Create a mock VeSync config entry with the specified humidifier device."""
# Install the defined humidifier
manager._dev_list["fans"].append(request.getfixturevalue(request.param))
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@pytest.fixture(name="switch_old_id_config_entry")
async def switch_old_id_config_entry(
hass: HomeAssistant, requests_mock: requests_mock.Mocker, config

View File

@ -56,6 +56,7 @@ async def test_async_setup_entry__no_devices(
Platform.HUMIDIFIER,
Platform.LIGHT,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
]
@ -87,6 +88,7 @@ async def test_async_setup_entry__loads_fans(
Platform.HUMIDIFIER,
Platform.LIGHT,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
]

View File

@ -0,0 +1,54 @@
"""Tests for the select platform."""
import pytest
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.components.vesync.const import NIGHT_LIGHT_LEVEL_DIM
from homeassistant.components.vesync.select import HA_TO_VS_NIGHT_LIGHT_LEVEL_MAP
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from .common import ENTITY_HUMIDIFIER_300S_NIGHT_LIGHT_SELECT
@pytest.mark.parametrize(
"install_humidifier_device", ["humidifier_300s"], indirect=True
)
async def test_set_nightlight_level(
hass: HomeAssistant, manager, humidifier_300s, install_humidifier_device
) -> None:
"""Test set of night light level."""
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: ENTITY_HUMIDIFIER_300S_NIGHT_LIGHT_SELECT,
ATTR_OPTION: NIGHT_LIGHT_LEVEL_DIM,
},
blocking=True,
)
# Assert that setter API was invoked with the expected translated value
humidifier_300s.set_night_light_brightness.assert_called_once_with(
HA_TO_VS_NIGHT_LIGHT_LEVEL_MAP[NIGHT_LIGHT_LEVEL_DIM]
)
# Assert that devices were refreshed
manager.update_all_devices.assert_called_once()
@pytest.mark.parametrize(
"install_humidifier_device", ["humidifier_300s"], indirect=True
)
async def test_nightlight_level(hass: HomeAssistant, install_humidifier_device) -> None:
"""Test the state of night light level select entity."""
# The mocked device has night_light_brightness=50 which is "dim"
assert (
hass.states.get(ENTITY_HUMIDIFIER_300S_NIGHT_LIGHT_SELECT).state
== NIGHT_LIGHT_LEVEL_DIM
)