Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Entity to track connections to websocket API."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.components.sensor import SensorEntity
6 from homeassistant.core import HomeAssistant, callback
7 from homeassistant.helpers.dispatcher import async_dispatcher_connect
8 from homeassistant.helpers.entity_platform import AddEntitiesCallback
9 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
10 
11 from .const import (
12  DATA_CONNECTIONS,
13  SIGNAL_WEBSOCKET_CONNECTED,
14  SIGNAL_WEBSOCKET_DISCONNECTED,
15 )
16 
17 
19  hass: HomeAssistant,
20  config: ConfigType,
21  async_add_entities: AddEntitiesCallback,
22  discovery_info: DiscoveryInfoType | None = None,
23 ) -> None:
24  """Set up the API streams platform."""
25  entity = APICount()
26 
27  async_add_entities([entity])
28 
29 
31  """Entity to represent how many people are connected to the stream API."""
32 
33  _attr_name = "Connected clients"
34  _attr_native_unit_of_measurement = "clients"
35 
36  def __init__(self) -> None:
37  """Initialize the API count."""
38  self._attr_native_value_attr_native_value = 0
39 
40  async def async_added_to_hass(self) -> None:
41  """Handle addition to hass."""
42  self.async_on_removeasync_on_remove(
44  self.hasshass, SIGNAL_WEBSOCKET_CONNECTED, self._update_count_update_count
45  )
46  )
47  self.async_on_removeasync_on_remove(
49  self.hasshass, SIGNAL_WEBSOCKET_DISCONNECTED, self._update_count_update_count
50  )
51  )
52 
53  @callback
54  def _update_count(self) -> None:
55  self._attr_native_value_attr_native_value = self.hasshass.data.get(DATA_CONNECTIONS, 0)
56  self.async_write_ha_stateasync_write_ha_state()
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:23
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103