Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose camera PTZ information over websocket #556

Merged
merged 1 commit into from
Oct 18, 2023
Merged
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
12 changes: 12 additions & 0 deletions custom_components/frigate/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,18 @@ async def async_get_config(self) -> dict[str, Any]:
await self.api_wrapper("get", str(URL(self._host) / "api/config")),
)

async def async_get_ptz_info(
self,
camera: str,
decode_json: bool = True,
) -> Any:
"""Get PTZ info."""
return await self.api_wrapper(
"get",
str(URL(self._host) / "api" / camera / "ptz/info"),
decode_json=decode_json,
)

async def async_get_path(self, path: str) -> Any:
"""Get data from the API."""
return await self.api_wrapper("get", str(URL(self._host) / f"{path}/"))
Expand Down
36 changes: 36 additions & 0 deletions custom_components/frigate/ws_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def async_setup(hass: HomeAssistant) -> None:
websocket_api.async_register_command(hass, ws_get_recordings_summary)
websocket_api.async_register_command(hass, ws_get_events)
websocket_api.async_register_command(hass, ws_get_events_summary)
websocket_api.async_register_command(hass, ws_get_ptz_info)


def _get_client_or_send_error(
Expand Down Expand Up @@ -234,3 +235,38 @@ async def ws_get_events_summary(
f"API error whilst retrieving events summary for Frigate instance "
f"{msg['instance_id']}",
)


@websocket_api.websocket_command(
{
vol.Required("type"): "frigate/ptz/info",
vol.Required("instance_id"): str,
vol.Required("camera"): str,
}
) # type: ignore[misc]
@websocket_api.async_response # type: ignore[misc]
async def ws_get_ptz_info(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict,
) -> None:
"""Get PTZ info."""
client = _get_client_or_send_error(hass, msg["instance_id"], msg["id"], connection)
if not client:
return

try:
connection.send_result(
msg["id"],
await client.async_get_ptz_info(
msg["camera"],
decode_json=False,
),
)
except FrigateApiClientError:
connection.send_error(
msg["id"],
"frigate_error",
f"API error whilst retrieving PTZ info for camera "
f"{msg['camera']} for Frigate instance {msg['instance_id']}",
)
27 changes: 27 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,3 +384,30 @@ async def recordings_handler(request: web.Request) -> web.Response:
await frigate_client.async_get_recordings(camera, after, before)
== recordings_success
)


async def test_async_get_ptz_info(
aiohttp_session: aiohttp.ClientSession, aiohttp_server: Any
) -> None:
"""Test async_get_ptz_info."""

camera = "master_bedroom"
summary_success = [
{
"features": ["pt", "zoom", "pt-r", "zoom-r"],
"name": camera,
"presets": [
"preset01",
"preset02",
],
}
]
summary_handler = AsyncMock(return_value=web.json_response(summary_success))

server = await start_frigate_server(
aiohttp_server, [web.get(f"/api/{camera}/ptz/info", summary_handler)]
)

frigate_client = FrigateApiClient(str(server.make_url("/")), aiohttp_session)
assert await frigate_client.async_get_ptz_info(camera) == summary_success
assert summary_handler.called
75 changes: 75 additions & 0 deletions tests/test_ws_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,3 +402,78 @@ async def test_get_events_summary_api_error(
response = await ws_client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "frigate_error"


async def test_get_ptz_info_success(hass: HomeAssistant, hass_ws_client: Any) -> None:
"""Test retrieving PTZ info successfully."""

mock_client = create_mock_frigate_client()
await setup_mock_frigate_config_entry(hass, client=mock_client)

ws_client = await hass_ws_client()
ptz_info_json = {
"id": 1,
"type": "frigate/ptz/info",
"instance_id": TEST_FRIGATE_INSTANCE_ID,
"camera": "master_bedroom",
}
ptz_info_success = {
"features": ["pt", "zoom", "pt-r", "zoom-r"],
"name": "master_bedroom",
"presets": [
"preset01",
"preset02",
],
}
mock_client.async_get_ptz_info = AsyncMock(return_value=ptz_info_success)
await ws_client.send_json(ptz_info_json)

response = await ws_client.receive_json()
mock_client.async_get_ptz_info.assert_called_with(
"master_bedroom", decode_json=False
)
assert response["success"]
assert response["result"] == ptz_info_success


async def test_get_ptz_info_instance_not_found(
hass: HomeAssistant, hass_ws_client: Any
) -> None:
"""Test retrieving PTZ info from a non-existent instance."""

await setup_mock_frigate_config_entry(hass)

ws_client = await hass_ws_client()
ptz_info_json = {
"id": 1,
"type": "frigate/ptz/info",
"instance_id": "THIS-IS-NOT-A-REAL-INSTANCE-ID",
"camera": "master_bedroom",
}

await ws_client.send_json(ptz_info_json)
response = await ws_client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "not_found"


async def test_get_ptz_info_api_error(hass: HomeAssistant, hass_ws_client: Any) -> None:
"""Test retrieving PTZ info when the API has an error."""

mock_client = create_mock_frigate_client()
await setup_mock_frigate_config_entry(hass, client=mock_client)

ws_client = await hass_ws_client()
ptz_info_json = {
"id": 1,
"type": "frigate/ptz/info",
"instance_id": TEST_FRIGATE_INSTANCE_ID,
"camera": "master_bedroom",
}

mock_client.async_get_ptz_info = AsyncMock(side_effect=FrigateApiClientError)

await ws_client.send_json(ptz_info_json)
response = await ws_client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "frigate_error"
Loading