1 """The weather websocket API."""
3 from __future__
import annotations
5 from typing
import Any, Literal
7 import voluptuous
as vol
14 from .const
import DATA_COMPONENT, DOMAIN, VALID_UNITS, WeatherEntityFeature
16 FORECAST_TYPE_TO_FLAG = {
17 "daily": WeatherEntityFeature.FORECAST_DAILY,
18 "hourly": WeatherEntityFeature.FORECAST_HOURLY,
19 "twice_daily": WeatherEntityFeature.FORECAST_TWICE_DAILY,
25 """Set up the weather websocket API."""
26 websocket_api.async_register_command(hass, ws_convertible_units)
27 websocket_api.async_register_command(hass, ws_subscribe_forecast)
31 @websocket_api.websocket_command(
{
vol.Required("type"):
"weather/convertible_units",
37 """Return supported units for a device class."""
39 key: sorted(units, key=str.casefold)
for key, units
in VALID_UNITS.items()
41 connection.send_result(msg[
"id"], {
"units": sorted_units})
44 @websocket_api.websocket_command(
{
vol.Required("type"):
"weather/subscribe_forecast",
45 vol.Required(
"entity_id"): cv.entity_domain(DOMAIN),
46 vol.Required(
"forecast_type"): vol.In([
"daily",
"hourly",
"twice_daily"]),
49 @websocket_api.async_response
53 """Subscribe to weather forecasts."""
54 entity_id: str = msg[
"entity_id"]
55 forecast_type: Literal[
"daily",
"hourly",
"twice_daily"] = msg[
"forecast_type"]
57 if not (entity := hass.data[DATA_COMPONENT].
get_entity(msg[
"entity_id"])):
58 connection.send_error(
61 f
"Weather entity not found: {entity_id}",
66 entity.supported_features
is None
67 or not entity.supported_features & FORECAST_TYPE_TO_FLAG[forecast_type]
69 connection.send_error(
71 "forecast_not_supported",
72 f
"The weather entity does not support forecast type: {forecast_type}",
77 def forecast_listener(forecast: list[JsonValueType] |
None) ->
None:
78 """Push a new forecast to websocket."""
79 connection.send_message(
80 websocket_api.event_message(
83 "type": forecast_type,
89 connection.subscriptions[msg[
"id"]] = entity.async_subscribe_forecast(
90 forecast_type, forecast_listener
92 connection.send_message(websocket_api.result_message(msg[
"id"]))
95 await entity.async_update_listeners({forecast_type})
96
CalendarEntity get_entity(HomeAssistant hass, str entity_id)
None ws_convertible_units(HomeAssistant hass, websocket_api.ActiveConnection connection, dict[str, Any] msg)
None async_setup(HomeAssistant hass)
None ws_subscribe_forecast(HomeAssistant hass, websocket_api.ActiveConnection connection, dict[str, Any] msg)