diff --git a/homeassistant/components/switchbot/__init__.py b/homeassistant/components/switchbot/__init__.py index 790bc512dcb8..bbab2feda8bb 100644 --- a/homeassistant/components/switchbot/__init__.py +++ b/homeassistant/components/switchbot/__init__.py @@ -103,6 +103,12 @@ PLATFORMS_BY_TYPE = { Platform.SWITCH, Platform.SENSOR, ], + SupportedModels.CIRCULATOR_FAN_PRO.value: [ + Platform.FAN, + Platform.LIGHT, + Platform.SENSOR, + Platform.SWITCH, + ], SupportedModels.S10_VACUUM.value: [Platform.VACUUM, Platform.SENSOR], SupportedModels.S20_VACUUM.value: [Platform.VACUUM, Platform.SENSOR], SupportedModels.K10_VACUUM.value: [Platform.VACUUM, Platform.SENSOR], @@ -228,6 +234,7 @@ CLASS_BY_DEVICE = { SupportedModels.ROLLER_SHADE.value: switchbot.SwitchbotRollerShade, SupportedModels.CIRCULATOR_FAN.value: switchbot.SwitchbotFan, SupportedModels.STANDING_FAN.value: switchbot.SwitchbotStandingFan, + SupportedModels.CIRCULATOR_FAN_PRO.value: switchbot.SwitchbotCirculatorFanPro, SupportedModels.UNIVERSAL_REMOTE.value: switchbot.SwitchbotUniversalRemote, SupportedModels.S10_VACUUM.value: switchbot.SwitchbotVacuum, SupportedModels.S20_VACUUM.value: switchbot.SwitchbotVacuum, diff --git a/homeassistant/components/switchbot/const.py b/homeassistant/components/switchbot/const.py index e6e299d92963..491f03089cd8 100644 --- a/homeassistant/components/switchbot/const.py +++ b/homeassistant/components/switchbot/const.py @@ -39,6 +39,7 @@ class SupportedModels(StrEnum): ROLLER_SHADE = "roller_shade" HUBMINI_MATTER = "hubmini_matter" CIRCULATOR_FAN = "circulator_fan" + CIRCULATOR_FAN_PRO = "circulator_fan_pro" K20_VACUUM = "k20_vacuum" S10_VACUUM = "s10_vacuum" K10_VACUUM = "k10_vacuum" @@ -96,6 +97,7 @@ CONNECTABLE_SUPPORTED_MODEL_TYPES = { SwitchbotModel.RELAY_SWITCH_1: SupportedModels.RELAY_SWITCH_1, SwitchbotModel.ROLLER_SHADE: SupportedModels.ROLLER_SHADE, SwitchbotModel.CIRCULATOR_FAN: SupportedModels.CIRCULATOR_FAN, + SwitchbotModel.CIRCULATOR_FAN_PRO: SupportedModels.CIRCULATOR_FAN_PRO, SwitchbotModel.K20_VACUUM: SupportedModels.K20_VACUUM, SwitchbotModel.S10_VACUUM: SupportedModels.S10_VACUUM, SwitchbotModel.S20_VACUUM: SupportedModels.S20_VACUUM, @@ -188,6 +190,7 @@ ENCRYPTED_MODELS = { SwitchbotModel.LOCK_VISION, SwitchbotModel.LOCK_PRO_WIFI, SwitchbotModel.CANDLE_WARMER_LAMP, + SwitchbotModel.CIRCULATOR_FAN_PRO, SwitchbotModel.RGBIC_NEON_ROPE_LIGHT, SwitchbotModel.RGBIC_NEON_WIRE_ROPE_LIGHT, } @@ -226,6 +229,7 @@ ENCRYPTED_SWITCHBOT_MODEL_TO_CLASS: dict[ SwitchbotModel.LOCK_VISION: switchbot.SwitchbotLock, SwitchbotModel.LOCK_PRO_WIFI: switchbot.SwitchbotLock, SwitchbotModel.CANDLE_WARMER_LAMP: switchbot.SwitchbotCandleWarmerLamp, + SwitchbotModel.CIRCULATOR_FAN_PRO: switchbot.SwitchbotCirculatorFanPro, SwitchbotModel.RGBIC_NEON_ROPE_LIGHT: switchbot.SwitchbotRgbicNeonLight, SwitchbotModel.RGBIC_NEON_WIRE_ROPE_LIGHT: switchbot.SwitchbotRgbicNeonLight, } diff --git a/homeassistant/components/switchbot/fan.py b/homeassistant/components/switchbot/fan.py index ee919f6b3ef2..7f07131f31ee 100644 --- a/homeassistant/components/switchbot/fan.py +++ b/homeassistant/components/switchbot/fan.py @@ -5,7 +5,7 @@ import logging from typing import Any, override import switchbot -from switchbot import AirPurifierMode, FanMode, StandingFanMode +from switchbot import AirPurifierMode, StandingFanMode from homeassistant.components.fan import FanEntity, FanEntityFeature from homeassistant.core import HomeAssistant @@ -47,7 +47,6 @@ class SwitchBotFanEntity(SwitchbotEntity, FanEntity, RestoreEntity): | FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON ) - _attr_preset_modes = FanMode.get_modes() _attr_translation_key = "fan" _attr_name = None @@ -55,6 +54,7 @@ class SwitchBotFanEntity(SwitchbotEntity, FanEntity, RestoreEntity): """Initialize the switchbot.""" super().__init__(coordinator) self._attr_is_on = False + self._attr_preset_modes = self._device.fan_modes @property @override diff --git a/homeassistant/components/switchbot/light.py b/homeassistant/components/switchbot/light.py index 9b6864f5ed28..c57c0ed65426 100644 --- a/homeassistant/components/switchbot/light.py +++ b/homeassistant/components/switchbot/light.py @@ -42,6 +42,8 @@ async def async_setup_entry( coordinator = entry.runtime_data if isinstance(coordinator.device, switchbot.SwitchbotAirPurifier): async_add_entities([SwitchbotAirPurifierLightEntity(coordinator)]) + elif isinstance(coordinator.device, switchbot.SwitchbotCirculatorFanPro): + async_add_entities([SwitchbotCirculatorFanProLightEntity(coordinator)]) else: async_add_entities([SwitchbotLightEntity(coordinator)]) @@ -227,3 +229,57 @@ class SwitchbotLightEntity(SwitchbotEntity, LightEntity): """Instruct the light to turn off.""" _LOGGER.debug("Turning off light %s, address %s", kwargs, self._address) await self._device.turn_off() + + +class SwitchbotCirculatorFanProLightEntity(SwitchbotEntity, LightEntity): + """Two-level night light of a Circulator Fan Pro. + + The night light has two brightness levels (high / low), mapped onto HA + brightness: values up to 128 select the low level. + """ + + _device: switchbot.SwitchbotCirculatorFanPro + _attr_translation_key = "circulator_fan_pro_light" + _attr_supported_color_modes = {ColorMode.BRIGHTNESS} + _attr_color_mode = ColorMode.BRIGHTNESS + + def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None: + """Initialize the Circulator Fan Pro night light.""" + super().__init__(coordinator) + self._attr_unique_id = f"{coordinator.base_unique_id}_light" # pylint: disable=home-assistant-entity-unique-id-redundant-platform + + @property + @override + def is_on(self) -> bool | None: + """Return true if the night light is on.""" + return self._device.is_night_light_on() + + @property + @override + def brightness(self) -> int | None: + """Return HA brightness for the night light's two hardware levels. + + The device reports level 1 (high) or level 2 (low); these map to HA + brightness 255 and 128 respectively. Returns None when unavailable. + """ + level = self._device.get_night_light_level() + if not level: + return None + return 128 if level == 2 else 255 + + @exception_handler + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Turn the night light on (picking high/low from the requested brightness).""" + _LOGGER.debug("Turning on night light %s, address %s", kwargs, self._address) + low = ( + requested := kwargs.get(ATTR_BRIGHTNESS) + ) is not None and requested <= 128 + await self._device.turn_on_light(low=low) + + @exception_handler + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Turn the night light off.""" + _LOGGER.debug("Turning off night light %s, address %s", kwargs, self._address) + await self._device.turn_off_light() diff --git a/homeassistant/components/switchbot/strings.json b/homeassistant/components/switchbot/strings.json index 9034516c0409..35e246ad14df 100644 --- a/homeassistant/components/switchbot/strings.json +++ b/homeassistant/components/switchbot/strings.json @@ -215,6 +215,7 @@ "preset_mode": { "state": { "baby": "Baby", + "hurricane": "Hurricane", "natural": "Natural", "normal": "[%key:common::state::normal%]", "sleep": "Sleep" @@ -268,6 +269,9 @@ "air_purifier_light": { "name": "[%key:component::light::title%]" }, + "circulator_fan_pro_light": { + "name": "[%key:component::light::title%]" + }, "light": { "state_attributes": { "effect": { diff --git a/homeassistant/components/switchbot/switch.py b/homeassistant/components/switchbot/switch.py index 864b2d11ef9c..148c40609e0f 100644 --- a/homeassistant/components/switchbot/switch.py +++ b/homeassistant/components/switchbot/switch.py @@ -56,6 +56,17 @@ AIRPURIFIER_TABLE_SWITCHES: tuple[SwitchbotSwitchEntityDescription, ...] = ( ), ) +CIRCULATOR_FAN_PRO_SWITCHES: tuple[SwitchbotSwitchEntityDescription, ...] = ( + SwitchbotSwitchEntityDescription( + key="vertical_oscillation", + translation_key="vertical_oscillation", + device_class=SwitchDeviceClass.SWITCH, + is_on_fn=lambda device: device.get_vertical_oscillating_state(), + turn_on_fn=lambda device: device.set_vertical_oscillation(True), + turn_off_fn=lambda device: device.set_vertical_oscillation(False), + ), +) + PARALLEL_UPDATES = 0 _LOGGER = logging.getLogger(__name__) @@ -95,6 +106,11 @@ async def async_setup_entry( SwitchbotFanVerticalOscillationSwitch(coordinator), ] ) + elif isinstance(coordinator.device, switchbot.SwitchbotCirculatorFanPro): + async_add_entities( + SwitchbotGenericSwitch(coordinator, desc) + for desc in CIRCULATOR_FAN_PRO_SWITCHES + ) else: async_add_entities([SwitchBotSwitch(coordinator)]) diff --git a/tests/components/switchbot/__init__.py b/tests/components/switchbot/__init__.py index 01dd3b7278c5..b21950699f8b 100644 --- a/tests/components/switchbot/__init__.py +++ b/tests/components/switchbot/__init__.py @@ -589,6 +589,33 @@ CIRCULATOR_FAN_SERVICE_INFO = BluetoothServiceInfoBleak( ) +CIRCULATOR_FAN_PRO_SERVICE_INFO = BluetoothServiceInfoBleak( + name="Circulator Fan Pro", + manufacturer_data={ + 2409: b"\xb0\xe9\xfe\xfd\xc0\xb1\x9a\xd9\x98\x0b\x00\x00\x00\x00\x00\x00", + }, + service_data={"0000fd3d-0000-1000-8000-00805f9b34fb": b"\x00\x00Y\x00\x11\xb3@"}, + service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], + address="AA:BB:CC:DD:EE:FF", + rssi=-60, + source="local", + advertisement=generate_advertisement_data( + local_name="Circulator Fan Pro", + manufacturer_data={ + 2409: b"\xb0\xe9\xfe\xfd\xc0\xb1\x9a\xd9\x98\x0b\x00\x00\x00\x00\x00\x00", + }, + service_data={ + "0000fd3d-0000-1000-8000-00805f9b34fb": b"\x00\x00Y\x00\x11\xb3@" + }, + service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], + ), + device=generate_ble_device("AA:BB:CC:DD:EE:FF", "Circulator Fan Pro"), + time=0, + connectable=True, + tx_power=-127, +) + + UNIVERSAL_REMOTE_SERVICE_INFO = BluetoothServiceInfoBleak( name="Universal Remote", manufacturer_data={ diff --git a/tests/components/switchbot/test_config_flow.py b/tests/components/switchbot/test_config_flow.py index 54c742ccd3bf..26e9aa004a65 100644 --- a/tests/components/switchbot/test_config_flow.py +++ b/tests/components/switchbot/test_config_flow.py @@ -26,6 +26,7 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from . import ( + CIRCULATOR_FAN_PRO_SERVICE_INFO, LOCK_ULTRA_MAX_SERVICE_INFO, NOT_SWITCHBOT_INFO, USER_INPUT, @@ -214,6 +215,43 @@ async def test_bluetooth_discovery_lock_ultra_max(hass: HomeAssistant) -> None: assert len(mock_setup_entry.mock_calls) == 1 +async def test_bluetooth_discovery_circulator_fan_pro(hass: HomeAssistant) -> None: + """Test discovery of an encrypted Circulator Fan Pro.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_BLUETOOTH}, + data=CIRCULATOR_FAN_PRO_SERVICE_INFO, + ) + assert result["type"] is FlowResultType.MENU + assert result["step_id"] == "encrypted_choose_method" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "encrypted_key"} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "encrypted_key" + + with ( + patch_async_setup_entry() as mock_setup_entry, + patch( + "switchbot.SwitchbotCirculatorFanPro.verify_encryption_key", + return_value=True, + ), + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_KEY_ID: "ff", + CONF_ENCRYPTION_KEY: "ffffffffffffffffffffffffffffffff", + }, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_SENSOR_TYPE] == "circulator_fan_pro" + assert len(mock_setup_entry.mock_calls) == 1 + + async def test_bluetooth_discovery_key(hass: HomeAssistant) -> None: """Test discovery via bluetooth with a encrypted device.""" result = await hass.config_entries.flow.async_init( diff --git a/tests/components/switchbot/test_fan.py b/tests/components/switchbot/test_fan.py index b39cba0b788a..c8bf0d162d02 100644 --- a/tests/components/switchbot/test_fan.py +++ b/tests/components/switchbot/test_fan.py @@ -25,6 +25,7 @@ from . import ( AIR_PURIFIER_TABLE_JP_SERVICE_INFO, AIR_PURIFIER_TABLE_US_SERVICE_INFO, AIR_PURIFIER_US_SERVICE_INFO, + CIRCULATOR_FAN_PRO_SERVICE_INFO, CIRCULATOR_FAN_SERVICE_INFO, STANDING_FAN_SERVICE_INFO, ) @@ -235,6 +236,57 @@ async def test_exception_handling_air_purifier_service( ) +@pytest.mark.parametrize( + ("service", "service_data", "mock_method", "expected_call"), + [ + ( + SERVICE_SET_PRESET_MODE, + {ATTR_PRESET_MODE: "hurricane"}, + "set_preset_mode", + ("hurricane",), + ), + (SERVICE_SET_PERCENTAGE, {ATTR_PERCENTAGE: 27}, "set_percentage", (27,)), + (SERVICE_OSCILLATE, {ATTR_OSCILLATING: True}, "set_oscillation", (True,)), + (SERVICE_TURN_OFF, {}, "turn_off", ()), + (SERVICE_TURN_ON, {}, "turn_on", ()), + ], +) +async def test_circulator_fan_pro_controlling( + hass: HomeAssistant, + mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], + service: str, + service_data: dict, + mock_method: str, + expected_call: tuple, +) -> None: + """Test controlling the encrypted Circulator Fan Pro fan.""" + inject_bluetooth_service_info(hass, CIRCULATOR_FAN_PRO_SERVICE_INFO) + + entry = mock_entry_encrypted_factory(sensor_type="circulator_fan_pro") + entity_id = "fan.test_name" + entry.add_to_hass(hass) + + mocked_instance = AsyncMock(return_value=True) + mocked_none_instance = AsyncMock(return_value=None) + with patch.multiple( + "homeassistant.components.switchbot.fan.switchbot.SwitchbotCirculatorFanPro", + get_basic_info=mocked_none_instance, + update=mocked_none_instance, + **{mock_method: mocked_instance}, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + await hass.services.async_call( + FAN_DOMAIN, + service, + {**service_data, ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + mocked_instance.assert_awaited_once_with(*expected_call) + + @pytest.mark.parametrize( ("service", "service_data", "mock_method", "expected_call"), [ diff --git a/tests/components/switchbot/test_light.py b/tests/components/switchbot/test_light.py index e62a990cab70..b980b3002399 100644 --- a/tests/components/switchbot/test_light.py +++ b/tests/components/switchbot/test_light.py @@ -17,9 +17,10 @@ from homeassistant.components.light import ( SERVICE_TURN_OFF, SERVICE_TURN_ON, ) -from homeassistant.const import ATTR_ENTITY_ID, STATE_ON +from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, State from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er from . import ( AIR_PURIFIER_JP_SERVICE_INFO, @@ -29,6 +30,7 @@ from . import ( BULB_SERVICE_INFO, CANDLE_WARMER_LAMP_SERVICE_INFO, CEILING_LIGHT_SERVICE_INFO, + CIRCULATOR_FAN_PRO_SERVICE_INFO, FLOOR_LAMP_SERVICE_INFO, PERMANENT_OUTDOOR_LIGHT_SERVICE_INFO, RGBIC_NEON_LIGHT_SERVICE_INFO, @@ -726,3 +728,94 @@ async def test_air_purifier_light_restore_state( assert state.attributes.get(ATTR_BRIGHTNESS) == 13 assert state.attributes.get(ATTR_RGB_COLOR) == (2, 3, 4) + + +@pytest.mark.parametrize( + ("service", "service_data", "mock_method", "expected_kwargs"), + [ + (SERVICE_TURN_ON, {}, "turn_on_light", {"low": False}), + (SERVICE_TURN_ON, {ATTR_BRIGHTNESS: 255}, "turn_on_light", {"low": False}), + (SERVICE_TURN_ON, {ATTR_BRIGHTNESS: 128}, "turn_on_light", {"low": True}), + (SERVICE_TURN_ON, {ATTR_BRIGHTNESS: 100}, "turn_on_light", {"low": True}), + (SERVICE_TURN_OFF, {}, "turn_off_light", {}), + ], +) +async def test_circulator_fan_pro_light_services( + hass: HomeAssistant, + mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], + service: str, + service_data: dict, + mock_method: str, + expected_kwargs: dict, +) -> None: + """Test the Circulator Fan Pro night-light services.""" + inject_bluetooth_service_info(hass, CIRCULATOR_FAN_PRO_SERVICE_INFO) + + entry = mock_entry_encrypted_factory(sensor_type="circulator_fan_pro") + entry.add_to_hass(hass) + entity_id = "light.test_name_light" + + mocked_instance = AsyncMock(return_value=True) + mocked_none_instance = AsyncMock(return_value=None) + + with patch.multiple( + "homeassistant.components.switchbot.light.switchbot.SwitchbotCirculatorFanPro", + **{mock_method: mocked_instance}, + get_basic_info=mocked_none_instance, + update=mocked_none_instance, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + await hass.services.async_call( + LIGHT_DOMAIN, + service, + {**service_data, ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + mocked_instance.assert_awaited_once_with(**expected_kwargs) + + +@pytest.mark.parametrize( + ("is_on", "level", "expected_state", "expected_brightness"), + [ + pytest.param(True, 1, STATE_ON, 255, id="high"), + pytest.param(True, 2, STATE_ON, 128, id="low"), + pytest.param(False, 0, STATE_OFF, None, id="off"), + ], +) +async def test_circulator_fan_pro_light_state( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], + is_on: bool, + level: int, + expected_state: str, + expected_brightness: int | None, +) -> None: + """Test the Circulator Fan Pro night-light states.""" + inject_bluetooth_service_info(hass, CIRCULATOR_FAN_PRO_SERVICE_INFO) + + entry = mock_entry_encrypted_factory(sensor_type="circulator_fan_pro") + entry.add_to_hass(hass) + entity_id = "light.test_name_light" + + with patch.multiple( + "homeassistant.components.switchbot.light.switchbot.SwitchbotCirculatorFanPro", + is_night_light_on=lambda self: is_on, + get_night_light_level=lambda self: level, + get_basic_info=AsyncMock(return_value=None), + update=AsyncMock(return_value=None), + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(entity_id) + assert state is not None + assert state.state == expected_state + assert state.attributes.get(ATTR_BRIGHTNESS) == expected_brightness + assert hass.states.get("sensor.test_name_battery") is not None + assert ( + entity_registry.async_get("sensor.test_name_bluetooth_signal") is not None + ) diff --git a/tests/components/switchbot/test_switch.py b/tests/components/switchbot/test_switch.py index fdbd43206c2a..313e48ff9922 100644 --- a/tests/components/switchbot/test_switch.py +++ b/tests/components/switchbot/test_switch.py @@ -22,6 +22,7 @@ from . import ( AIR_PURIFIER_TABLE_JP_SERVICE_INFO, AIR_PURIFIER_TABLE_US_SERVICE_INFO, AIR_PURIFIER_US_SERVICE_INFO, + CIRCULATOR_FAN_PRO_SERVICE_INFO, PLUG_MINI_EU_SERVICE_INFO, RELAY_SWITCH_1_SERVICE_INFO, RELAY_SWITCH_2PM_SERVICE_INFO, @@ -455,3 +456,43 @@ async def test_standing_fan_oscillation_switches( ) assert mocked_set.await_count == 2 mocked_set.assert_awaited_with(False) + + +@pytest.mark.parametrize( + ("service", "mock_method", "expected_arg"), + [ + (SERVICE_TURN_ON, "set_vertical_oscillation", True), + (SERVICE_TURN_OFF, "set_vertical_oscillation", False), + ], +) +async def test_circulator_fan_pro_vertical_oscillation_switch( + hass: HomeAssistant, + mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], + service: str, + mock_method: str, + expected_arg: bool, +) -> None: + """Test the Circulator Fan Pro vertical oscillation switch.""" + inject_bluetooth_service_info(hass, CIRCULATOR_FAN_PRO_SERVICE_INFO) + + entry = mock_entry_encrypted_factory(sensor_type="circulator_fan_pro") + entry.add_to_hass(hass) + + mocked_instance = AsyncMock(return_value=True) + with patch.multiple( + "homeassistant.components.switchbot.switch.switchbot.SwitchbotCirculatorFanPro", + get_basic_info=AsyncMock(return_value=None), + update=AsyncMock(return_value=None), + **{mock_method: mocked_instance}, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + await hass.services.async_call( + SWITCH_DOMAIN, + service, + {ATTR_ENTITY_ID: "switch.test_name_vertical_oscillation"}, + blocking=True, + ) + + mocked_instance.assert_awaited_once_with(expected_arg)