mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Add camera light to Bosch Smart Camera (#188998)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com> Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
Simon Lamon
Joost Lekkerkerker
parent
c8923f46ef
commit
78bae90ae4
@@ -5,7 +5,7 @@ from homeassistant.core import HomeAssistant
|
||||
|
||||
from .coordinator import BoschCameraConfigEntry, BoschCameraCoordinator
|
||||
|
||||
PLATFORMS = [Platform.CAMERA, Platform.SWITCH]
|
||||
PLATFORMS = [Platform.CAMERA, Platform.LIGHT, Platform.SWITCH]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: BoschCameraConfigEntry) -> None:
|
||||
|
||||
@@ -13,9 +13,15 @@ from bosch_shc_camera_client.cameras import (
|
||||
BoschCameraConnectionError,
|
||||
BoschCameraInvalidResponseError,
|
||||
Camera,
|
||||
CameraModel,
|
||||
)
|
||||
from bosch_shc_camera_client.client import BoschCameraClient
|
||||
from bosch_shc_camera_client.states import CameraAccountStates
|
||||
from bosch_shc_camera_client.cloud import cloud_set_camera_light
|
||||
from bosch_shc_camera_client.states import (
|
||||
CameraAccountStates,
|
||||
LightState,
|
||||
get_light_state,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN
|
||||
@@ -61,6 +67,9 @@ class BoschCameraCoordinator(DataUpdateCoordinator[dict[str, Camera]]):
|
||||
update_interval=SCAN_INTERVAL,
|
||||
)
|
||||
self.account_states: dict[str, CameraAccountStates] = {}
|
||||
self.light_states: dict[str, LightState] = {}
|
||||
self._light_writes: defaultdict[str, int] = defaultdict(int)
|
||||
self._light_unreachable: set[str] = set()
|
||||
self._write_seq = 0
|
||||
self._written_at: dict[str, int] = {}
|
||||
self._snapshots: dict[str, tuple[float, bytes | None]] = {}
|
||||
@@ -110,6 +119,7 @@ class BoschCameraCoordinator(DataUpdateCoordinator[dict[str, Camera]]):
|
||||
if written > started
|
||||
}
|
||||
data = {camera.id: camera for camera in cameras}
|
||||
await self._async_update_light_states(cameras)
|
||||
for camera_id in self._snapshots.keys() - data.keys():
|
||||
del self._snapshots[camera_id]
|
||||
self._snapshot_locks.pop(camera_id, None)
|
||||
@@ -135,6 +145,88 @@ class BoschCameraCoordinator(DataUpdateCoordinator[dict[str, Camera]]):
|
||||
self._snapshots[camera_id] = (time.monotonic(), image)
|
||||
return image
|
||||
|
||||
async def _async_update_light_states(self, cameras: list[Camera]) -> None:
|
||||
"""Poll the light of each Gen1 outdoor camera, isolating failures."""
|
||||
# Forget removed cameras so a camera that comes back is logged again.
|
||||
listed = {camera.id for camera in cameras}
|
||||
self._light_unreachable &= listed
|
||||
for camera_id in self._light_writes.keys() - listed:
|
||||
del self._light_writes[camera_id]
|
||||
polled: dict[str, tuple[int, LightState | None]] = {}
|
||||
for camera in cameras:
|
||||
if camera.model is not CameraModel.EYES_OUTDOOR:
|
||||
continue
|
||||
writes = self._light_writes[camera.id]
|
||||
try:
|
||||
state = await get_light_state(
|
||||
async_get_clientsession(self.hass),
|
||||
await self._async_get_token(),
|
||||
camera.id,
|
||||
)
|
||||
except BoschCameraAuthError as err:
|
||||
raise ConfigEntryAuthFailed(
|
||||
translation_domain=DOMAIN, translation_key="auth_failed"
|
||||
) from err
|
||||
except BoschCameraConnectionError, BoschCameraInvalidResponseError:
|
||||
if camera.id not in self._light_unreachable:
|
||||
self._light_unreachable.add(camera.id)
|
||||
_LOGGER.info("The light of %s is unreachable", camera.title)
|
||||
_LOGGER.debug("Unable to read the light of a camera", exc_info=True)
|
||||
state = None
|
||||
else:
|
||||
if camera.id in self._light_unreachable:
|
||||
self._light_unreachable.discard(camera.id)
|
||||
_LOGGER.info("The light of %s is reachable again", camera.title)
|
||||
polled[camera.id] = (writes, state)
|
||||
# A write that finished while polling makes the polled state outdated,
|
||||
# also for cameras polled before the write.
|
||||
states: dict[str, LightState] = {}
|
||||
for camera_id, (writes, state) in polled.items():
|
||||
if writes != self._light_writes[camera_id]:
|
||||
state = self.light_states.get(camera_id)
|
||||
if state is not None:
|
||||
states[camera_id] = state
|
||||
self.light_states = states
|
||||
|
||||
async def async_set_light(self, camera_id: str, on: bool) -> None:
|
||||
"""Switch the light of a camera and remember the new state."""
|
||||
known = self.light_states.get(camera_id)
|
||||
intensity = known.front_light_intensity if known else None
|
||||
try:
|
||||
result = await cloud_set_camera_light(
|
||||
async_get_clientsession(self.hass),
|
||||
await self._async_get_token(),
|
||||
camera_id,
|
||||
on,
|
||||
gen2=False,
|
||||
last_front_intensity=intensity or 1.0,
|
||||
)
|
||||
except BoschCameraAuthError as err:
|
||||
self.config_entry.async_start_reauth_if_available(self.hass)
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN, translation_key="auth_failed"
|
||||
) from err
|
||||
except BoschCameraConnectionError as err:
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN, translation_key="light_failed"
|
||||
) from err
|
||||
if result.status in (401, 403):
|
||||
self.config_entry.async_start_reauth_if_available(self.hass)
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN, translation_key="auth_failed"
|
||||
)
|
||||
if not result.ok:
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN, translation_key="light_failed"
|
||||
)
|
||||
self._light_writes[camera_id] += 1
|
||||
self.light_states[camera_id] = LightState(
|
||||
front_light_on=on,
|
||||
wallwasher_on=on,
|
||||
front_light_intensity=intensity,
|
||||
)
|
||||
self.async_update_listeners()
|
||||
|
||||
async def async_set_privacy_mode(self, camera_id: str, enabled: bool) -> None:
|
||||
"""Switch the privacy mode of a camera and update the cached state."""
|
||||
result = await self._client.set_privacy_mode(camera_id, enabled)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Light platform for the Bosch Smart Camera integration."""
|
||||
|
||||
from typing import Any, override
|
||||
|
||||
from bosch_shc_camera_client.cameras import CameraModel
|
||||
|
||||
from homeassistant.components.light import ColorMode, LightEntity
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import BoschCameraConfigEntry, BoschCameraCoordinator
|
||||
from .entity import BoschCameraEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: BoschCameraConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the camera lights of the account."""
|
||||
coordinator = entry.runtime_data
|
||||
known: set[str] = set()
|
||||
|
||||
@callback
|
||||
def _add_new_lights() -> None:
|
||||
# Forget removed cameras so one that comes back gets a new entity.
|
||||
known.intersection_update(coordinator.data)
|
||||
new = {
|
||||
camera_id
|
||||
for camera_id, camera in coordinator.data.items()
|
||||
if camera.model is CameraModel.EYES_OUTDOOR
|
||||
} - known
|
||||
known.update(new)
|
||||
async_add_entities(
|
||||
BoschCameraLight(coordinator, camera_id) for camera_id in new
|
||||
)
|
||||
|
||||
entry.async_on_unload(coordinator.async_add_listener(_add_new_lights))
|
||||
_add_new_lights()
|
||||
|
||||
|
||||
class BoschCameraLight(BoschCameraEntity, LightEntity):
|
||||
"""The light of a camera, switchable on and off."""
|
||||
|
||||
_attr_translation_key = "camera_light"
|
||||
_attr_color_mode = ColorMode.ONOFF
|
||||
_attr_supported_color_modes = {ColorMode.ONOFF}
|
||||
|
||||
def __init__(self, coordinator: BoschCameraCoordinator, camera_id: str) -> None:
|
||||
"""Initialize the light."""
|
||||
super().__init__(coordinator, camera_id)
|
||||
self._attr_unique_id = camera_id
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return whether the camera light state is known."""
|
||||
return super().available and self._camera_id in self.coordinator.light_states
|
||||
|
||||
@property
|
||||
@override
|
||||
def is_on(self) -> bool:
|
||||
"""Return whether the light is on."""
|
||||
return self.coordinator.light_states[self._camera_id].any_on
|
||||
|
||||
@override
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the light on."""
|
||||
await self.coordinator.async_set_light(self._camera_id, True)
|
||||
|
||||
@override
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn the light off."""
|
||||
await self.coordinator.async_set_light(self._camera_id, False)
|
||||
@@ -63,9 +63,7 @@ rules:
|
||||
entity-category: done
|
||||
entity-device-class: todo
|
||||
entity-disabled-by-default: todo
|
||||
entity-translations:
|
||||
status: exempt
|
||||
comment: The camera entity uses the device name.
|
||||
entity-translations: done
|
||||
exception-translations: done
|
||||
icon-translations: todo
|
||||
reconfiguration-flow: todo
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"light": {
|
||||
"camera_light": {
|
||||
"name": "Camera light"
|
||||
}
|
||||
},
|
||||
"switch": {
|
||||
"privacy_mode": {
|
||||
"name": "Privacy mode"
|
||||
@@ -35,6 +40,9 @@
|
||||
"cannot_connect": {
|
||||
"message": "Unable to fetch the cameras from Bosch."
|
||||
},
|
||||
"light_failed": {
|
||||
"message": "Unable to switch the camera light."
|
||||
},
|
||||
"privacy_mode_failed": {
|
||||
"message": "Unable to change the privacy mode at Bosch."
|
||||
},
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
"""Test the Bosch Smart Camera light platform."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from bosch_shc_camera_client.cameras import (
|
||||
BoschCameraAuthError,
|
||||
BoschCameraConnectionError,
|
||||
BoschCameraInvalidResponseError,
|
||||
Camera,
|
||||
CameraModel,
|
||||
)
|
||||
from bosch_shc_camera_client.cloud import CameraLightSetResult
|
||||
from bosch_shc_camera_client.states import LightState
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
from homeassistant.components.bosch_smart_camera.coordinator import SCAN_INTERVAL
|
||||
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN, LightService
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, TargetKey
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
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 = "light.garden_camera_light"
|
||||
GEN1 = Camera(CAMERA_ID, "Garden", "OUTDOOR", CameraModel.EYES_OUTDOOR, "7.91.56")
|
||||
OFF = LightState(False, False, 0.5)
|
||||
ON = LightState(True, True, 0.5)
|
||||
OTHER_ID = "22222222-2222-2222-2222-222222222222"
|
||||
MODULE = "homeassistant.components.bosch_smart_camera.coordinator"
|
||||
|
||||
|
||||
async def turn_on(hass: HomeAssistant, entity_id: str = ENTITY_ID) -> None:
|
||||
"""Turn the light on through the service."""
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: entity_id},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_gen1(mock_list_cameras: AsyncMock) -> None:
|
||||
"""Make the account hold a Gen1 outdoor camera."""
|
||||
mock_list_cameras.return_value = [GEN1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_get_light() -> Generator[AsyncMock]:
|
||||
"""Mock the light state of the library."""
|
||||
with patch(f"{MODULE}.get_light_state", autospec=True, return_value=OFF) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_set_light() -> Generator[AsyncMock]:
|
||||
"""Mock the light write of the library."""
|
||||
with patch(
|
||||
f"{MODULE}.cloud_set_camera_light",
|
||||
autospec=True,
|
||||
return_value=CameraLightSetResult(ok=True, status=204),
|
||||
) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_light_entity(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test the light is created for a Gen1 outdoor camera."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_OFF
|
||||
assert entity_registry.async_get(ENTITY_ID).unique_id == CAMERA_ID
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_no_light_for_other_models(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_list_cameras: AsyncMock,
|
||||
) -> None:
|
||||
"""Test cameras without the Gen1 light get no light entity."""
|
||||
mock_list_cameras.return_value = list(CAMERAS)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert hass.states.async_entity_ids(LIGHT_DOMAIN) == []
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_turn_on_and_off(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_set_light: AsyncMock
|
||||
) -> None:
|
||||
"""Test the light writes to the camera and shows the new state."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_ON
|
||||
assert mock_set_light.await_args.args[1:4] == (
|
||||
"fake-access-token",
|
||||
CAMERA_ID,
|
||||
True,
|
||||
)
|
||||
assert mock_set_light.await_args.kwargs == {
|
||||
"gen2": False,
|
||||
"last_front_intensity": 0.5,
|
||||
}
|
||||
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_OFF,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_OFF
|
||||
assert mock_set_light.await_args.args[3] is False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_intensity_defaults_to_full(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
mock_set_light: AsyncMock,
|
||||
) -> None:
|
||||
"""Test an unknown intensity is sent as full intensity."""
|
||||
mock_get_light.return_value = LightState(False, False, None)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert mock_set_light.await_args.kwargs["last_front_intensity"] == 1.0
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
@pytest.mark.parametrize(
|
||||
"side_effect",
|
||||
[
|
||||
BoschCameraConnectionError("offline"),
|
||||
CameraLightSetResult(ok=False, status=400),
|
||||
],
|
||||
)
|
||||
async def test_write_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_set_light: AsyncMock,
|
||||
side_effect: Exception | CameraLightSetResult,
|
||||
) -> None:
|
||||
"""Test a failed write raises and leaves the state untouched."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
mock_set_light.side_effect = [side_effect]
|
||||
|
||||
with pytest.raises(HomeAssistantError) as err:
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert err.value.translation_key == "light_failed"
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_unavailable_without_light_state(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the light is unavailable when a poll cannot read its state."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_OFF
|
||||
|
||||
mock_get_light.side_effect = BoschCameraConnectionError
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_light_auth_error(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_get_light: AsyncMock
|
||||
) -> None:
|
||||
"""Test a rejected token while reading the light starts reauthentication."""
|
||||
mock_get_light.side_effect = BoschCameraAuthError("rejected")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[BoschCameraConnectionError("offline"), BoschCameraInvalidResponseError("bad")],
|
||||
)
|
||||
async def test_light_read_error_only_affects_the_light(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
error: Exception,
|
||||
) -> None:
|
||||
"""Test a failing light endpoint leaves the camera itself available."""
|
||||
mock_get_light.side_effect = error
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
assert hass.states.get("camera.garden").state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 403])
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_write_auth_status_starts_reauth(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_set_light: AsyncMock,
|
||||
status: int,
|
||||
) -> None:
|
||||
"""Test a rejected write token starts reauthentication."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
mock_set_light.return_value = CameraLightSetResult(ok=False, status=status)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
mock_config_entry, "async_start_reauth_if_available"
|
||||
) as start_reauth,
|
||||
pytest.raises(HomeAssistantError) as err,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert err.value.translation_key == "auth_failed"
|
||||
start_reauth.assert_called_once_with(hass)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_light")
|
||||
async def test_write_auth_error_starts_reauth(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_set_light: AsyncMock,
|
||||
) -> None:
|
||||
"""Test an auth exception on the write starts reauthentication."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
mock_set_light.side_effect = BoschCameraAuthError("rejected")
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
mock_config_entry, "async_start_reauth_if_available"
|
||||
) as start_reauth,
|
||||
pytest.raises(HomeAssistantError) as err,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
LightService.TURN_ON,
|
||||
{TargetKey.ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
assert err.value.translation_key == "auth_failed"
|
||||
start_reauth.assert_called_once_with(hass)
|
||||
|
||||
|
||||
async def test_poll_started_before_a_write_does_not_overwrite_it(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
mock_set_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test an older poll result is dropped after a successful write."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
async def stale_read(*args: Any, **kwargs: Any) -> LightState:
|
||||
await turn_on(hass)
|
||||
return OFF
|
||||
|
||||
mock_get_light.side_effect = stale_read
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_ON
|
||||
|
||||
|
||||
async def test_write_during_poll_of_another_camera_is_kept(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_list_cameras: AsyncMock,
|
||||
mock_get_light: AsyncMock,
|
||||
mock_set_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test a write to a camera polled earlier is not overwritten by the batch."""
|
||||
other = Camera(OTHER_ID, "Yard", "OUTDOOR", CameraModel.EYES_OUTDOOR, None)
|
||||
mock_list_cameras.return_value = [GEN1, other]
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
async def read(session: Any, token: str, camera_id: str) -> LightState:
|
||||
if camera_id == OTHER_ID:
|
||||
await turn_on(hass)
|
||||
return OFF
|
||||
|
||||
mock_get_light.side_effect = read
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_ON
|
||||
|
||||
|
||||
async def test_write_after_failed_poll_keeps_working(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
mock_set_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test a poll failing during a write does not break recording the write."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
async def slow_write(*args: Any, **kwargs: Any) -> CameraLightSetResult:
|
||||
mock_get_light.side_effect = BoschCameraConnectionError("offline")
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
return CameraLightSetResult(ok=True, status=204)
|
||||
|
||||
mock_set_light.side_effect = slow_write
|
||||
await turn_on(hass)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_ON
|
||||
|
||||
|
||||
async def test_light_unreachable_and_recovery_logged_once(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_get_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test an unreachable light is logged once, and again when it recovers."""
|
||||
good = mock_get_light.return_value
|
||||
mock_get_light.side_effect = BoschCameraConnectionError
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert caplog.text.count("is unreachable") == 1
|
||||
assert "is reachable again" not in caplog.text
|
||||
|
||||
mock_get_light.side_effect = None
|
||||
mock_get_light.return_value = good
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert caplog.text.count("is reachable again") == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_set_light")
|
||||
async def test_removed_cameras_are_forgotten_by_the_light_tracking(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_list_cameras: AsyncMock,
|
||||
mock_get_light: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test a camera that left the account starts fresh when it returns."""
|
||||
other = Camera(OTHER_ID, "Yard", "OUTDOOR", CameraModel.EYES_OUTDOOR, None)
|
||||
mock_list_cameras.return_value = [GEN1, other]
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
await turn_on(hass, "light.yard_camera_light")
|
||||
|
||||
async def read(session: Any, token: str, camera_id: str) -> LightState:
|
||||
if camera_id == OTHER_ID:
|
||||
raise BoschCameraConnectionError
|
||||
return OFF
|
||||
|
||||
mock_get_light.side_effect = read
|
||||
for cameras in ([GEN1, other], [GEN1], [GEN1, other]):
|
||||
mock_list_cameras.return_value = cameras
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert caplog.text.count("The light of Yard is unreachable") == 2
|
||||
Reference in New Issue
Block a user