From 2ed6df900354d6e267b8e3141f77d9635b813cd1 Mon Sep 17 00:00:00 2001 From: Brandon Rothweiler Date: Mon, 16 Jan 2023 23:29:50 -0500 Subject: [PATCH] Add EufyLife Bluetooth integration (#85907) Co-authored-by: J. Nick Koston --- .coveragerc | 2 + CODEOWNERS | 2 + homeassistant/brands/eufy.json | 6 + .../components/eufylife_ble/__init__.py | 70 ++++++ .../components/eufylife_ble/config_flow.py | 99 ++++++++ .../components/eufylife_ble/const.py | 5 + .../components/eufylife_ble/manifest.json | 28 +++ .../components/eufylife_ble/models.py | 15 ++ .../components/eufylife_ble/sensor.py | 215 ++++++++++++++++++ .../components/eufylife_ble/strings.json | 22 ++ .../eufylife_ble/translations/en.json | 22 ++ homeassistant/generated/bluetooth.py | 20 ++ homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 17 +- requirements_all.txt | 3 + requirements_test_all.txt | 3 + tests/components/eufylife_ble/__init__.py | 24 ++ tests/components/eufylife_ble/conftest.py | 8 + .../eufylife_ble/test_config_flow.py | 200 ++++++++++++++++ 19 files changed, 759 insertions(+), 3 deletions(-) create mode 100644 homeassistant/brands/eufy.json create mode 100644 homeassistant/components/eufylife_ble/__init__.py create mode 100644 homeassistant/components/eufylife_ble/config_flow.py create mode 100644 homeassistant/components/eufylife_ble/const.py create mode 100644 homeassistant/components/eufylife_ble/manifest.json create mode 100644 homeassistant/components/eufylife_ble/models.py create mode 100644 homeassistant/components/eufylife_ble/sensor.py create mode 100644 homeassistant/components/eufylife_ble/strings.json create mode 100644 homeassistant/components/eufylife_ble/translations/en.json create mode 100644 tests/components/eufylife_ble/__init__.py create mode 100644 tests/components/eufylife_ble/conftest.py create mode 100644 tests/components/eufylife_ble/test_config_flow.py diff --git a/.coveragerc b/.coveragerc index 7e5714fdc73a13..d74a0d3a1223f0 100644 --- a/.coveragerc +++ b/.coveragerc @@ -351,6 +351,8 @@ omit = homeassistant/components/esphome/switch.py homeassistant/components/etherscan/sensor.py homeassistant/components/eufy/* + homeassistant/components/eufylife_ble/__init__.py + homeassistant/components/eufylife_ble/sensor.py homeassistant/components/everlights/light.py homeassistant/components/evohome/* homeassistant/components/ezviz/__init__.py diff --git a/CODEOWNERS b/CODEOWNERS index 54472d8be202e2..ec2575e93840f6 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -337,6 +337,8 @@ build.json @home-assistant/supervisor /tests/components/escea/ @lazdavila /homeassistant/components/esphome/ @OttoWinter @jesserockz /tests/components/esphome/ @OttoWinter @jesserockz +/homeassistant/components/eufylife_ble/ @bdr99 +/tests/components/eufylife_ble/ @bdr99 /homeassistant/components/evil_genius_labs/ @balloob /tests/components/evil_genius_labs/ @balloob /homeassistant/components/evohome/ @zxdavb diff --git a/homeassistant/brands/eufy.json b/homeassistant/brands/eufy.json new file mode 100644 index 00000000000000..516c3d5c8241f8 --- /dev/null +++ b/homeassistant/brands/eufy.json @@ -0,0 +1,6 @@ +{ + "domain": "eufy", + "name": "eufy", + "integrations": ["eufy", "eufylife_ble"], + "iot_standards": [] +} diff --git a/homeassistant/components/eufylife_ble/__init__.py b/homeassistant/components/eufylife_ble/__init__.py new file mode 100644 index 00000000000000..49370c2efcf84b --- /dev/null +++ b/homeassistant/components/eufylife_ble/__init__.py @@ -0,0 +1,70 @@ +"""The EufyLife integration.""" +from __future__ import annotations + +from eufylife_ble_client import EufyLifeBLEDevice + +from homeassistant.components import bluetooth +from homeassistant.components.bluetooth.match import ADDRESS, BluetoothCallbackMatcher +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform +from homeassistant.core import Event, HomeAssistant, callback + +from .const import CONF_MODEL, DOMAIN +from .models import EufyLifeData + +PLATFORMS: list[Platform] = [Platform.SENSOR] + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up EufyLife device from a config entry.""" + address = entry.unique_id + assert address is not None + + model = entry.data[CONF_MODEL] + client = EufyLifeBLEDevice(model=model) + + @callback + def _async_update_ble( + service_info: bluetooth.BluetoothServiceInfoBleak, + change: bluetooth.BluetoothChange, + ) -> None: + """Update from a ble callback.""" + client.set_ble_device_and_advertisement_data( + service_info.device, service_info.advertisement + ) + if not client.advertisement_data_contains_state: + hass.async_create_task(client.connect()) + + entry.async_on_unload( + bluetooth.async_register_callback( + hass, + _async_update_ble, + BluetoothCallbackMatcher({ADDRESS: address}), + bluetooth.BluetoothScanningMode.ACTIVE, + ) + ) + + hass.data.setdefault(DOMAIN, {})[entry.entry_id] = EufyLifeData( + address, + model, + client, + ) + + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + async def _async_stop(event: Event) -> None: + """Close the connection.""" + await client.stop() + + entry.async_on_unload( + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop) + ) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload a config entry.""" + if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): + hass.data[DOMAIN].pop(entry.entry_id) + + return unload_ok diff --git a/homeassistant/components/eufylife_ble/config_flow.py b/homeassistant/components/eufylife_ble/config_flow.py new file mode 100644 index 00000000000000..9e1ff4af7a8a95 --- /dev/null +++ b/homeassistant/components/eufylife_ble/config_flow.py @@ -0,0 +1,99 @@ +"""Config flow for the EufyLife integration.""" +from __future__ import annotations + +from typing import Any + +from eufylife_ble_client import MODEL_TO_NAME +import voluptuous as vol + +from homeassistant.components.bluetooth import ( + BluetoothServiceInfoBleak, + async_discovered_service_info, +) +from homeassistant.config_entries import ConfigFlow +from homeassistant.const import CONF_ADDRESS +from homeassistant.data_entry_flow import FlowResult + +from .const import CONF_MODEL, DOMAIN + + +class EufyLifeConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for EufyLife.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialize the config flow.""" + self._discovery_info: BluetoothServiceInfoBleak | None = None + self._discovered_devices: dict[str, str] = {} + + async def async_step_bluetooth( + self, discovery_info: BluetoothServiceInfoBleak + ) -> FlowResult: + """Handle the bluetooth discovery step.""" + await self.async_set_unique_id(discovery_info.address) + self._abort_if_unique_id_configured() + + if discovery_info.name not in MODEL_TO_NAME: + return self.async_abort(reason="not_supported") + + self._discovery_info = discovery_info + return await self.async_step_bluetooth_confirm() + + async def async_step_bluetooth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Confirm discovery.""" + assert self._discovery_info is not None + discovery_info = self._discovery_info + + model_name = MODEL_TO_NAME.get(discovery_info.name) + assert model_name is not None + + if user_input is not None: + return self.async_create_entry( + title=model_name, data={CONF_MODEL: discovery_info.name} + ) + + self._set_confirm_only() + placeholders = {"name": model_name} + self.context["title_placeholders"] = placeholders + return self.async_show_form( + step_id="bluetooth_confirm", description_placeholders=placeholders + ) + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Handle the user step to pick discovered device.""" + 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() + + model = self._discovered_devices[address] + return self.async_create_entry( + title=MODEL_TO_NAME[model], + data={CONF_MODEL: model}, + ) + + current_addresses = self._async_current_ids() + for discovery_info in async_discovered_service_info(self.hass, False): + address = discovery_info.address + if ( + address in current_addresses + or address in self._discovered_devices + or discovery_info.name not in MODEL_TO_NAME + ): + continue + self._discovered_devices[address] = discovery_info.name + + if not self._discovered_devices: + return self.async_abort(reason="no_devices_found") + + return self.async_show_form( + step_id="user", + data_schema=vol.Schema( + {vol.Required(CONF_ADDRESS): vol.In(self._discovered_devices)} + ), + ) diff --git a/homeassistant/components/eufylife_ble/const.py b/homeassistant/components/eufylife_ble/const.py new file mode 100644 index 00000000000000..dac0afc910956e --- /dev/null +++ b/homeassistant/components/eufylife_ble/const.py @@ -0,0 +1,5 @@ +"""Constants for the EufyLife integration.""" + +DOMAIN = "eufylife_ble" + +CONF_MODEL = "model" diff --git a/homeassistant/components/eufylife_ble/manifest.json b/homeassistant/components/eufylife_ble/manifest.json new file mode 100644 index 00000000000000..f38389a6341b24 --- /dev/null +++ b/homeassistant/components/eufylife_ble/manifest.json @@ -0,0 +1,28 @@ +{ + "domain": "eufylife_ble", + "name": "EufyLife", + "integration_type": "device", + "config_flow": true, + "documentation": "https://www.home-assistant.io/integrations/eufylife_ble", + "bluetooth": [ + { + "local_name": "eufy T9140" + }, + { + "local_name": "eufy T9146" + }, + { + "local_name": "eufy T9147" + }, + { + "local_name": "eufy T9148" + }, + { + "local_name": "eufy T9149" + } + ], + "requirements": ["eufylife_ble_client==0.1.7"], + "dependencies": ["bluetooth_adapters"], + "codeowners": ["@bdr99"], + "iot_class": "local_push" +} diff --git a/homeassistant/components/eufylife_ble/models.py b/homeassistant/components/eufylife_ble/models.py new file mode 100644 index 00000000000000..62537f22f23ed5 --- /dev/null +++ b/homeassistant/components/eufylife_ble/models.py @@ -0,0 +1,15 @@ +"""Models for the EufyLife integration.""" +from __future__ import annotations + +from dataclasses import dataclass + +from eufylife_ble_client import EufyLifeBLEDevice + + +@dataclass +class EufyLifeData: + """Data for the EufyLife integration.""" + + address: str + model: str + client: EufyLifeBLEDevice diff --git a/homeassistant/components/eufylife_ble/sensor.py b/homeassistant/components/eufylife_ble/sensor.py new file mode 100644 index 00000000000000..e57b83687a627e --- /dev/null +++ b/homeassistant/components/eufylife_ble/sensor.py @@ -0,0 +1,215 @@ +"""Support for EufyLife sensors.""" +from __future__ import annotations + +from typing import Any + +from eufylife_ble_client import MODEL_TO_NAME + +from homeassistant import config_entries +from homeassistant.components.bluetooth import async_address_present +from homeassistant.components.sensor import SensorDeviceClass, SensorEntity +from homeassistant.const import ( + ATTR_UNIT_OF_MEASUREMENT, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + UnitOfMass, +) +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.entity import DeviceInfo +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.util.unit_conversion import MassConverter +from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM + +from .const import DOMAIN +from .models import EufyLifeData + +IGNORED_STATES = {STATE_UNAVAILABLE, STATE_UNKNOWN} + + +async def async_setup_entry( + hass: HomeAssistant, + entry: config_entries.ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up the EufyLife sensors.""" + data: EufyLifeData = hass.data[DOMAIN][entry.entry_id] + + entities = [ + EufyLifeWeightSensorEntity(data), + EufyLifeRealTimeWeightSensorEntity(data), + ] + + if data.client.supports_heart_rate: + entities.append(EufyLifeHeartRateSensorEntity(data)) + + async_add_entities(entities) + + +class EufyLifeSensorEntity(SensorEntity): + """Representation of an EufyLife sensor.""" + + _attr_has_entity_name = True + + def __init__(self, data: EufyLifeData) -> None: + """Initialize the weight sensor entity.""" + self._data = data + + self._attr_device_info = DeviceInfo( + name=MODEL_TO_NAME[data.model], + connections={(dr.CONNECTION_BLUETOOTH, data.address)}, + ) + + @property + def available(self) -> bool: + """Determine if the entity is available.""" + if self._data.client.advertisement_data_contains_state: + # If the device only uses advertisement data, just check if the address is present. + return async_address_present(self.hass, self._data.address) + + # If the device needs an active connection, availability is based on whether it is connected. + return self._data.client.is_connected + + @callback + def _handle_state_update(self, *args: Any) -> None: + """Handle state update.""" + self.async_write_ha_state() + + async def async_added_to_hass(self) -> None: + """Register callback.""" + self.async_on_remove( + self._data.client.register_callback(self._handle_state_update) + ) + + +class EufyLifeRealTimeWeightSensorEntity(EufyLifeSensorEntity): + """Representation of an EufyLife real-time weight sensor.""" + + _attr_name = "Real-time weight" + _attr_native_unit_of_measurement = UnitOfMass.KILOGRAMS + _attr_device_class = SensorDeviceClass.WEIGHT + + def __init__(self, data: EufyLifeData) -> None: + """Initialize the real-time weight sensor entity.""" + super().__init__(data) + self._attr_unique_id = f"{data.address}_real_time_weight" + + @property + def native_value(self) -> float | None: + """Return the native value.""" + if self._data.client.state is not None: + return self._data.client.state.weight_kg + return None + + @property + def suggested_unit_of_measurement(self) -> str | None: + """Set the suggested unit based on the unit system.""" + if self.hass.config.units is US_CUSTOMARY_SYSTEM: + return UnitOfMass.POUNDS + + return UnitOfMass.KILOGRAMS + + +class EufyLifeWeightSensorEntity(RestoreEntity, EufyLifeSensorEntity): + """Representation of an EufyLife weight sensor.""" + + _attr_name = "Weight" + _attr_native_unit_of_measurement = UnitOfMass.KILOGRAMS + _attr_device_class = SensorDeviceClass.WEIGHT + + _weight_kg: float | None = None + + def __init__(self, data: EufyLifeData) -> None: + """Initialize the weight sensor entity.""" + super().__init__(data) + self._attr_unique_id = f"{data.address}_weight" + + @property + def available(self) -> bool: + """Determine if the entity is available.""" + return True + + @property + def native_value(self) -> float | None: + """Return the native value.""" + return self._weight_kg + + @property + def suggested_unit_of_measurement(self) -> str | None: + """Set the suggested unit based on the unit system.""" + if self.hass.config.units is US_CUSTOMARY_SYSTEM: + return UnitOfMass.POUNDS + + return UnitOfMass.KILOGRAMS + + @callback + def _handle_state_update(self, *args: Any) -> None: + """Handle state update.""" + state = self._data.client.state + if state is not None and state.final_weight_kg is not None: + self._weight_kg = state.final_weight_kg + + super()._handle_state_update(args) + + async def async_added_to_hass(self) -> None: + """Restore state on startup.""" + await super().async_added_to_hass() + + last_state = await self.async_get_last_state() + if not last_state or last_state.state in IGNORED_STATES: + return + + last_weight = float(last_state.state) + last_weight_unit = last_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) + + # Since the RestoreEntity stores the state using the displayed unit, + # not the native unit, we need to convert the state back to the native + # unit. + self._weight_kg = MassConverter.convert( + last_weight, last_weight_unit, self.native_unit_of_measurement + ) + + +class EufyLifeHeartRateSensorEntity(RestoreEntity, EufyLifeSensorEntity): + """Representation of an EufyLife heart rate sensor.""" + + _attr_name = "Heart rate" + _attr_icon = "mdi:heart-pulse" + _attr_native_unit_of_measurement = "bpm" + + _heart_rate: int | None = None + + def __init__(self, data: EufyLifeData) -> None: + """Initialize the heart rate sensor entity.""" + super().__init__(data) + self._attr_unique_id = f"{data.address}_heart_rate" + + @property + def available(self) -> bool: + """Determine if the entity is available.""" + return True + + @property + def native_value(self) -> float | None: + """Return the native value.""" + return self._heart_rate + + @callback + def _handle_state_update(self, *args: Any) -> None: + """Handle state update.""" + state = self._data.client.state + if state is not None and state.heart_rate is not None: + self._heart_rate = state.heart_rate + + super()._handle_state_update(args) + + async def async_added_to_hass(self) -> None: + """Restore state on startup.""" + await super().async_added_to_hass() + + last_state = await self.async_get_last_state() + if not last_state or last_state.state in IGNORED_STATES: + return + + self._heart_rate = int(last_state.state) diff --git a/homeassistant/components/eufylife_ble/strings.json b/homeassistant/components/eufylife_ble/strings.json new file mode 100644 index 00000000000000..a045d84771e33b --- /dev/null +++ b/homeassistant/components/eufylife_ble/strings.json @@ -0,0 +1,22 @@ +{ + "config": { + "flow_title": "[%key:component::bluetooth::config::flow_title%]", + "step": { + "user": { + "description": "[%key:component::bluetooth::config::step::user::description%]", + "data": { + "address": "[%key:component::bluetooth::config::step::user::data::address%]" + } + }, + "bluetooth_confirm": { + "description": "[%key:component::bluetooth::config::step::bluetooth_confirm::description%]" + } + }, + "abort": { + "not_supported": "Device not supported", + "no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]", + "already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]", + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" + } + } +} diff --git a/homeassistant/components/eufylife_ble/translations/en.json b/homeassistant/components/eufylife_ble/translations/en.json new file mode 100644 index 00000000000000..afe859ca766194 --- /dev/null +++ b/homeassistant/components/eufylife_ble/translations/en.json @@ -0,0 +1,22 @@ +{ + "config": { + "abort": { + "already_configured": "Device is already configured", + "already_in_progress": "Configuration flow is already in progress", + "no_devices_found": "No devices found on the network", + "not_supported": "Device not supported" + }, + "flow_title": "{name}", + "step": { + "bluetooth_confirm": { + "description": "Do you want to set up {name}?" + }, + "user": { + "data": { + "address": "Device" + }, + "description": "Choose a device to set up" + } + } + } +} \ No newline at end of file diff --git a/homeassistant/generated/bluetooth.py b/homeassistant/generated/bluetooth.py index 819722832b3731..8ba9b7be01923e 100644 --- a/homeassistant/generated/bluetooth.py +++ b/homeassistant/generated/bluetooth.py @@ -42,6 +42,26 @@ "domain": "bthome", "service_data_uuid": "0000fcd2-0000-1000-8000-00805f9b34fb", }, + { + "domain": "eufylife_ble", + "local_name": "eufy T9140", + }, + { + "domain": "eufylife_ble", + "local_name": "eufy T9146", + }, + { + "domain": "eufylife_ble", + "local_name": "eufy T9147", + }, + { + "domain": "eufylife_ble", + "local_name": "eufy T9148", + }, + { + "domain": "eufylife_ble", + "local_name": "eufy T9149", + }, { "connectable": False, "domain": "fjaraskupan", diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 1c45260b40dc60..ca4ca2e2c4f6e7 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -120,6 +120,7 @@ "epson", "escea", "esphome", + "eufylife_ble", "evil_genius_labs", "ezviz", "faa_delays", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 6c56c0bcaac88a..6c81703e13e99a 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -1481,9 +1481,20 @@ }, "eufy": { "name": "eufy", - "integration_type": "hub", - "config_flow": false, - "iot_class": "local_polling" + "integrations": { + "eufy": { + "integration_type": "hub", + "config_flow": false, + "iot_class": "local_polling", + "name": "eufy" + }, + "eufylife_ble": { + "integration_type": "device", + "config_flow": true, + "iot_class": "local_push", + "name": "EufyLife" + } + } }, "everlights": { "name": "EverLights", diff --git a/requirements_all.txt b/requirements_all.txt index 7a6b737d9d7be2..6aabb8e5ace71f 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -678,6 +678,9 @@ esphome-dashboard-api==1.1 # homeassistant.components.netgear_lte eternalegypt==0.0.12 +# homeassistant.components.eufylife_ble +eufylife_ble_client==0.1.7 + # homeassistant.components.keyboard_remote # evdev==1.4.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index b1f26b1cefef0a..54ee80e5fb3ba7 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -525,6 +525,9 @@ epson-projector==0.5.0 # homeassistant.components.esphome esphome-dashboard-api==1.1 +# homeassistant.components.eufylife_ble +eufylife_ble_client==0.1.7 + # homeassistant.components.faa_delays faadelays==0.0.7 diff --git a/tests/components/eufylife_ble/__init__.py b/tests/components/eufylife_ble/__init__.py new file mode 100644 index 00000000000000..7fbeed9d7980d7 --- /dev/null +++ b/tests/components/eufylife_ble/__init__.py @@ -0,0 +1,24 @@ +"""Tests for the EufyLife integration.""" + + +from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo + +NOT_EUFYLIFE_SERVICE_INFO = BluetoothServiceInfo( + name="Not it", + address="11:22:33:44:55:66", + rssi=-60, + manufacturer_data={}, + service_data={}, + service_uuids=[], + source="local", +) + +T9146_SERVICE_INFO = BluetoothServiceInfo( + name="eufy T9146", + address="11:22:33:44:55:66", + rssi=-60, + manufacturer_data={}, + service_uuids=["0000fff0-0000-1000-8000-00805f9b34fb"], + service_data={}, + source="local", +) diff --git a/tests/components/eufylife_ble/conftest.py b/tests/components/eufylife_ble/conftest.py new file mode 100644 index 00000000000000..18f5a0ec3a112d --- /dev/null +++ b/tests/components/eufylife_ble/conftest.py @@ -0,0 +1,8 @@ +"""EufyLife session fixtures.""" + +import pytest + + +@pytest.fixture(autouse=True) +def mock_bluetooth(enable_bluetooth): + """Auto mock bluetooth.""" diff --git a/tests/components/eufylife_ble/test_config_flow.py b/tests/components/eufylife_ble/test_config_flow.py new file mode 100644 index 00000000000000..c62883e8858661 --- /dev/null +++ b/tests/components/eufylife_ble/test_config_flow.py @@ -0,0 +1,200 @@ +"""Test the EufyLife config flow.""" + +from unittest.mock import patch + +from homeassistant import config_entries +from homeassistant.components.eufylife_ble.const import DOMAIN +from homeassistant.data_entry_flow import FlowResultType + +from . import NOT_EUFYLIFE_SERVICE_INFO, T9146_SERVICE_INFO + +from tests.common import MockConfigEntry + + +async def test_async_step_bluetooth_valid_device(hass): + """Test discovery via bluetooth with a valid device.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=T9146_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + with patch( + "homeassistant.components.eufylife_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={} + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == "Smart Scale C1" + assert result2["data"] == {"model": "eufy T9146"} + assert result2["result"].unique_id == "11:22:33:44:55:66" + + +async def test_async_step_bluetooth_not_eufylife(hass): + """Test discovery via bluetooth with an invalid device.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=NOT_EUFYLIFE_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "not_supported" + + +async def test_async_step_user_no_devices_found(hass): + """Test setup from service info cache with no devices found.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "no_devices_found" + + +async def test_async_step_user_with_found_devices(hass): + """Test setup from service info cache with devices found.""" + with patch( + "homeassistant.components.eufylife_ble.config_flow.async_discovered_service_info", + return_value=[T9146_SERVICE_INFO], + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "user" + with patch( + "homeassistant.components.eufylife_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": "11:22:33:44:55:66"}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == "Smart Scale C1" + assert result2["data"] == {"model": "eufy T9146"} + assert result2["result"].unique_id == "11:22:33:44:55:66" + + +async def test_async_step_user_device_added_between_steps(hass): + """Test the device gets added via another flow between steps.""" + with patch( + "homeassistant.components.eufylife_ble.config_flow.async_discovered_service_info", + return_value=[T9146_SERVICE_INFO], + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "user" + + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="11:22:33:44:55:66", + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.eufylife_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": "11:22:33:44:55:66"}, + ) + assert result2["type"] == FlowResultType.ABORT + assert result2["reason"] == "already_configured" + + +async def test_async_step_user_with_found_devices_already_setup(hass): + """Test setup from service info cache with devices found.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="11:22:33:44:55:66", + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.eufylife_ble.config_flow.async_discovered_service_info", + return_value=[T9146_SERVICE_INFO], + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "no_devices_found" + + +async def test_async_step_bluetooth_devices_already_setup(hass): + """Test we can't start a flow if there is already a config entry.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="11:22:33:44:55:66", + ) + entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=T9146_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_async_step_bluetooth_already_in_progress(hass): + """Test we can't start a flow for the same device twice.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=T9146_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=T9146_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "already_in_progress" + + +async def test_async_step_user_takes_precedence_over_discovery(hass): + """Test manual setup takes precedence over discovery.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=T9146_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + + with patch( + "homeassistant.components.eufylife_ble.config_flow.async_discovered_service_info", + return_value=[T9146_SERVICE_INFO], + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] == FlowResultType.FORM + + with patch( + "homeassistant.components.eufylife_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": "11:22:33:44:55:66"}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == "Smart Scale C1" + assert result2["data"] == {"model": "eufy T9146"} + assert result2["result"].unique_id == "11:22:33:44:55:66" + + # Verify the original one was aborted + assert not hass.config_entries.flow.async_progress(DOMAIN)