diff --git a/homeassistant/components/hikvision/binary_sensor.py b/homeassistant/components/hikvision/binary_sensor.py index 9e1cb97f7783..c4455e7461c5 100644 --- a/homeassistant/components/hikvision/binary_sensor.py +++ b/homeassistant/components/hikvision/binary_sensor.py @@ -314,6 +314,12 @@ class HikvisionBinarySensor(HikvisionEntity, BinarySensorEntity): """Get sensor attributes from camera.""" return self._camera.fetch_attributes(self._sensor_type, self._channel) + @property + @override + def available(self) -> bool: + """Return true if the device's event stream is connected.""" + return self._camera.stream_connected + @property @override def is_on(self) -> bool: diff --git a/tests/components/hikvision/conftest.py b/tests/components/hikvision/conftest.py index da827a707793..b0c090451106 100644 --- a/tests/components/hikvision/conftest.py +++ b/tests/components/hikvision/conftest.py @@ -123,6 +123,7 @@ def mock_hikcamera(mock_hik_get_channels: MagicMock) -> Generator[MagicMock]: "2024-01-01T00:00:00Z", ) camera.get_event_triggers.return_value = {} + camera.stream_connected = True # pyHik 0.4.0 methods camera.get_channels.return_value = [1] diff --git a/tests/components/hikvision/test_binary_sensor.py b/tests/components/hikvision/test_binary_sensor.py index 5cc742971e1c..74b9cf19a22e 100644 --- a/tests/components/hikvision/test_binary_sensor.py +++ b/tests/components/hikvision/test_binary_sensor.py @@ -19,6 +19,7 @@ from homeassistant.const import ( CONF_SSL, CONF_USERNAME, STATE_OFF, + STATE_UNAVAILABLE, Platform, ) from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant @@ -394,3 +395,27 @@ async def test_binary_sensor_update_callback( state = hass.states.get("binary_sensor.front_camera_motion") assert state is not None assert state.state == "on" + + +async def test_binary_sensor_unavailable_when_stream_disconnected( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_hikcamera: MagicMock, +) -> None: + """Test sensors go unavailable when the event stream disconnects.""" + camera = mock_hikcamera.return_value + await setup_integration(hass, mock_config_entry) + + state = hass.states.get("binary_sensor.front_camera_motion") + assert state is not None + assert state.state == STATE_OFF + + # pyhik notifies every registered callback when the stream drops + camera.stream_connected = False + callback_func = camera.add_update_callback.call_args_list[0][0][0] + callback_func("stream disconnected") + await hass.async_block_till_done() + + state = hass.states.get("binary_sensor.front_camera_motion") + assert state is not None + assert state.state == STATE_UNAVAILABLE