Make recorder WS command recorder/update_statistics_metadata wait (#127179)

This commit is contained in:
Erik Montnemery 2024-10-02 09:56:36 +02:00 committed by GitHub
parent 7790bb528c
commit 2a2af01d12
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 52 additions and 4 deletions

View file

@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
from datetime import datetime as dt
from typing import Any, Literal, cast
@ -48,6 +49,8 @@ from .statistics import (
)
from .util import PERIOD_SCHEMA, get_instance, resolve_period
UPDATE_STATISTICS_METADATA_TIME_OUT = 10
UNIT_SCHEMA = vol.Schema(
{
vol.Optional("conductivity"): vol.In(ConductivityConverter.VALID_UNITS),
@ -357,17 +360,33 @@ async def ws_get_statistics_metadata(
vol.Required("unit_of_measurement"): vol.Any(str, None),
}
)
@callback
def ws_update_statistics_metadata(
@websocket_api.async_response
async def ws_update_statistics_metadata(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Update statistics metadata for a statistic_id.
Only the normalized unit of measurement can be updated.
"""
done_event = asyncio.Event()
def update_statistics_metadata_done() -> None:
hass.loop.call_soon_threadsafe(done_event.set)
get_instance(hass).async_update_statistics_metadata(
msg["statistic_id"], new_unit_of_measurement=msg["unit_of_measurement"]
msg["statistic_id"],
new_unit_of_measurement=msg["unit_of_measurement"],
on_done=update_statistics_metadata_done,
)
try:
async with asyncio.timeout(UPDATE_STATISTICS_METADATA_TIME_OUT):
await done_event.wait()
except TimeoutError:
connection.send_error(
msg["id"], websocket_api.ERR_TIMEOUT, "update_statistics_metadata timed out"
)
return
connection.send_result(msg["id"])