Add Wi-Fi signal strength sensor to Bosch Smart Camera (#188996)

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas
2026-11-24 22:42:43 +01:00
committed by GitHub
co-authored by Claude Sonnet 5.5
parent c0163ef96a
commit 8d201c7091
7 changed files with 448 additions and 2 deletions
@@ -5,7 +5,7 @@ from homeassistant.core import HomeAssistant
from .coordinator import BoschCameraConfigEntry, BoschCameraCoordinator
PLATFORMS = [Platform.CAMERA, Platform.LIGHT, Platform.SWITCH]
PLATFORMS = [Platform.CAMERA, Platform.LIGHT, Platform.SENSOR, Platform.SWITCH]
async def async_setup_entry(hass: HomeAssistant, entry: BoschCameraConfigEntry) -> None:
@@ -21,6 +21,7 @@ from bosch_shc_camera_client.states import (
CameraAccountStates,
LightState,
get_light_state,
get_wifi_info,
)
from homeassistant.config_entries import ConfigEntry
@@ -42,6 +43,9 @@ _LOGGER = logging.getLogger(__name__)
# The camera list only changes when the user adds or removes a camera.
SCAN_INTERVAL = timedelta(minutes=5)
# The signal strength fluctuates, but a diagnostic value needs no tight polling.
WIFI_SCAN_INTERVAL = timedelta(minutes=10)
# Dashboards request the image often, but the latest event rarely changes.
SNAPSHOT_TTL = 60
@@ -248,6 +252,11 @@ class BoschCameraCoordinator(DataUpdateCoordinator[dict[str, Camera]]):
self.account_states[camera_id] = replace(state, privacy_mode=enabled)
self.async_update_listeners()
async def async_get_access_token(self) -> str:
"""Return a valid access token."""
await self._oauth_session.async_ensure_token_valid()
return str(self._oauth_session.token[CONF_ACCESS_TOKEN])
def _sync_devices(self, cameras: dict[str, Camera]) -> None:
"""Remove devices of cameras no longer in the account, refresh the rest."""
device_registry = dr.async_get(self.hass)
@@ -271,3 +280,53 @@ class BoschCameraCoordinator(DataUpdateCoordinator[dict[str, Camera]]):
device_registry.async_update_device(
device.id, name=camera.title, sw_version=camera.firmware_version
)
class BoschWifiCoordinator(DataUpdateCoordinator[dict[str, int | None]]):
"""Fetch the Wi-Fi signal strength of every camera."""
config_entry: BoschCameraConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: BoschCameraConfigEntry,
cameras: BoschCameraCoordinator,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=f"{DOMAIN}_wifi",
update_interval=WIFI_SCAN_INTERVAL,
)
self._cameras = cameras
@override
async def _async_update_data(self) -> dict[str, int | None]:
"""Fetch the signal strength of each camera."""
token = await self._cameras.async_get_access_token()
session = async_get_clientsession(self.hass)
data: dict[str, int | None] = {}
# The first poll runs before any entity exists; later ones only fetch
# cameras that have an enabled sensor.
subscribed = set(self.async_contexts())
camera_ids = [
camera_id
for camera_id in self._cameras.data
if self.data is None or camera_id in subscribed
]
for camera_id in camera_ids:
try:
info = await get_wifi_info(session, token, camera_id)
except BoschCameraAuthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="auth_failed"
) from err
except BoschCameraConnectionError, BoschCameraInvalidResponseError:
# One failing camera must not hide the others; it stays unavailable.
_LOGGER.debug("Wi-Fi info of camera %s unavailable", camera_id)
continue
data[camera_id] = info.signal_strength
return data
@@ -0,0 +1,84 @@
"""Sensor platform for the Bosch Smart Camera integration."""
from typing import override
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import PERCENTAGE, EntityCategory
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import BoschCameraConfigEntry, BoschWifiCoordinator
PARALLEL_UPDATES = 0
WIFI_SIGNAL_STRENGTH = SensorEntityDescription(
key="wifi_signal_strength",
translation_key="wifi_signal_strength",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
)
async def async_setup_entry(
hass: HomeAssistant,
entry: BoschCameraConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the sensors of the cameras."""
cameras = entry.runtime_data
coordinator = BoschWifiCoordinator(hass, entry, cameras)
await coordinator.async_refresh()
known: set[str] = set()
@callback
def _add_new_sensors() -> None:
# Forget removed cameras so one that comes back gets a new entity.
known.intersection_update(cameras.data)
new = set(cameras.data) - known
known.update(new)
async_add_entities(
BoschWifiSensor(coordinator, camera_id, cameras.data[camera_id].title)
for camera_id in new
)
entry.async_on_unload(cameras.async_add_listener(_add_new_sensors))
_add_new_sensors()
class BoschWifiSensor(CoordinatorEntity[BoschWifiCoordinator], SensorEntity):
"""The Wi-Fi signal strength of a camera."""
_attr_has_entity_name = True
entity_description = WIFI_SIGNAL_STRENGTH
def __init__(
self, coordinator: BoschWifiCoordinator, camera_id: str, title: str
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, camera_id)
self._camera_id = camera_id
self._attr_unique_id = f"{camera_id}_{self.entity_description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, camera_id)}, manufacturer="Bosch", name=title
)
@property
@override
def available(self) -> bool:
"""Return whether the last poll returned a value for this camera."""
return super().available and self._camera_id in self.coordinator.data
@property
@override
def native_value(self) -> int | None:
"""Return the signal strength in percent."""
return self.coordinator.data.get(self._camera_id)
@@ -27,6 +27,11 @@
"name": "Camera light"
}
},
"sensor": {
"wifi_signal_strength": {
"name": "Wi-Fi signal strength"
}
},
"switch": {
"privacy_mode": {
"name": "Privacy mode"
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, patch
from bosch_shc_camera_client.cameras import Camera, CameraModel
from bosch_shc_camera_client.cloud import CloudPutResult
from bosch_shc_camera_client.states import CameraAccountStates
from bosch_shc_camera_client.states import CameraAccountStates, WifiInfo
import pytest
from pytest_homeassistant.common import MockConfigEntry
@@ -77,6 +77,17 @@ def mock_set_privacy_mode() -> Generator[AsyncMock]:
yield mock
@pytest.fixture(autouse=True)
def mock_get_wifi_info() -> Generator[AsyncMock]:
"""Mock the Wi-Fi signal strength of the library."""
with patch(
"homeassistant.components.bosch_smart_camera.coordinator.get_wifi_info",
autospec=True,
return_value=WifiInfo(signal_strength=72),
) as mock:
yield mock
@pytest.fixture
async def setup_credentials(hass: HomeAssistant) -> None:
"""Register the OAuth2 application credentials."""
@@ -0,0 +1,55 @@
# serializer version: 1
# name: test_all_entities[sensor.garden_wi_fi_signal_strength-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('bosch_smart_camera', '11111111-1111-1111-1111-111111111111')]>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.garden_wi_fi_signal_strength',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Wi-Fi signal strength',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Wi-Fi signal strength',
'platform': 'bosch_smart_camera',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'wifi_signal_strength',
'unique_id': '11111111-1111-1111-1111-111111111111_wifi_signal_strength',
'unit_of_measurement': '%',
})
# ---
# name: test_all_entities[sensor.garden_wi_fi_signal_strength-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Garden Wi-Fi signal strength',
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.MEASUREMENT: 'measurement'>,
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '%',
}),
'context': <ANY>,
'entity_id': 'sensor.garden_wi_fi_signal_strength',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '72',
})
# ---
@@ -0,0 +1,232 @@
"""Test the Bosch Smart Camera sensor platform."""
from dataclasses import replace
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from bosch_shc_camera_client.cameras import (
BoschCameraAuthError,
BoschCameraConnectionError,
BoschCameraInvalidResponseError,
)
from bosch_shc_camera_client.states import WifiInfo
from freezegun.api import FrozenDateTimeFactory
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
async_fire_time_changed,
snapshot_platform,
)
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.bosch_smart_camera.coordinator import WIFI_SCAN_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from .conftest import CAMERA_ID, CAMERAS
pytestmark = pytest.mark.usefixtures("setup_credentials")
ENTITY_ID = "sensor.garden_wi_fi_signal_strength"
OTHER_ID = "22222222-2222-2222-2222-222222222222"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test all sensor entities."""
with patch(
"homeassistant.components.bosch_smart_camera.PLATFORMS", [Platform.SENSOR]
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_disabled_by_default(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the signal strength sensor is disabled by default."""
await setup_integration(hass, mock_config_entry)
entry = entity_registry.async_get(ENTITY_ID)
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
assert hass.states.get(ENTITY_ID) is None
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_value_updates(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_get_wifi_info: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the sensor follows the reported signal strength."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get(ENTITY_ID).state == "72"
assert mock_get_wifi_info.await_args.args[1:] == ("fake-access-token", CAMERA_ID)
mock_get_wifi_info.return_value = WifiInfo(signal_strength=None)
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
"error", [BoschCameraConnectionError, BoschCameraInvalidResponseError]
)
async def test_update_failure_makes_sensor_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_get_wifi_info: AsyncMock,
freezer: FrozenDateTimeFactory,
error: type[Exception],
) -> None:
"""Test a failing update makes the sensor unavailable until it recovers."""
await setup_integration(hass, mock_config_entry)
mock_get_wifi_info.side_effect = error
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
mock_get_wifi_info.side_effect = None
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == "72"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_first_refresh_failure_keeps_setup_alive(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_get_wifi_info: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a failing first refresh only makes the sensor unavailable."""
mock_get_wifi_info.side_effect = BoschCameraConnectionError
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
mock_get_wifi_info.side_effect = None
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == "72"
async def test_auth_error_starts_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_get_wifi_info: AsyncMock,
) -> None:
"""Test a rejected token asks the user to sign in again."""
mock_get_wifi_info.side_effect = BoschCameraAuthError
with patch.object(
mock_config_entry, "async_start_reauth_if_available"
) as mock_start_reauth:
await setup_integration(hass, mock_config_entry)
assert mock_start_reauth.called
async def test_only_cameras_with_enabled_sensor_are_polled(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_list_cameras: AsyncMock,
mock_get_wifi_info: AsyncMock,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test recurring polls skip cameras whose sensor stays disabled."""
mock_list_cameras.return_value = [
*CAMERAS,
replace(CAMERAS[0], id=OTHER_ID, title="Hall"),
]
mock_config_entry.add_to_hass(hass)
entity_registry.async_get_or_create(
"sensor",
"bosch_smart_camera",
f"{CAMERA_ID}_wifi_signal_strength",
config_entry=mock_config_entry,
suggested_object_id="garden_wi_fi_signal_strength",
)
await setup_integration(hass, mock_config_entry)
mock_get_wifi_info.reset_mock()
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert [call.args[2] for call in mock_get_wifi_info.await_args_list] == [CAMERA_ID]
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_camera_added_and_removed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_list_cameras: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensors follow the camera list of the account."""
await setup_integration(hass, mock_config_entry)
other = replace(CAMERAS[0], id=OTHER_ID, title="Hall")
mock_list_cameras.return_value = [*CAMERAS, other]
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done()
freezer.tick(WIFI_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get("sensor.hall_wi_fi_signal_strength").state == "72"
mock_list_cameras.return_value = [other]
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID) is None
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_failing_camera_does_not_affect_others(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_list_cameras: AsyncMock,
mock_get_wifi_info: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test an error for one camera leaves the sensors of the others available."""
mock_list_cameras.return_value = [
*CAMERAS,
replace(CAMERAS[0], id=OTHER_ID, title="Hall"),
]
async def wifi(session, token, camera_id):
if camera_id == CAMERA_ID:
raise BoschCameraConnectionError
return WifiInfo(signal_strength=55)
mock_get_wifi_info.side_effect = wifi
await setup_integration(hass, mock_config_entry)
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
assert hass.states.get("sensor.hall_wi_fi_signal_strength").state == "55"