Home Assistant Unofficial Reference 2024.12.1
websocket_api.py
Go to the documentation of this file.
1 """The sensor websocket API."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 import voluptuous as vol
8 
9 from homeassistant.components import websocket_api
10 from homeassistant.core import HomeAssistant, callback
11 
12 from .const import DEVICE_CLASS_UNITS, UNIT_CONVERTERS
13 
14 
15 @callback
16 def async_setup(hass: HomeAssistant) -> None:
17  """Set up the number websocket API."""
18  websocket_api.async_register_command(hass, ws_device_class_units)
19 
20 
21 @callback
22 @websocket_api.websocket_command( { vol.Required("type"): "number/device_class_convertible_units",
23  vol.Required("device_class"): str,
24  }
25 )
27  hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
28 ) -> None:
29  """Return supported units for a device class."""
30  device_class = msg["device_class"]
31  convertible_units = []
32  if device_class in UNIT_CONVERTERS and device_class in DEVICE_CLASS_UNITS:
33  convertible_units = sorted(
34  DEVICE_CLASS_UNITS[device_class],
35  key=lambda s: str.casefold(str(s)),
36  )
37  connection.send_result(msg["id"], {"units": convertible_units})