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 (
13  DEVICE_CLASS_UNITS,
14  NON_NUMERIC_DEVICE_CLASSES,
15  UNIT_CONVERTERS,
16  SensorDeviceClass,
17 )
18 
19 _NUMERIC_DEVICE_CLASSES = list(set(SensorDeviceClass) - NON_NUMERIC_DEVICE_CLASSES)
20 
21 
22 @callback
23 def async_setup(hass: HomeAssistant) -> None:
24  """Set up the sensor websocket API."""
25  websocket_api.async_register_command(hass, ws_device_class_units)
26  websocket_api.async_register_command(hass, ws_numeric_device_classes)
27 
28 
29 @callback
30 @websocket_api.websocket_command( { vol.Required("type"): "sensor/device_class_convertible_units",
31  vol.Required("device_class"): str,
32  }
33 )
35  hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
36 ) -> None:
37  """Return supported units for a device class."""
38  device_class = msg["device_class"]
39  convertible_units = []
40  if device_class in UNIT_CONVERTERS and device_class in DEVICE_CLASS_UNITS:
41  convertible_units = sorted(
42  DEVICE_CLASS_UNITS[device_class],
43  key=lambda s: str.casefold(str(s)),
44  )
45  connection.send_result(msg["id"], {"units": convertible_units})
46 
47 
48 @callback
49 @websocket_api.websocket_command( { vol.Required("type"): "sensor/numeric_device_classes",
50  }
51 )
53  hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
54 ) -> None:
55  """Return numeric sensor device classes."""
56  connection.send_result(
57  msg["id"], {"numeric_device_classes": _NUMERIC_DEVICE_CLASSES}
58  )
59 
None ws_numeric_device_classes(HomeAssistant hass, websocket_api.ActiveConnection connection, dict[str, Any] msg)
None ws_device_class_units(HomeAssistant hass, websocket_api.ActiveConnection connection, dict[str, Any] msg)