From e258d448ffbf80342bd0fac50b5bf6089e9eb1af Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Tue, 6 Oct 2026 12:31:24 +0200 Subject: [PATCH] Add bluetooth connectivity sensor to lamarzocco (#184248) --- .../components/lamarzocco/binary_sensor.py | 35 +++++++++-- .../components/lamarzocco/coordinator.py | 5 ++ .../components/lamarzocco/icons.json | 6 ++ .../components/lamarzocco/strings.json | 3 + tests/components/lamarzocco/conftest.py | 4 ++ .../snapshots/test_binary_sensor.ambr | 51 +++++++++++++++ .../lamarzocco/test_binary_sensor.py | 63 +++++++++++++++++-- 7 files changed, 156 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/lamarzocco/binary_sensor.py b/homeassistant/components/lamarzocco/binary_sensor.py index 4726afa9ad18..381459d09d0d 100644 --- a/homeassistant/components/lamarzocco/binary_sensor.py +++ b/homeassistant/components/lamarzocco/binary_sensor.py @@ -99,6 +99,15 @@ ENTITIES: tuple[LaMarzoccoBinarySensorEntityDescription, ...] = ( ), ) +BLUETOOTH_CONNECTED = LaMarzoccoBinarySensorEntityDescription( + key="bluetooth_connected", + translation_key="bluetooth_connected", + device_class=BinarySensorDeviceClass.CONNECTIVITY, + is_on_fn=(lambda machine: machine.bluetooth_connected), + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, +) + async def async_setup_entry( hass: HomeAssistant, @@ -107,14 +116,20 @@ async def async_setup_entry( ) -> None: """Set up binary sensor entities.""" coordinator = entry.runtime_data.config_coordinator + bluetooth_coordinator = entry.runtime_data.bluetooth_coordinator - async_add_entities( - LaMarzoccoBinarySensorEntity( - coordinator, description, entry.runtime_data.bluetooth_coordinator - ) + entities = [ + LaMarzoccoBinarySensorEntity(coordinator, description, bluetooth_coordinator) for description in ENTITIES if description.supported_fn(coordinator) - ) + ] + if bluetooth_coordinator is not None: + entities.append( + LaMarzoccoBluetoothConnectedEntity( + coordinator, BLUETOOTH_CONNECTED, bluetooth_coordinator + ) + ) + async_add_entities(entities) class LaMarzoccoBinarySensorEntity(LaMarzoccoEntity, BinarySensorEntity): @@ -127,3 +142,13 @@ class LaMarzoccoBinarySensorEntity(LaMarzoccoEntity, BinarySensorEntity): def is_on(self) -> bool | None: """Return true if the binary sensor is on.""" return self.entity_description.is_on_fn(self.coordinator.device) + + +class LaMarzoccoBluetoothConnectedEntity(LaMarzoccoBinarySensorEntity): + """Binary sensor showing whether Bluetooth is connected to the machine.""" + + @property + @override + def available(self) -> bool: + """Return True, the connection state is known even if Bluetooth updates fail.""" + return True diff --git a/homeassistant/components/lamarzocco/coordinator.py b/homeassistant/components/lamarzocco/coordinator.py index 890dab9c192e..9db5b88a10c1 100644 --- a/homeassistant/components/lamarzocco/coordinator.py +++ b/homeassistant/components/lamarzocco/coordinator.py @@ -249,6 +249,11 @@ class LaMarzoccoBluetoothUpdateCoordinator(LaMarzoccoUpdateCoordinator): entry.async_on_unload( config_coordinator.async_add_listener(self._async_update_shot_timer) ) + entry.async_on_unload( + device.register_bluetooth_connection_callback( + lambda _: self.async_update_listeners() + ) + ) @override async def _internal_async_setup(self) -> None: diff --git a/homeassistant/components/lamarzocco/icons.json b/homeassistant/components/lamarzocco/icons.json index ac59d954c371..f8093825bd77 100644 --- a/homeassistant/components/lamarzocco/icons.json +++ b/homeassistant/components/lamarzocco/icons.json @@ -7,6 +7,12 @@ "on": "mdi:water" } }, + "bluetooth_connected": { + "default": "mdi:bluetooth", + "state": { + "off": "mdi:bluetooth-off" + } + }, "brew_active": { "default": "mdi:cup", "state": { diff --git a/homeassistant/components/lamarzocco/strings.json b/homeassistant/components/lamarzocco/strings.json index 6f7185ac758d..585b7c17778e 100644 --- a/homeassistant/components/lamarzocco/strings.json +++ b/homeassistant/components/lamarzocco/strings.json @@ -64,6 +64,9 @@ "backflush_enabled": { "name": "Backflush active" }, + "bluetooth_connected": { + "name": "Bluetooth connected" + }, "brew_active": { "name": "Brewing active" }, diff --git a/tests/components/lamarzocco/conftest.py b/tests/components/lamarzocco/conftest.py index af4a07ce75a3..10697b4ac210 100644 --- a/tests/components/lamarzocco/conftest.py +++ b/tests/components/lamarzocco/conftest.py @@ -137,6 +137,10 @@ def mock_lamarzocco(device_fixture: ModelName) -> Generator[MagicMock]: machine_mock.websocket.connected = True machine_mock.websocket.disconnect = AsyncMock() machine_mock.bluetooth_shot_counter_active = False + machine_mock.bluetooth_connected = True + machine_mock.register_bluetooth_connection_callback.return_value = MagicMock( + return_value=None + ) machine_mock.connect_bluetooth_shot_counter.return_value = True yield machine_mock diff --git a/tests/components/lamarzocco/snapshots/test_binary_sensor.ambr b/tests/components/lamarzocco/snapshots/test_binary_sensor.ambr index f95e707104fe..1d2cef9fe5e4 100644 --- a/tests/components/lamarzocco/snapshots/test_binary_sensor.ambr +++ b/tests/components/lamarzocco/snapshots/test_binary_sensor.ambr @@ -50,6 +50,57 @@ 'state': 'off', }) # --- +# name: test_binary_sensors[binary_sensor.gs012345_bluetooth_connected-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.gs012345_bluetooth_connected', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Bluetooth connected', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Bluetooth connected', + 'platform': 'lamarzocco', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'bluetooth_connected', + 'unique_id': 'GS012345_bluetooth_connected', + 'unit_of_measurement': None, + }) +# --- +# name: test_binary_sensors[binary_sensor.gs012345_bluetooth_connected-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'connectivity', + : 'GS012345 Bluetooth connected', + }), + 'context': , + 'entity_id': 'binary_sensor.gs012345_bluetooth_connected', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- # name: test_binary_sensors[binary_sensor.gs012345_brewing_active-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/lamarzocco/test_binary_sensor.py b/tests/components/lamarzocco/test_binary_sensor.py index d65385508b0c..ad4a21c6098b 100644 --- a/tests/components/lamarzocco/test_binary_sensor.py +++ b/tests/components/lamarzocco/test_binary_sensor.py @@ -4,11 +4,11 @@ from datetime import timedelta from unittest.mock import MagicMock, PropertyMock, patch from freezegun.api import FrozenDateTimeFactory -from pylamarzocco.exceptions import RequestNotSuccessful +from pylamarzocco.exceptions import BluetoothConnectionFailed, RequestNotSuccessful import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.const import STATE_UNAVAILABLE, Platform +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -19,10 +19,12 @@ from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_plat pytestmark = pytest.mark.usefixtures("mock_websocket_terminated") -@pytest.mark.usefixtures("entity_registry_enabled_by_default") +@pytest.mark.usefixtures( + "entity_registry_enabled_by_default", "mock_ble_device_from_address" +) async def test_binary_sensors( hass: HomeAssistant, - mock_config_entry: MockConfigEntry, + mock_config_entry_bluetooth: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: @@ -31,8 +33,57 @@ async def test_binary_sensors( with patch( "homeassistant.components.lamarzocco.PLATFORMS", [Platform.BINARY_SENSOR] ): - await async_init_integration(hass, mock_config_entry) - await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + await async_init_integration(hass, mock_config_entry_bluetooth) + await snapshot_platform( + hass, entity_registry, snapshot, mock_config_entry_bluetooth.entry_id + ) + + +@pytest.mark.usefixtures( + "entity_registry_enabled_by_default", "mock_ble_device_from_address" +) +async def test_bluetooth_connected( + hass: HomeAssistant, + mock_lamarzocco: MagicMock, + mock_config_entry_bluetooth: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the Bluetooth connected binary sensor follows the connection.""" + await async_init_integration(hass, mock_config_entry_bluetooth) + + entity_id = "binary_sensor.gs012345_bluetooth_connected" + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_ON + + # the library reports connection changes through the registered callback + mock_lamarzocco.bluetooth_connected = False + connection_callback = ( + mock_lamarzocco.register_bluetooth_connection_callback.call_args.args[0] + ) + connection_callback(False) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_OFF + + # a failing Bluetooth poll doesn't hide the known connection state + mock_lamarzocco.websocket.connected = False + mock_lamarzocco.get_dashboard_from_bluetooth.side_effect = ( + BluetoothConnectionFailed("") + ) + freezer.tick(timedelta(seconds=61)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + # entities relying on Bluetooth updates are unavailable now + assert (state := hass.states.get("binary_sensor.gs012345_water_tank_empty")) + assert state.state == STATE_UNAVAILABLE + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_OFF + + unregister = mock_lamarzocco.register_bluetooth_connection_callback.return_value + await hass.config_entries.async_unload(mock_config_entry_bluetooth.entry_id) + unregister.assert_called_once() async def test_brew_active_unavailable(