Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Private BLE Device sensors."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 
8 from bluetooth_data_tools import calculate_distance_meters
9 
10 from homeassistant.components import bluetooth
12  SensorDeviceClass,
13  SensorEntity,
14  SensorEntityDescription,
15  SensorStateClass,
16 )
17 from homeassistant.config_entries import ConfigEntry
18 from homeassistant.const import (
19  SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
20  EntityCategory,
21  UnitOfLength,
22  UnitOfTime,
23 )
24 from homeassistant.core import HomeAssistant, callback
25 from homeassistant.helpers.entity_platform import AddEntitiesCallback
26 
27 from .entity import BasePrivateDeviceEntity
28 
29 
30 @dataclass(frozen=True, kw_only=True)
32  """Describes sensor entity."""
33 
34  value_fn: Callable[
35  [HomeAssistant, bluetooth.BluetoothServiceInfoBleak], str | int | float | None
36  ]
37 
38 
39 SENSOR_DESCRIPTIONS = (
41  key="rssi",
42  device_class=SensorDeviceClass.SIGNAL_STRENGTH,
43  native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
44  entity_registry_enabled_default=False,
45  entity_category=EntityCategory.DIAGNOSTIC,
46  value_fn=lambda _, service_info: service_info.advertisement.rssi,
47  state_class=SensorStateClass.MEASUREMENT,
48  ),
50  key="power",
51  translation_key="power",
52  device_class=SensorDeviceClass.SIGNAL_STRENGTH,
53  native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
54  entity_registry_enabled_default=False,
55  entity_category=EntityCategory.DIAGNOSTIC,
56  value_fn=lambda _, service_info: service_info.advertisement.tx_power,
57  state_class=SensorStateClass.MEASUREMENT,
58  ),
60  key="estimated_distance",
61  translation_key="estimated_distance",
62  native_unit_of_measurement=UnitOfLength.METERS,
63  value_fn=lambda _, service_info: service_info.advertisement
64  and service_info.advertisement.tx_power
65  and calculate_distance_meters(
66  service_info.advertisement.tx_power * 10, service_info.advertisement.rssi
67  ),
68  state_class=SensorStateClass.MEASUREMENT,
69  device_class=SensorDeviceClass.DISTANCE,
70  suggested_display_precision=1,
71  ),
73  key="estimated_broadcast_interval",
74  translation_key="estimated_broadcast_interval",
75  native_unit_of_measurement=UnitOfTime.SECONDS,
76  entity_registry_enabled_default=False,
77  entity_category=EntityCategory.DIAGNOSTIC,
78  value_fn=(
79  lambda hass, service_info: (
80  bluetooth.async_get_learned_advertising_interval(
81  hass, service_info.address
82  )
83  or bluetooth.async_get_fallback_availability_interval(
84  hass, service_info.address
85  )
86  or bluetooth.FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
87  )
88  ),
89  suggested_display_precision=1,
90  ),
91 )
92 
93 
95  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
96 ) -> None:
97  """Set up sensors for Private BLE component."""
99  PrivateBLEDeviceSensor(entry, description)
100  for description in SENSOR_DESCRIPTIONS
101  )
102 
103 
105  """A sensor entity."""
106 
107  entity_description: PrivateDeviceSensorEntityDescription
108 
109  def __init__(
110  self,
111  config_entry: ConfigEntry,
112  entity_description: PrivateDeviceSensorEntityDescription,
113  ) -> None:
114  """Initialize an sensor entity."""
115  self.entity_descriptionentity_description = entity_description
116  self._attr_available_attr_available = False
117  super().__init__(config_entry)
118 
119  @callback
121  self,
122  service_info: bluetooth.BluetoothServiceInfoBleak,
123  change: bluetooth.BluetoothChange,
124  ) -> None:
125  """Update state."""
126  self._attr_available_attr_available = True
127  self._last_info_last_info = service_info
128  self.async_write_ha_stateasync_write_ha_state()
129 
130  @callback
132  self, service_info: bluetooth.BluetoothServiceInfoBleak
133  ) -> None:
134  """Update state."""
135  self._attr_available_attr_available = False
136  self.async_write_ha_stateasync_write_ha_state()
137 
138  @property
139  def native_value(self) -> str | int | float | None:
140  """Return the state of the sensor."""
141  assert self._last_info_last_info
142  return self.entity_descriptionentity_description.value_fn(self.hasshass, self._last_info_last_info)
None _async_track_service_info(self, bluetooth.BluetoothServiceInfoBleak service_info, bluetooth.BluetoothChange change)
Definition: sensor.py:124
None _async_track_unavailable(self, bluetooth.BluetoothServiceInfoBleak service_info)
Definition: sensor.py:133
None __init__(self, ConfigEntry config_entry, PrivateDeviceSensorEntityDescription entity_description)
Definition: sensor.py:113
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:96