Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions docs/source/advanced/state.rst
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,13 @@ A :class:`~pyhap.camera.Camera` stores its recording settings under its AID:
whether recording and its audio are on, the selected recording configuration
and the camera operating mode (snapshots, HomeKit camera active). Hubs do not
select a configuration again after a restart, so the camera restores the
selection, unless its supported recording configuration changed. The 17.99
values a controller writes, like the global operating mode and the motion
zones, are kept as well. A new home resets all of it.
selection, unless its supported recording configuration changed. Changing
what a paired camera advertises, like its recording resolutions or prebuffer,
therefore drops the selection: the camera logs a warning and refuses
recordings until the hub selects a configuration again. Turning recording off
and on in the Home app should make it select one. The 17.99 values a
controller writes, like the global operating mode and the motion zones, are
kept as well. A new home resets all of it.

A new home must not inherit the old one
=======================================
Expand Down
33 changes: 31 additions & 2 deletions pyhap/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,12 @@ def __init__(self, options: dict[str, Any], *args: Any, **kwargs: Any) -> None:
self._selected_recording_config = None
# Last selection that decoded, the char may hold a rejected write.
self._selected_recording_raw = None
# Logged once, a camera built after the driver loaded its state
# restores twice.
self._selection_dropped_logged = False
# A recording refused without a selection, logged once until the hub
# selects.
self._no_selection_logged = False
self._recording_defaults = {}
self._save_pending = False
self._recording_changed = False
Expand Down Expand Up @@ -1380,6 +1386,7 @@ def set_selected_recording_configuration(self, value: str) -> None:
hksv_recording.SelectedRecordingConfiguration.decode(base64_to_bytes(value))
)
self._selected_recording_raw = value
self._no_selection_logged = False
self.recording_configuration_selected(self._selected_recording_config)

def recording_configuration_selected(self, configuration: Any) -> None:
Expand Down Expand Up @@ -1520,8 +1527,22 @@ def _restore_recording_state(self) -> None:
# The hub does not select again after a restart, so keep the selection
# unless the supported configuration changed.
selected = stored.get(SELECTED_RECORDING_CHAR)
stale = stored.get("supported_hash") != self._supported_recording_hash()
if not selected or stale:
if not selected:
return
if stored.get("supported_hash") != self._supported_recording_hash():
# Only worth a warning while the hub has recording on.
if self.recording_active and not self._selection_dropped_logged:
self._selection_dropped_logged = True
# The refusals that follow have the same cause.
self._no_selection_logged = True
logger.warning(
"%s: the supported recording configuration changed, so the "
"configuration the hub selected was dropped and recordings "
"are refused until the hub selects one again. Turning "
"recording off and on in the Home app should make it select "
"one",
self.display_name,
)
return
try:
config = hksv_recording.SelectedRecordingConfiguration.decode(
Expand Down Expand Up @@ -1611,6 +1632,14 @@ def _recording_open_gate(
if self._recording_stream is not None and self._recording_stream.streaming:
return reasons.BUSY
if self._selected_recording_config is None:
if not self._no_selection_logged:
self._no_selection_logged = True
logger.warning(
"%s: refused a recording, the hub has not selected a "
"recording configuration. Turning recording off and on in "
"the Home app should make it select one",
self.display_name,
)
return reasons.INVALID_CONFIGURATION
self._recording_stream = manager
return None
Expand Down
63 changes: 62 additions & 1 deletion tests/test_hksv_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from pyhap.accessory_driver import AccessoryDriver
from pyhap.camera import Camera
from pyhap.encoder import AccessoryEncoder
from pyhap.hds_recording import RecordingReason
from pyhap.state import State
from pyhap.util import base64_to_bytes, to_base64_str

Expand Down Expand Up @@ -178,13 +179,73 @@ async def test_restore_on_construction(driver: Any) -> None:
_assert_state(other, DEFAULTS, selected=False)


async def test_stale_selected_configuration_dropped(driver: Any) -> None:
async def test_stale_selected_configuration_dropped(
driver: Any, caplog: pytest.LogCaptureFixture
) -> None:
"""Verify a changed configuration drops the selection with one warning."""
await _write_recording_state(Camera(_options(), driver, "Cam", aid=CAMERA_AID))

camera = Camera(
_options(resolutions=((1280, 720, 30),)), driver, "Cam", aid=CAMERA_AID
)
_assert_state(camera, {**WRITES, SELECTED_CHAR: ""}, selected=False)
# A driver that loaded its state before restores the camera once more.
camera.restore_accessory_state()
# The refusal has the same cause, it is not logged again.
_char(camera, "CameraOperatingMode", "HomeKitCameraActive").set_value(1)
refused = camera._recording_open_gate(MagicMock())
assert refused == RecordingReason.INVALID_CONFIGURATION
assert [record.levelname for record in caplog.records] == ["WARNING"]
assert caplog.messages[0].startswith("Cam: the supported recording configuration")
assert "off and on in the Home app should make it select" in caplog.messages[0]


@pytest.mark.parametrize(
"writes",
[
pytest.param(
{**WRITES, ("CameraRecordingManagement", "Active"): 0}, id="recording-off"
),
pytest.param(
{key: value for key, value in WRITES.items() if key != SELECTED_CHAR},
id="nothing-selected",
),
],
)
async def test_changed_configuration_without_active_selection_is_quiet(
driver: Any, caplog: pytest.LogCaptureFixture, writes: dict[Any, Any]
) -> None:
"""Verify a changed configuration warns only for a selection in use."""
old = Camera(_options(), driver, "Cam", aid=CAMERA_AID)
for (service, name), value in writes.items():
_char(old, service, name).client_update_value(value)
await _drain()

Camera(_options(resolutions=((1280, 720, 30),)), driver, "Cam", aid=CAMERA_AID)

assert not caplog.records


async def test_recording_refused_without_selection_is_logged_once(
driver: Any, caplog: pytest.LogCaptureFixture
) -> None:
"""Verify a refusal for a missing selection warns once until the hub selects."""
camera = Camera(_options(), driver, "Cam", aid=CAMERA_AID)
active = _char(camera, "CameraRecordingManagement", "Active")
active.client_update_value(1)
refused = [camera._recording_open_gate(MagicMock()) for _ in range(2)]
assert refused == [RecordingReason.INVALID_CONFIGURATION] * 2
assert [record.levelname for record in caplog.records] == ["WARNING"]
assert caplog.messages[0].startswith("Cam: refused a recording")
assert "off and on in the Home app should make it select" in caplog.messages[0]

# The hub selects, later a new home turns recording on without selecting.
_char(camera, *SELECTED_CHAR).client_update_value(SELECTED)
camera.reset_accessory_state()
active.client_update_value(1)
refused = camera._recording_open_gate(MagicMock())
assert refused == RecordingReason.INVALID_CONFIGURATION
assert caplog.messages == [caplog.messages[0]] * 2


@pytest.mark.parametrize("value", [None, 7, "1", float("inf"), float("nan")])
Expand Down
Loading