diff --git a/.strict-typing b/.strict-typing index 330424faec7..67b5d44b97b 100644 --- a/.strict-typing +++ b/.strict-typing @@ -229,6 +229,7 @@ homeassistant.components.rituals_perfume_genie.* homeassistant.components.roku.* homeassistant.components.rpi_power.* homeassistant.components.rtsp_to_webrtc.* +homeassistant.components.ruuvitag_ble.* homeassistant.components.samsungtv.* homeassistant.components.scene.* homeassistant.components.schedule.* diff --git a/CODEOWNERS b/CODEOWNERS index db01573e808..1f45098e4f8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -964,6 +964,8 @@ build.json @home-assistant/supervisor /tests/components/rtsp_to_webrtc/ @allenporter /homeassistant/components/ruckus_unleashed/ @gabe565 /tests/components/ruckus_unleashed/ @gabe565 +/homeassistant/components/ruuvitag_ble/ @akx +/tests/components/ruuvitag_ble/ @akx /homeassistant/components/sabnzbd/ @shaiu /tests/components/sabnzbd/ @shaiu /homeassistant/components/safe_mode/ @home-assistant/core diff --git a/homeassistant/components/ruuvitag_ble/__init__.py b/homeassistant/components/ruuvitag_ble/__init__.py new file mode 100644 index 00000000000..5e30820f837 --- /dev/null +++ b/homeassistant/components/ruuvitag_ble/__init__.py @@ -0,0 +1,49 @@ +"""The ruuvitag_ble integration.""" +from __future__ import annotations + +import logging + +from ruuvitag_ble import RuuvitagBluetoothDeviceData + +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 Ruuvitag BLE device from a config entry.""" + address = entry.unique_id + assert address is not None + data = RuuvitagBluetoothDeviceData() + 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/ruuvitag_ble/config_flow.py b/homeassistant/components/ruuvitag_ble/config_flow.py new file mode 100644 index 00000000000..620b901f4fe --- /dev/null +++ b/homeassistant/components/ruuvitag_ble/config_flow.py @@ -0,0 +1,94 @@ +"""Config flow for ruuvitag_ble.""" +from __future__ import annotations + +from typing import Any + +from ruuvitag_ble import RuuvitagBluetoothDeviceData +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 RuuvitagConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for ruuvitag_ble.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialize the config flow.""" + self._discovery_info: BluetoothServiceInfoBleak | None = None + self._discovered_device: RuuvitagBluetoothDeviceData | 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 = RuuvitagBluetoothDeviceData() + 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 = RuuvitagBluetoothDeviceData() + 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/ruuvitag_ble/const.py b/homeassistant/components/ruuvitag_ble/const.py new file mode 100644 index 00000000000..0df74a24eea --- /dev/null +++ b/homeassistant/components/ruuvitag_ble/const.py @@ -0,0 +1,3 @@ +"""Constants for the ruuvitag_ble integration.""" + +DOMAIN = "ruuvitag_ble" diff --git a/homeassistant/components/ruuvitag_ble/manifest.json b/homeassistant/components/ruuvitag_ble/manifest.json new file mode 100644 index 00000000000..a3500fca7c6 --- /dev/null +++ b/homeassistant/components/ruuvitag_ble/manifest.json @@ -0,0 +1,18 @@ +{ + "domain": "ruuvitag_ble", + "name": "RuuviTag BLE", + "config_flow": true, + "documentation": "https://www.home-assistant.io/integrations/ruuvitag_ble", + "bluetooth": [ + { + "manufacturer_id": 1177 + }, + { + "local_name": "Ruuvi *" + } + ], + "requirements": ["ruuvitag-ble==0.1.1"], + "dependencies": ["bluetooth"], + "codeowners": ["@akx"], + "iot_class": "local_push" +} diff --git a/homeassistant/components/ruuvitag_ble/sensor.py b/homeassistant/components/ruuvitag_ble/sensor.py new file mode 100644 index 00000000000..463d6da2de2 --- /dev/null +++ b/homeassistant/components/ruuvitag_ble/sensor.py @@ -0,0 +1,165 @@ +"""Support for RuuviTag sensors.""" +from __future__ import annotations + +from typing import Optional, Union + +from sensor_state_data import ( + DeviceKey, + SensorDescription, + SensorDeviceClass, + SensorDeviceInfo, + 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 ( + SensorEntity, + SensorEntityDescription, + SensorStateClass, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity import DeviceInfo +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .const import DOMAIN + +SENSOR_DESCRIPTIONS = { + (SensorDeviceClass.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, + ), + (SensorDeviceClass.HUMIDITY, Units.PERCENTAGE): SensorEntityDescription( + key=f"{SensorDeviceClass.HUMIDITY}_{Units.PERCENTAGE}", + device_class=SensorDeviceClass.HUMIDITY, + native_unit_of_measurement=const.PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, + ), + (SensorDeviceClass.PRESSURE, Units.PRESSURE_HPA): SensorEntityDescription( + key=f"{SensorDeviceClass.PRESSURE}_{Units.PRESSURE_HPA}", + device_class=SensorDeviceClass.PRESSURE, + native_unit_of_measurement=const.PRESSURE_HPA, + state_class=SensorStateClass.MEASUREMENT, + ), + ( + SensorDeviceClass.VOLTAGE, + Units.ELECTRIC_POTENTIAL_MILLIVOLT, + ): SensorEntityDescription( + key=f"{SensorDeviceClass.VOLTAGE}_{Units.ELECTRIC_POTENTIAL_MILLIVOLT}", + device_class=SensorDeviceClass.VOLTAGE, + native_unit_of_measurement=const.ELECTRIC_POTENTIAL_MILLIVOLT, + state_class=SensorStateClass.MEASUREMENT, + ), + ( + SensorDeviceClass.SIGNAL_STRENGTH, + Units.SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + ): SensorEntityDescription( + key=f"{SensorDeviceClass.SIGNAL_STRENGTH}_{Units.SIGNAL_STRENGTH_DECIBELS_MILLIWATT}", + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + native_unit_of_measurement=const.SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + (SensorDeviceClass.COUNT, None): SensorEntityDescription( + key="movement_counter", + device_class=SensorDeviceClass.COUNT, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), +} + + +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 _sensor_device_info_to_hass( + sensor_device_info: SensorDeviceInfo, +) -> DeviceInfo: + """Convert a sensor device info to a sensor device info.""" + hass_device_info = DeviceInfo() + if sensor_device_info.name is not None: + hass_device_info[const.ATTR_NAME] = sensor_device_info.name + if sensor_device_info.manufacturer is not None: + hass_device_info[const.ATTR_MANUFACTURER] = sensor_device_info.manufacturer + if sensor_device_info.model is not None: + hass_device_info[const.ATTR_MODEL] = sensor_device_info.model + return hass_device_info + + +def _to_sensor_key( + description: SensorDescription, +) -> tuple[SensorDeviceClass, 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) + 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 Ruuvitag 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( + RuuvitagBluetoothSensorEntity, async_add_entities + ) + ) + entry.async_on_unload(coordinator.async_register_processor(processor)) + + +class RuuvitagBluetoothSensorEntity( + PassiveBluetoothProcessorEntity[ + PassiveBluetoothDataProcessor[Optional[Union[float, int]]] + ], + SensorEntity, +): + """Representation of a Ruuvitag 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 355340d3ed3..6fa2342b5a4 100644 --- a/homeassistant/generated/bluetooth.py +++ b/homeassistant/generated/bluetooth.py @@ -263,6 +263,14 @@ BLUETOOTH: list[dict[str, bool | str | int | list[int]]] = [ "service_data_uuid": "0000fdcd-0000-1000-8000-00805f9b34fb", "connectable": False, }, + { + "domain": "ruuvitag_ble", + "manufacturer_id": 1177, + }, + { + "domain": "ruuvitag_ble", + "local_name": "Ruuvi *", + }, { "domain": "sensorpro", "manufacturer_id": 43605, diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 05e352ab2b7..46aefeebb22 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -334,6 +334,7 @@ FLOWS = { "rpi_power", "rtsp_to_webrtc", "ruckus_unleashed", + "ruuvitag_ble", "sabnzbd", "samsungtv", "screenlogic", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index bbb7928f68f..ed1aa0a3647 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -4475,6 +4475,12 @@ } } }, + "ruuvitag_ble": { + "name": "RuuviTag BLE", + "integration_type": "hub", + "config_flow": true, + "iot_class": "local_push" + }, "sabnzbd": { "name": "SABnzbd", "integration_type": "hub", diff --git a/mypy.ini b/mypy.ini index 988701393d6..b30d64163bc 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2043,6 +2043,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.ruuvitag_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.samsungtv.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/requirements_all.txt b/requirements_all.txt index 7fea5716280..c9106d2ce39 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2217,6 +2217,9 @@ russound==0.1.9 # homeassistant.components.russound_rio russound_rio==0.1.8 +# homeassistant.components.ruuvitag_ble +ruuvitag-ble==0.1.1 + # homeassistant.components.yamaha rxv==0.7.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index a62c14f197d..65966609ecc 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -1532,6 +1532,9 @@ rpi-bad-power==0.1.0 # homeassistant.components.rtsp_to_webrtc rtsp-to-webrtc==0.5.1 +# homeassistant.components.ruuvitag_ble +ruuvitag-ble==0.1.1 + # homeassistant.components.yamaha rxv==0.7.0 diff --git a/tests/components/ruuvitag_ble/__init__.py b/tests/components/ruuvitag_ble/__init__.py new file mode 100644 index 00000000000..e39900689cc --- /dev/null +++ b/tests/components/ruuvitag_ble/__init__.py @@ -0,0 +1 @@ +"""Test package for RuuviTag BLE sensor integration.""" diff --git a/tests/components/ruuvitag_ble/fixtures.py b/tests/components/ruuvitag_ble/fixtures.py new file mode 100644 index 00000000000..26eee1bac5e --- /dev/null +++ b/tests/components/ruuvitag_ble/fixtures.py @@ -0,0 +1,26 @@ +"""Fixtures for testing RuuviTag BLE.""" +from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo + +NOT_RUUVITAG_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", +) + +RUUVITAG_SERVICE_INFO = BluetoothServiceInfo( + name="RuuviTag 0911", + address="01:03:05:07:09:11", # Ignored (the payload encodes the correct MAC) + rssi=-60, + manufacturer_data={ + 1177: b"\x05\x05\xa0`\xa0\xc8\x9a\xfd4\x02\x8c\xff\x00cvriv\xde\xad{?\xef\xaf" + }, + service_data={}, + service_uuids=[], + source="local", +) +CONFIGURED_NAME = "RuuviTag EFAF" +CONFIGURED_PREFIX = "ruuvitag_efaf" diff --git a/tests/components/ruuvitag_ble/test_config_flow.py b/tests/components/ruuvitag_ble/test_config_flow.py new file mode 100644 index 00000000000..1482f9b61b0 --- /dev/null +++ b/tests/components/ruuvitag_ble/test_config_flow.py @@ -0,0 +1,202 @@ +"""Test the Ruuvitag config flow.""" + +from unittest.mock import patch + +import pytest + +from homeassistant import config_entries +from homeassistant.components.ruuvitag_ble.const import DOMAIN +from homeassistant.data_entry_flow import FlowResultType + +from .fixtures import CONFIGURED_NAME, NOT_RUUVITAG_SERVICE_INFO, RUUVITAG_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=RUUVITAG_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + with patch( + "homeassistant.components.ruuvitag_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 == RUUVITAG_SERVICE_INFO.address + + +async def test_async_step_bluetooth_not_ruuvitag(hass): + """Test discovery via bluetooth not ruuvitag.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=NOT_RUUVITAG_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.ruuvitag_ble.config_flow.async_discovered_service_info", + return_value=[RUUVITAG_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.ruuvitag_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": RUUVITAG_SERVICE_INFO.address}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == CONFIGURED_NAME + assert result2["result"].unique_id == RUUVITAG_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.ruuvitag_ble.config_flow.async_discovered_service_info", + return_value=[RUUVITAG_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=RUUVITAG_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.ruuvitag_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": RUUVITAG_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=RUUVITAG_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.ruuvitag_ble.config_flow.async_discovered_service_info", + return_value=[RUUVITAG_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=RUUVITAG_SERVICE_INFO.address, + ) + entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_BLUETOOTH}, + data=RUUVITAG_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=RUUVITAG_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=RUUVITAG_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=RUUVITAG_SERVICE_INFO, + ) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "bluetooth_confirm" + + with patch( + "homeassistant.components.ruuvitag_ble.config_flow.async_discovered_service_info", + return_value=[RUUVITAG_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.ruuvitag_ble.async_setup_entry", return_value=True + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"address": RUUVITAG_SERVICE_INFO.address}, + ) + assert result2["type"] == FlowResultType.CREATE_ENTRY + assert result2["title"] == CONFIGURED_NAME + assert result2["data"] == {} + assert result2["result"].unique_id == RUUVITAG_SERVICE_INFO.address diff --git a/tests/components/ruuvitag_ble/test_sensor.py b/tests/components/ruuvitag_ble/test_sensor.py new file mode 100644 index 00000000000..2f9c027293a --- /dev/null +++ b/tests/components/ruuvitag_ble/test_sensor.py @@ -0,0 +1,46 @@ +"""Test the Ruuvitag BLE sensors.""" + +from __future__ import annotations + +from homeassistant.components.ruuvitag_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, RUUVITAG_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 RuuviTag BLE sensors.""" + entry = MockConfigEntry(domain=DOMAIN, unique_id=RUUVITAG_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, + RUUVITAG_SERVICE_INFO, + ) + await hass.async_block_till_done() + assert len(hass.states.async_all()) >= 4 + + for sensor, value, unit, state_class in [ + ("temperature", "7.2", "°C", "measurement"), + ("humidity", "61.84", "%", "measurement"), + ("pressure", "1013.54", "hPa", "measurement"), + ("voltage", "2395", "mV", "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() + 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()