diff --git a/.strict-typing b/.strict-typing index 6947f186a49e4a..525d0d1477e8ed 100644 --- a/.strict-typing +++ b/.strict-typing @@ -371,6 +371,7 @@ homeassistant.components.kulersky.* homeassistant.components.labs.* homeassistant.components.lacrosse.* homeassistant.components.lacrosse_view.* +homeassistant.components.laifen.* homeassistant.components.lamarzocco.* homeassistant.components.lametric.* homeassistant.components.laundrify.* diff --git a/CODEOWNERS b/CODEOWNERS index 1a2d8272226b4b..56ed8bf7911216 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1077,6 +1077,8 @@ AGENTS.md @home-assistant/core /tests/components/labs/ @home-assistant/core /homeassistant/components/lacrosse_view/ @IceBotYT /tests/components/lacrosse_view/ @IceBotYT +/homeassistant/components/laifen/ @bzumik1 @UrbanTechIO +/tests/components/laifen/ @bzumik1 @UrbanTechIO /homeassistant/components/lamarzocco/ @zweckj /tests/components/lamarzocco/ @zweckj /homeassistant/components/lametric/ @robbiet480 @frenck @bachya diff --git a/homeassistant/components/laifen/__init__.py b/homeassistant/components/laifen/__init__.py new file mode 100644 index 00000000000000..3fb0519e580021 --- /dev/null +++ b/homeassistant/components/laifen/__init__.py @@ -0,0 +1,44 @@ +"""The Laifen integration.""" + +from laifen_ble import LaifenToothbrush + +from homeassistant.const import CONF_ADDRESS, EVENT_HOMEASSISTANT_STOP, Platform +from homeassistant.core import Event, HomeAssistant +from homeassistant.helpers import device_registry as dr + +from .const import DOMAIN +from .coordinator import LaifenConfigEntry, LaifenCoordinator + +PLATFORMS: list[Platform] = [Platform.SENSOR] + + +async def async_setup_entry(hass: HomeAssistant, entry: LaifenConfigEntry) -> None: + """Set up Laifen from a config entry.""" + address: str = entry.data[CONF_ADDRESS] + device = dr.async_get(hass).async_get_or_create( + config_entry_id=entry.entry_id, + identifiers={(DOMAIN, address)}, + connections={(dr.CONNECTION_BLUETOOTH, address)}, + manufacturer="Laifen", + model="Wave", + model_id="LFTB01-P", + name=entry.title, + ) + toothbrush = LaifenToothbrush(address) + coordinator = LaifenCoordinator(hass, entry, toothbrush, device.id) + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + + async def _async_disconnect(event: Event) -> None: + """Disconnect from the toothbrush when Home Assistant stops.""" + await toothbrush.disconnect() + + entry.async_on_unload( + hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, _async_disconnect) + ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + +async def async_unload_entry(hass: HomeAssistant, entry: LaifenConfigEntry) -> None: + """Unload a config entry.""" + await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) diff --git a/homeassistant/components/laifen/config_flow.py b/homeassistant/components/laifen/config_flow.py new file mode 100644 index 00000000000000..7ed830ae7a8cbb --- /dev/null +++ b/homeassistant/components/laifen/config_flow.py @@ -0,0 +1,124 @@ +"""Config flow for the Laifen integration.""" + +from typing import TYPE_CHECKING, Any, override + +from laifen_ble import ( + LaifenConnectionError, + LaifenToothbrush, + UnsupportedStateError, + is_supported, +) +import probatio + +from homeassistant.components.bluetooth import ( + BluetoothServiceInfoBleak, + async_ble_device_from_address, + async_discovered_service_info, +) +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.const import CONF_ADDRESS +from homeassistant.data_entry_flow import AbortFlow + +from .const import DOMAIN + + +class LaifenConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for Laifen.""" + + def __init__(self) -> None: + """Initialize the config flow.""" + self._discovery_info: BluetoothServiceInfoBleak | None = None + self._discovered_devices: dict[str, BluetoothServiceInfoBleak] = {} + + async def _async_can_connect(self, address: str) -> bool: + """Return whether the toothbrush can be connected to.""" + ble_device = async_ble_device_from_address(self.hass, address, connectable=True) + if ble_device is None: + return False + toothbrush = LaifenToothbrush(ble_device) + try: + await toothbrush.connect() + except UnsupportedStateError as err: + raise AbortFlow("unsupported_firmware") from err + except LaifenConnectionError: + return False + await toothbrush.disconnect() + return True + + @override + async def async_step_bluetooth( + self, discovery_info: BluetoothServiceInfoBleak + ) -> ConfigFlowResult: + """Handle a discovered toothbrush.""" + await self.async_set_unique_id(discovery_info.address) + self._abort_if_unique_id_configured() + self._discovery_info = discovery_info + self.context["title_placeholders"] = {"name": discovery_info.name} + return await self.async_step_bluetooth_confirm() + + async def async_step_bluetooth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm the discovered toothbrush.""" + discovery_info = self._discovery_info + if TYPE_CHECKING: + assert discovery_info is not None + errors: dict[str, str] = {} + if user_input is not None: + if await self._async_can_connect(discovery_info.address): + return self.async_create_entry( + title=discovery_info.name, + data={CONF_ADDRESS: discovery_info.address}, + ) + errors["base"] = "cannot_connect" + return self.async_show_form( + step_id="bluetooth_confirm", + description_placeholders={"name": discovery_info.name}, + errors=errors, + ) + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Pick a discovered toothbrush.""" + errors: dict[str, str] = {} + if user_input is not None: + address = user_input[CONF_ADDRESS] + await self.async_set_unique_id(address, raise_on_progress=False) + self._abort_if_unique_id_configured() + if await self._async_can_connect(address): + return self.async_create_entry( + title=self._discovered_devices[address].name, + data={CONF_ADDRESS: address}, + ) + errors["base"] = "cannot_connect" + + current_addresses = self._async_current_ids(include_ignore=False) + for discovery_info in async_discovered_service_info(self.hass): + address = discovery_info.address + if ( + address in current_addresses + or address in self._discovered_devices + or not is_supported(discovery_info.name) + ): + continue + self._discovered_devices[address] = discovery_info + + if not self._discovered_devices: + return self.async_abort(reason="no_devices_found") + + return self.async_show_form( + step_id="user", + data_schema=probatio.Schema( + { + probatio.Required(CONF_ADDRESS): probatio.In( + { + address: f"{discovery_info.name} ({address})" + for address, discovery_info in self._discovered_devices.items() + } + ) + } + ), + errors=errors, + ) diff --git a/homeassistant/components/laifen/const.py b/homeassistant/components/laifen/const.py new file mode 100644 index 00000000000000..3180f66ef02e69 --- /dev/null +++ b/homeassistant/components/laifen/const.py @@ -0,0 +1,3 @@ +"""Constants for the Laifen integration.""" + +DOMAIN = "laifen" diff --git a/homeassistant/components/laifen/coordinator.py b/homeassistant/components/laifen/coordinator.py new file mode 100644 index 00000000000000..ee79fe40094509 --- /dev/null +++ b/homeassistant/components/laifen/coordinator.py @@ -0,0 +1,169 @@ +"""Coordinator for the Laifen integration.""" + +from datetime import timedelta +import logging +from typing import override + +from laifen_ble import LaifenConnectionError, LaifenToothbrush, UnsupportedStateError + +from homeassistant.components.bluetooth import ( + MONOTONIC_TIME, + BluetoothCallbackMatcher, + BluetoothCallbackReplay, + BluetoothChange, + BluetoothReachabilityIntent, + BluetoothScanningMode, + BluetoothServiceInfoBleak, + async_address_reachability_diagnostics, + async_clear_advertisement_history, + async_last_service_info, + async_register_callback, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator + +_LOGGER = logging.getLogger(__name__) + +UPDATE_INTERVAL = timedelta(minutes=1) +ADVERTISEMENT_MAX_AGE = 30 + +type LaifenConfigEntry = ConfigEntry[LaifenCoordinator] + + +class LaifenCoordinator(DataUpdateCoordinator[None]): + """Connect to a Laifen toothbrush whenever it is awake. + + The toothbrush advertises the same data whenever it wakes up, so the + advertisement history is cleared at setup and after every connection to + hear the next wake-up. Its state is pushed over the connection, except for + the battery level, which is read every minute while it stays connected on + its charger. + """ + + config_entry: LaifenConfigEntry + + def __init__( + self, + hass: HomeAssistant, + config_entry: LaifenConfigEntry, + toothbrush: LaifenToothbrush, + device_id: str, + ) -> None: + """Initialize the coordinator.""" + super().__init__( + hass, + _LOGGER, + config_entry=config_entry, + name=config_entry.title, + ) + self.toothbrush = toothbrush + self.device_id = device_id + self._connected = False + self._firmware_version: str | None = None + + @override + async def _async_setup(self) -> None: + """Listen to the toothbrush and to its advertisements.""" + self.config_entry.async_on_unload( + self.toothbrush.register_callback(self._async_handle_toothbrush_update) + ) + self.config_entry.async_on_unload( + async_register_callback( + self.hass, + self._async_handle_advertisement, + BluetoothCallbackMatcher( + address=self.toothbrush.address, connectable=True + ), + BluetoothScanningMode.PASSIVE, + replay=BluetoothCallbackReplay.DISABLED, + ) + ) + async_clear_advertisement_history(self.hass, self.toothbrush.address) + + @callback + def _async_handle_advertisement( + self, service_info: BluetoothServiceInfoBleak, change: BluetoothChange + ) -> None: + """Connect when the toothbrush wakes up and advertises.""" + if self.hass.is_stopping or self.toothbrush.connected: + return + self.config_entry.async_create_background_task( + self.hass, self.async_request_refresh(), "laifen connect" + ) + + @callback + def _async_handle_toothbrush_update(self) -> None: + """Handle a change of the toothbrush or of its connection.""" + if self.hass.is_stopping: + return + connected = self.toothbrush.connected + if connected != self._connected: + self._connected = connected + if connected: + _LOGGER.info("Connected to %s", self.toothbrush.name) + self.update_interval = UPDATE_INTERVAL + else: + _LOGGER.info("%s is asleep or out of range", self.toothbrush.name) + self.update_interval = None + async_clear_advertisement_history(self.hass, self.toothbrush.address) + self._async_update_firmware_version() + self.async_set_updated_data(None) + + @callback + def _async_update_firmware_version(self) -> None: + """Store the firmware version on the device.""" + firmware_version = self.toothbrush.firmware_version + if firmware_version is None or firmware_version == self._firmware_version: + return + self._firmware_version = firmware_version + dr.async_get(self.hass).async_update_device( + self.device_id, sw_version=firmware_version + ) + + @override + async def _async_update_data(self) -> None: + """Read the state of a connected toothbrush, or connect if it is awake.""" + if self.hass.is_stopping: + return + if self.toothbrush.connected: + try: + await self.toothbrush.update() + except LaifenConnectionError as err: + _LOGGER.debug("Could not update %s: %s", self.toothbrush.name, err) + await self.toothbrush.disconnect() + return + service_info = async_last_service_info( + self.hass, self.toothbrush.address, connectable=True + ) + if service_info is None: + return + if MONOTONIC_TIME() - service_info.time > ADVERTISEMENT_MAX_AGE: + async_clear_advertisement_history(self.hass, self.toothbrush.address) + return + self.toothbrush.set_ble_device(service_info.device) + try: + await self.toothbrush.connect() + except UnsupportedStateError as err: + _LOGGER.warning( + "%s sends a state that is not supported: %s", self.toothbrush.name, err + ) + except LaifenConnectionError as err: + _LOGGER.debug( + "Could not connect to %s: %s (%s)", + self.toothbrush.name, + err, + async_address_reachability_diagnostics( + self.hass, + self.toothbrush.address, + BluetoothReachabilityIntent.CONNECTION, + ), + ) + async_clear_advertisement_history(self.hass, self.toothbrush.address) + + @override + async def async_shutdown(self) -> None: + """Disconnect from the toothbrush.""" + await super().async_shutdown() + await self.toothbrush.disconnect() diff --git a/homeassistant/components/laifen/entity.py b/homeassistant/components/laifen/entity.py new file mode 100644 index 00000000000000..4dd4acf7274fe5 --- /dev/null +++ b/homeassistant/components/laifen/entity.py @@ -0,0 +1,33 @@ +"""Base entity for the Laifen integration.""" + +from laifen_ble import LaifenToothbrush + +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import EntityDescription +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .const import DOMAIN +from .coordinator import LaifenCoordinator + + +class LaifenEntity(CoordinatorEntity[LaifenCoordinator]): + """Base class for Laifen entities.""" + + _attr_has_entity_name = True + + def __init__( + self, + coordinator: LaifenCoordinator, + entity_description: EntityDescription, + ) -> None: + """Initialize the entity.""" + super().__init__(coordinator) + self.entity_description = entity_description + address = coordinator.toothbrush.address + self._attr_unique_id = f"{address}_{entity_description.key}" + self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, address)}) + + @property + def toothbrush(self) -> LaifenToothbrush: + """Return the toothbrush.""" + return self.coordinator.toothbrush diff --git a/homeassistant/components/laifen/icons.json b/homeassistant/components/laifen/icons.json new file mode 100644 index 00000000000000..894cf360491fdf --- /dev/null +++ b/homeassistant/components/laifen/icons.json @@ -0,0 +1,12 @@ +{ + "entity": { + "sensor": { + "current_brushing_duration": { + "default": "mdi:timer" + }, + "last_brushing_duration": { + "default": "mdi:timer-outline" + } + } + } +} diff --git a/homeassistant/components/laifen/manifest.json b/homeassistant/components/laifen/manifest.json new file mode 100644 index 00000000000000..0083a9880cb290 --- /dev/null +++ b/homeassistant/components/laifen/manifest.json @@ -0,0 +1,21 @@ +{ + "domain": "laifen", + "name": "Laifen", + "bluetooth": [ + { + "connectable": true, + "local_name": "LFTB01-P-*" + } + ], + "categories": ["health_wellbeing"], + "codeowners": ["@bzumik1", "@UrbanTechIO"], + "config_flow": true, + "connectivity": ["bluetooth"], + "dependencies": ["bluetooth_adapters"], + "documentation": "https://www.home-assistant.io/integrations/laifen", + "integration_type": "device", + "iot_class": "local_push", + "loggers": ["laifen_ble"], + "quality_scale": "bronze", + "requirements": ["laifen-ble==0.4.1"] +} diff --git a/homeassistant/components/laifen/quality_scale.yaml b/homeassistant/components/laifen/quality_scale.yaml new file mode 100644 index 00000000000000..854b96ae879a70 --- /dev/null +++ b/homeassistant/components/laifen/quality_scale.yaml @@ -0,0 +1,104 @@ +rules: + # Bronze + action-setup: + status: exempt + comment: The integration does not register actions. + appropriate-polling: done + brands: done + common-modules: done + config-flow-test-coverage: done + config-flow: done + dependency-transparency: done + docs-actions: + status: exempt + comment: The integration does not register actions. + docs-conditions: + status: exempt + comment: The integration does not provide conditions. + docs-high-level-description: done + docs-installation-instructions: done + docs-removal-instructions: done + docs-triggers: + status: exempt + comment: The integration does not provide triggers. + entity-event-setup: + status: exempt + comment: Entities do not subscribe to events; the coordinator does. + entity-unique-id: done + has-entity-name: done + runtime-data: done + test-before-configure: done + test-before-setup: + status: exempt + comment: | + The toothbrush is asleep most of the time, so setup does not wait for it + and connects as soon as it wakes up and advertises. + unique-config-entry: done + # Silver + action-exceptions: + status: exempt + comment: The integration does not provide actions. + config-entry-unloading: done + docs-configuration-parameters: + status: exempt + comment: The integration has no options. + docs-installation-parameters: done + entity-unavailable: + status: done + comment: | + The toothbrush is a sleepy device that is asleep almost all the time, so + the battery and the duration of the last brushing keep their last value, + as the sensors of other sleepy Bluetooth devices do. + integration-owner: done + log-when-unavailable: done + parallel-updates: done + reauthentication-flow: + status: exempt + comment: The toothbrush does not require authentication. + test-coverage: done + + # Gold + devices: done + diagnostics: todo + discovery-update-info: + status: exempt + comment: The toothbrush is discovered over Bluetooth, which has no network address to update. + discovery: done + docs-data-update: done + docs-examples: done + docs-known-limitations: done + docs-supported-devices: done + docs-supported-functions: done + docs-troubleshooting: done + docs-use-cases: done + dynamic-devices: + status: exempt + comment: Each config entry is a single toothbrush. + entity-category: done + entity-device-class: done + entity-disabled-by-default: + status: exempt + comment: Every entity is relevant for the toothbrush. + entity-translations: done + exception-translations: + status: exempt + comment: The integration does not raise exceptions. + icon-translations: done + reconfiguration-flow: + status: exempt + comment: | + The only setting is the Bluetooth address, and a different address is a + different toothbrush. + repair-issues: + status: exempt + comment: The integration has no issues that the user could repair. + stale-devices: + status: exempt + comment: Each config entry is a single toothbrush. + + # Platinum + async-dependency: done + inject-websession: + status: exempt + comment: The toothbrush is reached over Bluetooth, not over HTTP. + strict-typing: done diff --git a/homeassistant/components/laifen/sensor.py b/homeassistant/components/laifen/sensor.py new file mode 100644 index 00000000000000..b6abc26581eedd --- /dev/null +++ b/homeassistant/components/laifen/sensor.py @@ -0,0 +1,166 @@ +"""Sensor platform for the Laifen integration.""" + +from collections.abc import Callable +from dataclasses import dataclass +from datetime import datetime, timedelta +from typing import override + +from laifen_ble import LaifenToothbrush + +from homeassistant.components.sensor import ( + RestoreSensor, + SensorDeviceClass, + SensorEntity, + SensorEntityDescription, + SensorStateClass, +) +from homeassistant.const import PERCENTAGE, UnitOfTime +from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.event import async_track_time_interval + +from .coordinator import LaifenConfigEntry +from .entity import LaifenEntity + +PARALLEL_UPDATES = 0 + +CURRENT_DURATION_INTERVAL = timedelta(seconds=1) + + +@dataclass(frozen=True, kw_only=True) +class LaifenSensorEntityDescription(SensorEntityDescription): + """Describes a Laifen sensor.""" + + value_fn: Callable[[LaifenToothbrush], int | None] + + +SENSORS: tuple[LaifenSensorEntityDescription, ...] = ( + LaifenSensorEntityDescription( + key="battery", + device_class=SensorDeviceClass.BATTERY, + native_unit_of_measurement=PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, + value_fn=lambda toothbrush: ( + toothbrush.state.battery_level if toothbrush.state else None + ), + ), + LaifenSensorEntityDescription( + key="last_brushing_duration", + translation_key="last_brushing_duration", + device_class=SensorDeviceClass.DURATION, + native_unit_of_measurement=UnitOfTime.SECONDS, + suggested_display_precision=0, + value_fn=lambda toothbrush: ( + toothbrush.last_session.duration if toothbrush.last_session else None + ), + ), +) + +CURRENT_BRUSHING_DURATION = SensorEntityDescription( + key="current_brushing_duration", + translation_key="current_brushing_duration", + device_class=SensorDeviceClass.DURATION, + native_unit_of_measurement=UnitOfTime.SECONDS, + suggested_display_precision=0, +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: LaifenConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up Laifen sensors.""" + coordinator = entry.runtime_data + async_add_entities( + [ + *(LaifenSensor(coordinator, description) for description in SENSORS), + LaifenCurrentBrushingDurationSensor(coordinator, CURRENT_BRUSHING_DURATION), + ] + ) + + +class LaifenSensor(LaifenEntity, RestoreSensor): + """A Laifen sensor that keeps its last value while the toothbrush sleeps.""" + + entity_description: LaifenSensorEntityDescription + + @override + async def async_added_to_hass(self) -> None: + """Restore the last value.""" + await super().async_added_to_hass() + if (last_sensor_data := await self.async_get_last_sensor_data()) is not None: + self._attr_native_value = last_sensor_data.native_value + self._update_native_value() + + @callback + @override + def _handle_coordinator_update(self) -> None: + """Handle updated data from the toothbrush.""" + self._update_native_value() + super()._handle_coordinator_update() + + def _update_native_value(self) -> None: + """Update the value from the toothbrush.""" + if (value := self.entity_description.value_fn(self.toothbrush)) is not None: + self._attr_native_value = value + + @property + @override + def available(self) -> bool: + """Return whether the sensor is available.""" + return super().available and ( + self.toothbrush.connected or self.native_value is not None + ) + + +class LaifenCurrentBrushingDurationSensor(LaifenEntity, SensorEntity): + """The duration of the brushing session in progress, updated every second.""" + + _unsubscribe_interval: CALLBACK_TYPE | None = None + + @override + async def async_added_to_hass(self) -> None: + """Start following a session that is already in progress.""" + await super().async_added_to_hass() + self.async_on_remove(self._async_stop_interval) + self._async_update_interval() + self._update_native_value() + + @callback + @override + def _handle_coordinator_update(self) -> None: + """Handle updated data from the toothbrush.""" + self._async_update_interval() + self._update_native_value() + super()._handle_coordinator_update() + + @callback + def _async_update_interval(self) -> None: + """Update the duration every second while the motor runs.""" + state = self.toothbrush.state + if self.toothbrush.connected and state is not None and state.running: + if self._unsubscribe_interval is None: + self._unsubscribe_interval = async_track_time_interval( + self.hass, self._async_handle_interval, CURRENT_DURATION_INTERVAL + ) + else: + self._async_stop_interval() + + @callback + def _async_stop_interval(self) -> None: + """Stop updating the duration.""" + if self._unsubscribe_interval is not None: + self._unsubscribe_interval() + self._unsubscribe_interval = None + + @callback + def _async_handle_interval(self, now: datetime) -> None: + """Update the duration of the session in progress.""" + self._update_native_value() + self.async_write_ha_state() + + def _update_native_value(self) -> None: + """Update the value from the toothbrush.""" + session = self.toothbrush.current_session + self._attr_native_value = session.duration if session else 0 diff --git a/homeassistant/components/laifen/strings.json b/homeassistant/components/laifen/strings.json new file mode 100644 index 00000000000000..07c54e96eb60e4 --- /dev/null +++ b/homeassistant/components/laifen/strings.json @@ -0,0 +1,37 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", + "no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]", + "unsupported_firmware": "The firmware of this toothbrush is not supported." + }, + "error": { + "cannot_connect": "Failed to connect. Press the button of the toothbrush to wake it up and try again." + }, + "flow_title": "{name}", + "step": { + "bluetooth_confirm": { + "description": "[%key:component::bluetooth::config::step::bluetooth_confirm::description%]" + }, + "user": { + "data": { + "address": "[%key:common::config_flow::data::device%]" + }, + "data_description": { + "address": "The toothbrush to set up." + }, + "description": "[%key:component::bluetooth::config::step::user::description%]" + } + } + }, + "entity": { + "sensor": { + "current_brushing_duration": { + "name": "Current brushing duration" + }, + "last_brushing_duration": { + "name": "Last brushing duration" + } + } + } +} diff --git a/homeassistant/generated/bluetooth.py b/homeassistant/generated/bluetooth.py index 29672d6f6e793d..90152c51e965f8 100644 --- a/homeassistant/generated/bluetooth.py +++ b/homeassistant/generated/bluetooth.py @@ -753,6 +753,11 @@ "domain": "kulersky", "service_uuid": "8d96a001-0002-64c2-0001-9acc4838521c", }, + { + "connectable": True, + "domain": "laifen", + "local_name": "LFTB01-P-*", + }, { "domain": "lamarzocco", "local_name": "MICRA_*", diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 5b525cf1fa9a83..8211e0208ddc59 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -450,6 +450,7 @@ "kraken", "kulersky", "lacrosse_view", + "laifen", "lamarzocco", "lametric", "landisgyr_heat_meter", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 43e5ec495fbe84..c6b630882b208b 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -8004,6 +8004,18 @@ "config_flow": true, "iot_class": "cloud_polling" }, + "laifen": { + "name": "Laifen", + "integration_type": "device", + "categories": [ + "health_wellbeing" + ], + "connectivity": [ + "bluetooth" + ], + "config_flow": true, + "iot_class": "local_push" + }, "lamarzocco": { "name": "La Marzocco", "integration_type": "device", diff --git a/mypy.ini b/mypy.ini index aad693c5eb5b36..4fc64412ef445a 100644 --- a/mypy.ini +++ b/mypy.ini @@ -3457,6 +3457,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.laifen.*] +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +warn_return_any = true +warn_unreachable = true + [mypy-homeassistant.components.lamarzocco.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/requirements_all.txt b/requirements_all.txt index 89311aacc375a1..18bd1904520a4c 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1540,6 +1540,9 @@ krakenex==2.2.2 # homeassistant.components.lacrosse_view lacrosse-view==1.1.2 +# homeassistant.components.laifen +laifen-ble==0.4.1 + # homeassistant.components.eufy lakeside==0.13 diff --git a/tests/components/laifen/__init__.py b/tests/components/laifen/__init__.py new file mode 100644 index 00000000000000..dc9d79847ee612 --- /dev/null +++ b/tests/components/laifen/__init__.py @@ -0,0 +1,48 @@ +"""Tests for the Laifen integration.""" + +from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.components.bluetooth import inject_bluetooth_service_info + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo + +ADDRESS = "C0:00:00:00:12:34" +NAME = "LFTB01-P-1234" +BATTERY_ENTITY_ID = "sensor.lftb01_p_1234_battery" +DURATION_ENTITY_ID = "sensor.lftb01_p_1234_last_brushing_duration" +CURRENT_DURATION_ENTITY_ID = "sensor.lftb01_p_1234_current_brushing_duration" + +LAIFEN_SERVICE_INFO = BluetoothServiceInfo( + name=NAME, + address=ADDRESS, + rssi=-60, + manufacturer_data={0xAA00: bytes.fromhex("3412000000c0")}, + service_data={}, + service_uuids=[], + source="local", +) + +UNSUPPORTED_SERVICE_INFO = BluetoothServiceInfo( + name="LFTB02-S-412B", + address="C0:00:00:00:41:2B", + rssi=-60, + manufacturer_data={}, + service_data={}, + service_uuids=[], + source="local", +) + + +async def setup_integration( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Set up the Laifen integration for testing.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + +async def wake_up(hass: HomeAssistant) -> None: + """Let the toothbrush advertise as it does when it wakes up.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + await hass.async_block_till_done(wait_background_tasks=True) diff --git a/tests/components/laifen/conftest.py b/tests/components/laifen/conftest.py new file mode 100644 index 00000000000000..9a91f81e935a41 --- /dev/null +++ b/tests/components/laifen/conftest.py @@ -0,0 +1,143 @@ +"""Common fixtures for the Laifen tests.""" + +from collections.abc import Callable, Generator +from datetime import UTC, datetime +from unittest.mock import AsyncMock, MagicMock, patch + +from laifen_ble import BrushingSession, LaifenState, Mode, ModeSettings +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.laifen import PLATFORMS +from homeassistant.components.laifen.const import DOMAIN +from homeassistant.const import CONF_ADDRESS, Platform +from homeassistant.core import HomeAssistant + +from . import ADDRESS, NAME, setup_integration, wake_up + +FIRMWARE_VERSION = "V2.0.93.XXX.T01.B00.Y44.303" +SESSION = BrushingSession( + started_at=datetime(2026, 11, 26, 7, 30, tzinfo=UTC), duration=124 +) + +STATE = LaifenState( + mode=Mode.MODE_2, + mode_settings={ + Mode.MODE_1: ModeSettings(strength=1, range=10, speed=7), + Mode.MODE_2: ModeSettings(strength=8, range=5, speed=3), + Mode.MODE_3: ModeSettings(strength=4, range=10, speed=10), + Mode.HIGH_FREQUENCY: ModeSettings(strength=20, range=1, speed=1), + }, + airplane_mode=False, + battery_level=93, + reminder_30s=False, + brushing_time=120, + high_frequency=True, + running=False, +) + + +@pytest.fixture(autouse=True) +def auto_enable_bluetooth(enable_bluetooth: None) -> None: + """Enable Bluetooth for all tests.""" + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Override async_setup_entry.""" + with patch( + "homeassistant.components.laifen.async_setup_entry", return_value=None + ) as mock_setup_entry: + yield mock_setup_entry + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return the default mocked config entry.""" + return MockConfigEntry( + domain=DOMAIN, + title=NAME, + data={CONF_ADDRESS: ADDRESS}, + unique_id=ADDRESS, + ) + + +@pytest.fixture +def mock_toothbrush_class() -> Generator[MagicMock]: + """Return the mocked toothbrush class.""" + with ( + patch( + "homeassistant.components.laifen.LaifenToothbrush", autospec=True + ) as toothbrush_class, + patch( + "homeassistant.components.laifen.config_flow.LaifenToothbrush", + new=toothbrush_class, + ), + ): + yield toothbrush_class + + +@pytest.fixture +def last_session() -> BrushingSession | None: + """Return the last brushing session of the toothbrush.""" + return None + + +@pytest.fixture +def mock_toothbrush( + mock_toothbrush_class: MagicMock, last_session: BrushingSession | None +) -> MagicMock: + """Return a mocked toothbrush that connects and reports its state.""" + toothbrush = mock_toothbrush_class.return_value + toothbrush.address = ADDRESS + toothbrush.name = NAME + toothbrush.connected = False + toothbrush.state = None + toothbrush.firmware_version = None + toothbrush.last_session = last_session + toothbrush.current_session = None + callbacks: list[Callable[[], None]] = [] + + def register_callback(callback: Callable[[], None]) -> Callable[[], None]: + callbacks.append(callback) + return lambda: callbacks.remove(callback) + + def notify() -> None: + for callback in callbacks: + callback() + + async def connect() -> None: + toothbrush.connected = True + toothbrush.state = STATE + toothbrush.firmware_version = FIRMWARE_VERSION + notify() + + async def disconnect() -> None: + toothbrush.connected = False + notify() + + toothbrush.register_callback.side_effect = register_callback + toothbrush.connect.side_effect = connect + toothbrush.disconnect.side_effect = disconnect + toothbrush.notify = notify + return toothbrush + + +@pytest.fixture +def platforms() -> list[Platform]: + """Return the platforms to set up.""" + return list(PLATFORMS) + + +@pytest.fixture +async def init_integration( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + platforms: list[Platform], +) -> MockConfigEntry: + """Set up the integration with an awake toothbrush.""" + with patch("homeassistant.components.laifen.PLATFORMS", platforms): + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + return mock_config_entry diff --git a/tests/components/laifen/snapshots/test_sensor.ambr b/tests/components/laifen/snapshots/test_sensor.ambr new file mode 100644 index 00000000000000..5bbbe92985f87a --- /dev/null +++ b/tests/components/laifen/snapshots/test_sensor.ambr @@ -0,0 +1,166 @@ +# serializer version: 1 +# name: test_sensors[sensor.lftb01_p_1234_battery-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.lftb01_p_1234_battery', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Battery', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Battery', + 'platform': 'laifen', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'C0:00:00:00:12:34_battery', + 'unit_of_measurement': '%', + }) +# --- +# name: test_sensors[sensor.lftb01_p_1234_battery-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'battery', + : 'LFTB01-P-1234 Battery', + : , + : '%', + }), + 'context': , + 'entity_id': 'sensor.lftb01_p_1234_battery', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '93', + }) +# --- +# name: test_sensors[sensor.lftb01_p_1234_current_brushing_duration-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.lftb01_p_1234_current_brushing_duration', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Current brushing duration', + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Current brushing duration', + 'platform': 'laifen', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'current_brushing_duration', + 'unique_id': 'C0:00:00:00:12:34_current_brushing_duration', + 'unit_of_measurement': , + }) +# --- +# name: test_sensors[sensor.lftb01_p_1234_current_brushing_duration-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'duration', + : 'LFTB01-P-1234 Current brushing duration', + : , + }), + 'context': , + 'entity_id': 'sensor.lftb01_p_1234_current_brushing_duration', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0', + }) +# --- +# name: test_sensors[sensor.lftb01_p_1234_last_brushing_duration-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.lftb01_p_1234_last_brushing_duration', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Last brushing duration', + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Last brushing duration', + 'platform': 'laifen', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'last_brushing_duration', + 'unique_id': 'C0:00:00:00:12:34_last_brushing_duration', + 'unit_of_measurement': , + }) +# --- +# name: test_sensors[sensor.lftb01_p_1234_last_brushing_duration-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'duration', + : 'LFTB01-P-1234 Last brushing duration', + : , + }), + 'context': , + 'entity_id': 'sensor.lftb01_p_1234_last_brushing_duration', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '124', + }) +# --- diff --git a/tests/components/laifen/test_config_flow.py b/tests/components/laifen/test_config_flow.py new file mode 100644 index 00000000000000..06a1f389bf6633 --- /dev/null +++ b/tests/components/laifen/test_config_flow.py @@ -0,0 +1,229 @@ +"""Test the Laifen config flow.""" + +from unittest.mock import MagicMock + +from laifen_ble import LaifenConnectionError, UnsupportedStateError +import pytest +from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.components.bluetooth import inject_bluetooth_service_info + +from homeassistant.components.laifen.const import DOMAIN +from homeassistant.config_entries import SOURCE_BLUETOOTH, SOURCE_USER +from homeassistant.const import CONF_ADDRESS +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from . import ADDRESS, LAIFEN_SERVICE_INFO, NAME, UNSUPPORTED_SERVICE_INFO + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_bluetooth_discovery( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test setting up a discovered toothbrush.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + flow = hass.config_entries.flow.async_get(result["flow_id"]) + assert flow["context"]["title_placeholders"] == {"name": NAME} + + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == NAME + assert result["data"] == {CONF_ADDRESS: ADDRESS} + assert result["result"].unique_id == ADDRESS + mock_toothbrush.connect.assert_awaited_once() + mock_toothbrush.disconnect.assert_awaited_once() + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_bluetooth_discovery_cannot_connect( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test recovering when the discovered toothbrush cannot be connected to.""" + connect = mock_toothbrush.connect.side_effect + mock_toothbrush.connect.side_effect = LaifenConnectionError + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_connect"} + + mock_toothbrush.connect.side_effect = connect + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_bluetooth_discovery_toothbrush_gone( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test recovering when the discovered toothbrush is no longer seen.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_connect"} + mock_toothbrush.connect.assert_not_awaited() + + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_bluetooth_discovery_unsupported_firmware( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test discovering a toothbrush with a firmware that is not supported.""" + mock_toothbrush.connect.side_effect = UnsupportedStateError + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_firmware" + + +async def test_bluetooth_discovery_already_configured( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test discovering a toothbrush that is already configured.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_bluetooth_discovery_already_in_progress(hass: HomeAssistant) -> None: + """Test discovering a toothbrush that is already being set up.""" + await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=LAIFEN_SERVICE_INFO + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_in_progress" + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_toothbrush") +async def test_user(hass: HomeAssistant) -> None: + """Test picking a discovered toothbrush.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + inject_bluetooth_service_info(hass, UNSUPPORTED_SERVICE_INFO) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ADDRESS: ADDRESS} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == NAME + assert result["data"] == {CONF_ADDRESS: ADDRESS} + assert result["result"].unique_id == ADDRESS + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_user_cannot_connect( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test recovering when the picked toothbrush cannot be connected to.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + connect = mock_toothbrush.connect.side_effect + mock_toothbrush.connect.side_effect = LaifenConnectionError + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ADDRESS: ADDRESS} + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_connect"} + + mock_toothbrush.connect.side_effect = connect + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ADDRESS: ADDRESS} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_unsupported_firmware( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test picking a toothbrush with a firmware that is not supported.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + mock_toothbrush.connect.side_effect = UnsupportedStateError + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ADDRESS: ADDRESS} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_firmware" + + +async def test_user_no_devices( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test that configured and unsupported toothbrushes are not offered.""" + mock_config_entry.add_to_hass(hass) + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + inject_bluetooth_service_info(hass, UNSUPPORTED_SERVICE_INFO) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "no_devices_found" + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_user_already_configured( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test picking a toothbrush that got configured meanwhile.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ADDRESS: ADDRESS} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" diff --git a/tests/components/laifen/test_init.py b/tests/components/laifen/test_init.py new file mode 100644 index 00000000000000..9f19942019520c --- /dev/null +++ b/tests/components/laifen/test_init.py @@ -0,0 +1,397 @@ +"""Test the Laifen integration setup.""" + +from dataclasses import replace +from datetime import timedelta +import logging +from unittest.mock import MagicMock + +from laifen_ble import LaifenConnectionError, UnsupportedStateError +import pytest +from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed +from pytest_homeassistant.components.bluetooth import ( + generate_advertisement_data, + generate_ble_device, + inject_advertisement_with_time_and_source_connectable, + inject_bluetooth_service_info, +) + +from homeassistant.components.bluetooth import MONOTONIC_TIME +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import EVENT_HOMEASSISTANT_STOP, STATE_UNAVAILABLE +from homeassistant.core import CoreState, HomeAssistant +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo +from homeassistant.util import dt as dt_util + +from . import ( + ADDRESS, + BATTERY_ENTITY_ID, + DURATION_ENTITY_ID, + LAIFEN_SERVICE_INFO, + NAME, + setup_integration, + wake_up, +) +from .conftest import FIRMWARE_VERSION, STATE + + +def inject_old_advertisement(hass: HomeAssistant) -> None: + """Inject the advertisement of the toothbrush as seen a minute ago.""" + inject_advertisement_with_time_and_source_connectable( + hass, + generate_ble_device(address=ADDRESS, name=NAME, details={}), + generate_advertisement_data( + local_name=NAME, + manufacturer_data=LAIFEN_SERVICE_INFO.manufacturer_data, + ), + MONOTONIC_TIME() - 60, + "local", + connectable=True, + ) + + +async def test_setup_toothbrush_asleep( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush_class: MagicMock, + mock_toothbrush: MagicMock, +) -> None: + """Test that setup succeeds while the toothbrush is asleep.""" + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.LOADED + mock_toothbrush_class.assert_called_once_with(ADDRESS) + mock_toothbrush.connect.assert_not_awaited() + + +async def test_setup_does_not_connect( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that setup does not wait for an advertisement seen before it.""" + inject_bluetooth_service_info(hass, LAIFEN_SERVICE_INFO) + + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.LOADED + mock_toothbrush.connect.assert_not_awaited() + + await wake_up(hass) + + mock_toothbrush.connect.assert_awaited_once() + + +async def test_connect_when_toothbrush_wakes_up( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + device_registry: dr.DeviceRegistry, +) -> None: + """Test connecting when the toothbrush starts advertising.""" + await setup_integration(hass, mock_config_entry) + + await wake_up(hass) + + mock_toothbrush.set_ble_device.assert_called_once() + mock_toothbrush.connect.assert_awaited_once() + device = device_registry.async_get_device_by_connection( + (dr.CONNECTION_BLUETOOTH, ADDRESS), mock_config_entry.entry_id + ) + assert device is not None + assert device.sw_version == FIRMWARE_VERSION + assert device.model == "Wave" + assert device.model_id == "LFTB01-P" + + +async def test_connection_failure( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that the next advertisement is tried after a failed connection.""" + await setup_integration(hass, mock_config_entry) + mock_toothbrush.connect.side_effect = LaifenConnectionError + + await wake_up(hass) + + assert mock_config_entry.state is ConfigEntryState.LOADED + mock_toothbrush.connect.assert_awaited_once() + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await wake_up(hass) + + assert mock_toothbrush.connect.await_count == 2 + + +async def test_unsupported_firmware( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that a toothbrush with an unsupported state is not retried.""" + await setup_integration(hass, mock_config_entry) + mock_toothbrush.connect.side_effect = UnsupportedStateError("length 15") + + await wake_up(hass) + + assert ( + "homeassistant.components.laifen.coordinator", + logging.WARNING, + f"{NAME} sends a state that is not supported: length 15", + ) in caplog.record_tuples + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await wake_up(hass) + + mock_toothbrush.connect.assert_awaited_once() + + +async def test_old_advertisement_is_ignored( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that an old advertisement does not hide the next wake-up.""" + await setup_integration(hass, mock_config_entry) + + inject_old_advertisement(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_toothbrush.connect.assert_not_awaited() + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await wake_up(hass) + + mock_toothbrush.connect.assert_awaited_once() + + +async def test_advertisement_while_connected( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that advertisements do not reconnect a connected toothbrush.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + + inject_bluetooth_service_info( + hass, + BluetoothServiceInfo( + name=NAME, + address=ADDRESS, + rssi=-50, + manufacturer_data={0xAA00: bytes.fromhex("3412000000c1")}, + service_data={}, + service_uuids=[], + source="local", + ), + ) + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_toothbrush.connect.assert_awaited_once() + mock_toothbrush.update.assert_not_awaited() + + +async def test_reconnect_after_sleep( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that the unchanged advertisement of a waking toothbrush reconnects.""" + caplog.set_level(logging.INFO) + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + mock_toothbrush.notify() + await hass.async_block_till_done() + assert caplog.text.count(f"Connected to {NAME}") == 1 + + await mock_toothbrush.disconnect() + await hass.async_block_till_done() + assert f"{NAME} is asleep or out of range" in caplog.text + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await wake_up(hass) + + assert mock_toothbrush.connect.await_count == 2 + + +async def test_reconnect_after_reload( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that the toothbrush is connected again after a reload.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + inject_old_advertisement(hass) + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + mock_toothbrush.disconnect.assert_awaited_once() + mock_toothbrush.connect.assert_awaited_once() + + await wake_up(hass) + + assert mock_toothbrush.connect.await_count == 2 + + +async def test_unload( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test unloading disconnects from the toothbrush.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + mock_toothbrush.disconnect.assert_awaited_once() + + +async def test_disconnect_when_home_assistant_stops( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that the connection is closed when Home Assistant stops.""" + caplog.set_level(logging.INFO) + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + + hass.set_state(CoreState.stopping) + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + + mock_toothbrush.disconnect.assert_awaited_once() + assert f"{NAME} is asleep or out of range" not in caplog.text + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await wake_up(hass) + + mock_toothbrush.connect.assert_awaited_once() + + +async def test_no_connect_after_home_assistant_stops( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that a connect waiting in the debouncer does not run after stop.""" + await setup_integration(hass, mock_config_entry) + connect = mock_toothbrush.connect.side_effect + mock_toothbrush.connect.side_effect = LaifenConnectionError + await wake_up(hass) + mock_toothbrush.connect.side_effect = connect + await wake_up(hass) + + hass.set_state(CoreState.stopping) + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11)) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_toothbrush.connect.assert_awaited_once() + assert not mock_toothbrush.connected + + +@pytest.mark.parametrize("entity_id", [BATTERY_ENTITY_ID, DURATION_ENTITY_ID]) +async def test_entities_unavailable_when_update_fails( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + entity_id: str, +) -> None: + """Test that the entities follow the availability of the coordinator.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + assert hass.states.get(entity_id).state != STATE_UNAVAILABLE + mock_toothbrush.update.side_effect = RuntimeError + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=61)) + await hass.async_block_till_done() + + assert hass.states.get(entity_id).state == STATE_UNAVAILABLE + + +async def test_push_restores_availability_after_failed_update( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that a pushed state restores the availability after a failed update.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + mock_toothbrush.update.side_effect = RuntimeError + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=61)) + await hass.async_block_till_done() + assert hass.states.get(BATTERY_ENTITY_ID).state == STATE_UNAVAILABLE + + mock_toothbrush.state = replace(STATE, battery_level=88) + mock_toothbrush.notify() + await hass.async_block_till_done() + + assert hass.states.get(BATTERY_ENTITY_ID).state == "88" + + +async def test_update_while_connected( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, +) -> None: + """Test that the state is read every minute while connected.""" + await setup_integration(hass, mock_config_entry) + await wake_up(hass) + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=61)) + await hass.async_block_till_done() + + mock_toothbrush.update.assert_awaited_once() + + mock_toothbrush.disconnect.assert_not_awaited() + + mock_toothbrush.update.side_effect = LaifenConnectionError + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=122)) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_toothbrush.update.await_count == 2 + mock_toothbrush.disconnect.assert_awaited_once() + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=133)) + await wake_up(hass) + + assert mock_toothbrush.connect.await_count == 2 + + +async def test_firmware_version_update( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + device_registry: dr.DeviceRegistry, +) -> None: + """Test that the firmware version is stored on the device once known.""" + await setup_integration(hass, mock_config_entry) + mock_toothbrush.notify() + await hass.async_block_till_done() + + device = device_registry.async_get_device_by_connection( + (dr.CONNECTION_BLUETOOTH, ADDRESS), mock_config_entry.entry_id + ) + assert device is not None + assert device.manufacturer == "Laifen" + assert device.sw_version is None + + mock_toothbrush.firmware_version = FIRMWARE_VERSION + mock_toothbrush.notify() + await hass.async_block_till_done() + + device = device_registry.async_get(device.id) + assert device is not None + assert device.sw_version == FIRMWARE_VERSION diff --git a/tests/components/laifen/test_sensor.py b/tests/components/laifen/test_sensor.py new file mode 100644 index 00000000000000..839e09a3da2775 --- /dev/null +++ b/tests/components/laifen/test_sensor.py @@ -0,0 +1,208 @@ +"""Test the Laifen sensors.""" + +from collections.abc import Awaitable, Callable +from dataclasses import replace +from unittest.mock import MagicMock + +from freezegun.api import FrozenDateTimeFactory +from laifen_ble import BrushingSession +import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + mock_restore_cache_with_extra_data, + snapshot_platform, +) +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.laifen.sensor import CURRENT_DURATION_INTERVAL +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform +from homeassistant.core import HomeAssistant, State +from homeassistant.helpers import entity_registry as er + +from . import ( + BATTERY_ENTITY_ID, + CURRENT_DURATION_ENTITY_ID, + DURATION_ENTITY_ID, + setup_integration, +) +from .conftest import SESSION, STATE + + +@pytest.fixture +def platforms() -> list[Platform]: + """Only set up the sensor platform.""" + return [Platform.SENSOR] + + +@pytest.fixture +def last_session() -> BrushingSession | None: + """Return a toothbrush that already brushed.""" + return SESSION + + +@pytest.mark.usefixtures("init_integration") +async def test_sensors( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test the sensors of a connected toothbrush.""" + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.usefixtures("init_integration") +async def test_pushed_state(hass: HomeAssistant, mock_toothbrush: MagicMock) -> None: + """Test that pushed states and sessions update the sensors.""" + mock_toothbrush.state = replace(STATE, battery_level=91) + mock_toothbrush.last_session = replace(SESSION, duration=118) + mock_toothbrush.notify() + await hass.async_block_till_done() + + assert hass.states.get(BATTERY_ENTITY_ID).state == "91" + assert hass.states.get(DURATION_ENTITY_ID).state == "118" + + +@pytest.mark.usefixtures("init_integration") +async def test_unknown_battery_level( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test that an unknown battery level keeps the last one.""" + mock_toothbrush.state = replace(STATE, battery_level=None) + mock_toothbrush.notify() + await hass.async_block_till_done() + + assert hass.states.get(BATTERY_ENTITY_ID).state == "93" + + +@pytest.mark.usefixtures("init_integration") +async def test_sensors_while_asleep( + hass: HomeAssistant, mock_toothbrush: MagicMock +) -> None: + """Test that the last values are kept when the toothbrush falls asleep.""" + await mock_toothbrush.disconnect() + await hass.async_block_till_done() + + assert hass.states.get(BATTERY_ENTITY_ID).state == "93" + assert hass.states.get(DURATION_ENTITY_ID).state == "124" + + +@pytest.mark.parametrize("last_session", [None]) +@pytest.mark.usefixtures("mock_toothbrush") +async def test_sensors_restored( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test that the last values are restored while the toothbrush is asleep.""" + mock_restore_cache_with_extra_data( + hass, + [ + ( + State(BATTERY_ENTITY_ID, "88"), + {"native_value": 88, "native_unit_of_measurement": "%"}, + ), + ], + ) + + await setup_integration(hass, mock_config_entry) + + assert hass.states.get(BATTERY_ENTITY_ID).state == "88" + assert hass.states.get(DURATION_ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize("last_session", [None]) +@pytest.mark.usefixtures("mock_toothbrush") +async def test_sensors_unavailable_before_first_connection( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test that sensors are unavailable before the first connection.""" + await setup_integration(hass, mock_config_entry) + + assert hass.states.get(BATTERY_ENTITY_ID).state == STATE_UNAVAILABLE + assert hass.states.get(DURATION_ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize("last_session", [None]) +@pytest.mark.usefixtures("init_integration") +async def test_duration_unknown_while_connected(hass: HomeAssistant) -> None: + """Test that the duration is unknown before the first brushing.""" + assert hass.states.get(DURATION_ENTITY_ID).state == STATE_UNKNOWN + + +async def _stop_motor(toothbrush: MagicMock) -> None: + """Let the toothbrush report that the motor stopped.""" + toothbrush.state = STATE + toothbrush.notify() + + +async def _fall_asleep(toothbrush: MagicMock) -> None: + """Let the toothbrush disconnect while the motor runs.""" + await toothbrush.disconnect() + + +async def _tick(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None: + """Let one interval of the current brushing duration pass.""" + freezer.tick(CURRENT_DURATION_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + +@pytest.mark.parametrize("end", [_stop_motor, _fall_asleep]) +@pytest.mark.usefixtures("init_integration") +async def test_current_brushing_duration( + hass: HomeAssistant, + mock_toothbrush: MagicMock, + freezer: FrozenDateTimeFactory, + end: Callable[[MagicMock], Awaitable[None]], +) -> None: + """Test that the current duration follows the session in progress.""" + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "0" + + mock_toothbrush.state = replace(STATE, running=True) + mock_toothbrush.notify() + await hass.async_block_till_done() + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "0" + + mock_toothbrush.current_session = replace(SESSION, duration=5) + await _tick(hass, freezer) + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "5" + + mock_toothbrush.current_session = replace(SESSION, duration=6) + await _tick(hass, freezer) + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "6" + + mock_toothbrush.current_session = None + await end(mock_toothbrush) + await hass.async_block_till_done() + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "0" + + mock_toothbrush.current_session = replace(SESSION, duration=7) + await _tick(hass, freezer) + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "0" + + +@pytest.mark.usefixtures("init_integration") +async def test_current_brushing_duration_after_unload( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_toothbrush: MagicMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test that the current duration stops updating when the entry is unloaded.""" + mock_toothbrush.state = replace(STATE, running=True) + mock_toothbrush.current_session = replace(SESSION, duration=5) + mock_toothbrush.notify() + await hass.async_block_till_done() + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == "5" + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + mock_toothbrush.current_session = replace(SESSION, duration=6) + await _tick(hass, freezer) + + assert hass.states.get(CURRENT_DURATION_ENTITY_ID).state == STATE_UNAVAILABLE