From 38b84620bdbf241a6b246b386dbc1cee21e95472 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Sat, 19 Nov 2022 22:26:54 +0200 Subject: [PATCH] Add support for Sensirion BLE sensors (#82382) --- .strict-typing | 1 + CODEOWNERS | 2 + .../components/sensirion_ble/__init__.py | 49 +++++ .../components/sensirion_ble/config_flow.py | 94 ++++++++ .../components/sensirion_ble/const.py | 3 + .../components/sensirion_ble/manifest.json | 18 ++ .../components/sensirion_ble/sensor.py | 131 +++++++++++ homeassistant/generated/bluetooth.py | 8 + homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 6 + mypy.ini | 10 + requirements_all.txt | 3 + requirements_test_all.txt | 3 + tests/components/sensirion_ble/__init__.py | 1 + tests/components/sensirion_ble/fixtures.py | 26 +++ .../sensirion_ble/test_config_flow.py | 206 ++++++++++++++++++ tests/components/sensirion_ble/test_sensor.py | 45 ++++ 17 files changed, 607 insertions(+) create mode 100644 homeassistant/components/sensirion_ble/__init__.py create mode 100644 homeassistant/components/sensirion_ble/config_flow.py create mode 100644 homeassistant/components/sensirion_ble/const.py create mode 100644 homeassistant/components/sensirion_ble/manifest.json create mode 100644 homeassistant/components/sensirion_ble/sensor.py create mode 100644 tests/components/sensirion_ble/__init__.py create mode 100644 tests/components/sensirion_ble/fixtures.py create mode 100644 tests/components/sensirion_ble/test_config_flow.py create mode 100644 tests/components/sensirion_ble/test_sensor.py diff --git a/.strict-typing b/.strict-typing index 08a167855d1..44e303152ce 100644 --- a/.strict-typing +++ b/.strict-typing @@ -238,6 +238,7 @@ homeassistant.components.schedule.* homeassistant.components.select.* homeassistant.components.senseme.* homeassistant.components.sensibo.* +homeassistant.components.sensirion_ble.* homeassistant.components.sensor.* homeassistant.components.senz.* homeassistant.components.shelly.* diff --git a/CODEOWNERS b/CODEOWNERS index 374a3d37a81..3646c36422d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -999,6 +999,8 @@ build.json @home-assistant/supervisor /tests/components/senseme/ @mikelawrence @bdraco /homeassistant/components/sensibo/ @andrey-git @gjohansson-ST /tests/components/sensibo/ @andrey-git @gjohansson-ST +/homeassistant/components/sensirion_ble/ @akx +/tests/components/sensirion_ble/ @akx /homeassistant/components/sensor/ @home-assistant/core /tests/components/sensor/ @home-assistant/core /homeassistant/components/sensorpro/ @bdraco diff --git a/homeassistant/components/sensirion_ble/__init__.py b/homeassistant/components/sensirion_ble/__init__.py new file mode 100644 index 00000000000..66e6f7c250b --- /dev/null +++ b/homeassistant/components/sensirion_ble/__init__.py @@ -0,0 +1,49 @@ +"""The sensirion_ble integration.""" +from __future__ import annotations + +import logging + +from sensirion_ble import SensirionBluetoothDeviceData + +from homeassistant.components.bluetooth import BluetoothScanningMode +from homeassistant.components.bluetooth.passive_update_processor import ( + PassiveBluetoothProcessorCoordinator, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant + +from .const import DOMAIN + +PLATFORMS: list[Platform] = [Platform.SENSOR] + +_LOGGER = logging.getLogger(__name__) + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up Sensirion BLE device from a config entry.""" + address = entry.unique_id + assert address is not None + data = SensirionBluetoothDeviceData() + coordinator = hass.data.setdefault(DOMAIN, {})[ + entry.entry_id + ] = PassiveBluetoothProcessorCoordinator( + hass, + _LOGGER, + address=address, + mode=BluetoothScanningMode.ACTIVE, + update_method=data.update, + ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + entry.async_on_unload( + coordinator.async_start() + ) # only start after all platforms have had a chance to subscribe + 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/sensirion_ble/config_flow.py b/homeassistant/components/sensirion_ble/config_flow.py new file mode 100644 index 00000000000..0442b6d16c3 --- /dev/null +++ b/homeassistant/components/sensirion_ble/config_flow.py @@ -0,0 +1,94 @@ +"""Config flow for sensirion_ble.""" +from __future__ import annotations + +from typing import Any + +from sensirion_ble import SensirionBluetoothDeviceData +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 DOMAIN + + +class SensirionConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for sensirion_ble.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialize the config flow.""" + self._discovery_info: BluetoothServiceInfoBleak | None = None + self._discovered_device: SensirionBluetoothDeviceData | 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() + device = SensirionBluetoothDeviceData() + if not device.supported(discovery_info): + return self.async_abort(reason="not_supported") + self._discovery_info = discovery_info + self._discovered_device = device + 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._discovered_device is not None + device = self._discovered_device + assert self._discovery_info is not None + discovery_info = self._discovery_info + title = device.title or device.get_device_name() or discovery_info.name + if user_input is not None: + return self.async_create_entry(title=title, data={}) + + self._set_confirm_only() + placeholders = {"name": title} + 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() + return self.async_create_entry( + title=self._discovered_devices[address], data={} + ) + + 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: + continue + device = SensirionBluetoothDeviceData() + if device.supported(discovery_info): + self._discovered_devices[address] = ( + device.title or device.get_device_name() or 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/sensirion_ble/const.py b/homeassistant/components/sensirion_ble/const.py new file mode 100644 index 00000000000..58403948762 --- /dev/null +++ b/homeassistant/components/sensirion_ble/const.py @@ -0,0 +1,3 @@ +"""Constants for the sensirion_ble integration.""" + +DOMAIN = "sensirion_ble" diff --git a/homeassistant/components/sensirion_ble/manifest.json b/homeassistant/components/sensirion_ble/manifest.json new file mode 100644 index 00000000000..f13f393a844 --- /dev/null +++ b/homeassistant/components/sensirion_ble/manifest.json @@ -0,0 +1,18 @@ +{ + "domain": "sensirion_ble", + "name": "Sensirion BLE", + "config_flow": true, + "documentation": "https://www.home-assistant.io/integrations/sensirion_ble", + "bluetooth": [ + { + "manufacturer_id": 1749 + }, + { + "local_name": "MyCO2*" + } + ], + "requirements": ["sensirion-ble==0.0.1"], + "dependencies": ["bluetooth"], + "codeowners": ["@akx"], + "iot_class": "local_push" +} diff --git a/homeassistant/components/sensirion_ble/sensor.py b/homeassistant/components/sensirion_ble/sensor.py new file mode 100644 index 00000000000..cd78d2e059b --- /dev/null +++ b/homeassistant/components/sensirion_ble/sensor.py @@ -0,0 +1,131 @@ +"""Support for Sensirion sensors.""" +from __future__ import annotations + +from typing import Optional, Union + +from sensor_state_data import ( + DeviceKey, + SensorDescription, + SensorDeviceClass as SSDSensorDeviceClass, + SensorUpdate, + Units, +) + +from homeassistant import config_entries, const +from homeassistant.components.bluetooth.passive_update_processor import ( + PassiveBluetoothDataProcessor, + PassiveBluetoothDataUpdate, + PassiveBluetoothEntityKey, + PassiveBluetoothProcessorCoordinator, + PassiveBluetoothProcessorEntity, +) +from homeassistant.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorEntityDescription, + SensorStateClass, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.sensor import sensor_device_info_to_hass_device_info + +from .const import DOMAIN + +SENSOR_DESCRIPTIONS: dict[ + tuple[SSDSensorDeviceClass, Units | None], SensorEntityDescription +] = { + ( + SSDSensorDeviceClass.CO2, + Units.CONCENTRATION_PARTS_PER_MILLION, + ): SensorEntityDescription( + key=f"{SensorDeviceClass.CO2}_{Units.CONCENTRATION_PARTS_PER_MILLION}", + device_class=SensorDeviceClass.CO2, + native_unit_of_measurement=const.CONCENTRATION_PARTS_PER_MILLION, + state_class=SensorStateClass.MEASUREMENT, + ), + (SSDSensorDeviceClass.HUMIDITY, Units.PERCENTAGE): SensorEntityDescription( + key=f"{SensorDeviceClass.HUMIDITY}_{Units.PERCENTAGE}", + device_class=SensorDeviceClass.HUMIDITY, + native_unit_of_measurement=const.PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, + ), + (SSDSensorDeviceClass.TEMPERATURE, Units.TEMP_CELSIUS): SensorEntityDescription( + key=f"{SensorDeviceClass.TEMPERATURE}_{Units.TEMP_CELSIUS}", + device_class=SensorDeviceClass.TEMPERATURE, + native_unit_of_measurement=const.TEMP_CELSIUS, + state_class=SensorStateClass.MEASUREMENT, + ), +} + + +def _device_key_to_bluetooth_entity_key( + device_key: DeviceKey, +) -> PassiveBluetoothEntityKey: + """Convert a device key to an entity key.""" + return PassiveBluetoothEntityKey(device_key.key, device_key.device_id) + + +def _to_sensor_key( + description: SensorDescription, +) -> tuple[SSDSensorDeviceClass, Units | None]: + assert description.device_class is not None + return (description.device_class, description.native_unit_of_measurement) + + +def sensor_update_to_bluetooth_data_update( + sensor_update: SensorUpdate, +) -> PassiveBluetoothDataUpdate: + """Convert a sensor update to a bluetooth data update.""" + return PassiveBluetoothDataUpdate( + devices={ + device_id: sensor_device_info_to_hass_device_info(device_info) + for device_id, device_info in sensor_update.devices.items() + }, + entity_descriptions={ + _device_key_to_bluetooth_entity_key(device_key): SENSOR_DESCRIPTIONS[ + _to_sensor_key(description) + ] + for device_key, description in sensor_update.entity_descriptions.items() + if _to_sensor_key(description) in SENSOR_DESCRIPTIONS + }, + entity_data={ + _device_key_to_bluetooth_entity_key(device_key): sensor_values.native_value + for device_key, sensor_values in sensor_update.entity_values.items() + }, + entity_names={ + _device_key_to_bluetooth_entity_key(device_key): sensor_values.name + for device_key, sensor_values in sensor_update.entity_values.items() + }, + ) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: config_entries.ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up the Sensirion BLE sensors.""" + coordinator: PassiveBluetoothProcessorCoordinator = hass.data[DOMAIN][ + entry.entry_id + ] + processor = PassiveBluetoothDataProcessor(sensor_update_to_bluetooth_data_update) + entry.async_on_unload( + processor.async_add_entities_listener( + SensirionBluetoothSensorEntity, async_add_entities + ) + ) + entry.async_on_unload(coordinator.async_register_processor(processor)) + + +class SensirionBluetoothSensorEntity( + PassiveBluetoothProcessorEntity[ + PassiveBluetoothDataProcessor[Optional[Union[float, int]]] + ], + SensorEntity, +): + """Representation of a Sensirion BLE sensor.""" + + @property + def native_value(self) -> int | float | None: + """Return the native value.""" + return self.processor.entity_data.get(self.entity_key) diff --git a/homeassistant/generated/bluetooth.py b/homeassistant/generated/bluetooth.py index 017135e9d10..922e754e84a 100644 --- a/homeassistant/generated/bluetooth.py +++ b/homeassistant/generated/bluetooth.py @@ -272,6 +272,14 @@ BLUETOOTH: list[dict[str, bool | str | int | list[int]]] = [ "domain": "ruuvitag_ble", "local_name": "Ruuvi *", }, + { + "domain": "sensirion_ble", + "manufacturer_id": 1749, + }, + { + "domain": "sensirion_ble", + "local_name": "MyCO2*", + }, { "connectable": False, "domain": "sensorpro", diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index cdcea6cf9b3..e3519ac8773 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -352,6 +352,7 @@ FLOWS = { "sense", "senseme", "sensibo", + "sensirion_ble", "sensorpro", "sensorpush", "sentry", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index f20e3f18b07..69911965eb4 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -4647,6 +4647,12 @@ "config_flow": true, "iot_class": "cloud_polling" }, + "sensirion_ble": { + "name": "Sensirion BLE", + "integration_type": "hub", + "config_flow": true, + "iot_class": "local_push" + }, "sensorblue": { "name": "SensorBlue", "integration_type": "virtual", diff --git a/mypy.ini b/mypy.ini index fa245821ede..c0628a2fc71 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2133,6 +2133,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.sensirion_ble.*] +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.sensor.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/requirements_all.txt b/requirements_all.txt index 17a9550b1c5..0341bb700ef 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2257,6 +2257,9 @@ sendgrid==6.8.2 # homeassistant.components.sense sense_energy==0.10.4 +# homeassistant.components.sensirion_ble +sensirion-ble==0.0.1 + # homeassistant.components.sensorpro sensorpro-ble==0.5.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 31c780304bd..b7cf3f9a2a9 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -1560,6 +1560,9 @@ securetar==2022.2.0 # homeassistant.components.sense sense_energy==0.10.4 +# homeassistant.components.sensirion_ble +sensirion-ble==0.0.1 + # homeassistant.components.sensorpro sensorpro-ble==0.5.0 diff --git a/tests/components/sensirion_ble/__init__.py b/tests/components/sensirion_ble/__init__.py new file mode 100644 index 00000000000..30f89f8934b --- /dev/null +++ b/tests/components/sensirion_ble/__init__.py @@ -0,0 +1 @@ +"""Test package for Sensirion BLE sensor integration.""" diff --git a/tests/components/sensirion_ble/fixtures.py b/tests/components/sensirion_ble/fixtures.py new file mode 100644 index 00000000000..c49ea3c1da2 --- /dev/null +++ b/tests/components/sensirion_ble/fixtures.py @@ -0,0 +1,26 @@ +"""Fixtures for testing Sensirion BLE.""" +from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo + +NOT_SENSIRION_SERVICE_INFO = BluetoothServiceInfo( + name="Not it", + address="61DE521B-F0BF-9F44-64D4-75BBE1738105", + rssi=-63, + manufacturer_data={3234: b"\x00\x01"}, + service_data={}, + service_uuids=[], + source="local", +) + +SENSIRION_SERVICE_INFO = BluetoothServiceInfo( + name="MyCO2", + address="01:03:05:07:09:11", # Ignored (the payload encodes a device ID) + rssi=-60, + manufacturer_data={ + 0x06D5: b"\x00\x08\x84\xe3>_3G\xd4\x02", + }, + service_data={}, + service_uuids=[], + source="local", +) +CONFIGURED_NAME = "MyCO2 84E3" +CONFIGURED_PREFIX = "myco2_84e3" diff --git a/tests/components/sensirion_ble/test_config_flow.py b/tests/components/sensirion_ble/test_config_flow.py new file mode 100644 index 00000000000..9c23a42c90c --- /dev/null +++ b/tests/components/sensirion_ble/test_config_flow.py @@ -0,0 +1,206 @@ +"""Test the Sensirion config flow.""" + +from unittest.mock import patch + +import pytest + +from homeassistant import config_entries +from homeassistant.components.sensirion_ble.const import DOMAIN +from homeassistant.data_entry_flow import FlowResultType + +from .fixtures import ( + CONFIGURED_NAME, + NOT_SENSIRION_SERVICE_INFO, + SENSIRION_SERVICE_INFO, +) + +from tests.common import MockConfigEntry + + +@pytest.fixture(autouse=True) +def mock_bluetooth(enable_bluetooth): + """Mock bluetooth for all tests in this module.""" + + +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=SENSIRION_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + with patch( + "homeassistant.components.sensirion_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"] == CONFIGURED_NAME + assert result2["result"].unique_id == SENSIRION_SERVICE_INFO.address + + +async def test_async_step_bluetooth_not_sensirion(hass): + """Test discovery via bluetooth not sensirion.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=NOT_SENSIRION_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.sensirion_ble.config_flow.async_discovered_service_info", + return_value=[SENSIRION_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.sensirion_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": SENSIRION_SERVICE_INFO.address}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == CONFIGURED_NAME + assert result2["result"].unique_id == SENSIRION_SERVICE_INFO.address + + +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.sensirion_ble.config_flow.async_discovered_service_info", + return_value=[SENSIRION_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=SENSIRION_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.sensirion_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": SENSIRION_SERVICE_INFO.address}, + ) + 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=SENSIRION_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.sensirion_ble.config_flow.async_discovered_service_info", + return_value=[SENSIRION_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=SENSIRION_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=SENSIRION_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=SENSIRION_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=SENSIRION_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=SENSIRION_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + + with patch( + "homeassistant.components.sensirion_ble.config_flow.async_discovered_service_info", + return_value=[SENSIRION_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.sensirion_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": SENSIRION_SERVICE_INFO.address}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == CONFIGURED_NAME + assert result2["data"] == {} + assert result2["result"].unique_id == SENSIRION_SERVICE_INFO.address diff --git a/tests/components/sensirion_ble/test_sensor.py b/tests/components/sensirion_ble/test_sensor.py new file mode 100644 index 00000000000..cdec4a0944e --- /dev/null +++ b/tests/components/sensirion_ble/test_sensor.py @@ -0,0 +1,45 @@ +"""Test the Sensirion BLE sensors.""" + +from __future__ import annotations + +from homeassistant.components.sensirion_ble.const import DOMAIN +from homeassistant.components.sensor import ATTR_STATE_CLASS +from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT +from homeassistant.core import HomeAssistant + +from .fixtures import CONFIGURED_NAME, CONFIGURED_PREFIX, SENSIRION_SERVICE_INFO + +from tests.common import MockConfigEntry +from tests.components.bluetooth import inject_bluetooth_service_info + + +async def test_sensors(enable_bluetooth, hass: HomeAssistant): + """Test the Sensirion BLE sensors.""" + entry = MockConfigEntry(domain=DOMAIN, unique_id=SENSIRION_SERVICE_INFO.address) + entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert len(hass.states.async_all()) == 0 + inject_bluetooth_service_info( + hass, + SENSIRION_SERVICE_INFO, + ) + await hass.async_block_till_done() + assert len(hass.states.async_all()) >= 3 + + for sensor, value, unit, state_class in [ + ("carbon_dioxide", "724", "ppm", "measurement"), + ("humidity", "27.8", "%", "measurement"), + ("temperature", "20.1", "°C", "measurement"), + ]: + state = hass.states.get(f"sensor.{CONFIGURED_PREFIX}_{sensor}") + assert state is not None + assert state.state == value + name_lower = state.attributes[ATTR_FRIENDLY_NAME].lower() + assert name_lower == f"{CONFIGURED_NAME} {sensor}".lower().replace("_", " ") + assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == unit + assert state.attributes[ATTR_STATE_CLASS] == state_class + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done()