Home Assistant Unofficial Reference 2024.12.1
device_tracker.py
Go to the documentation of this file.
1 """Tracking for bluetooth low energy devices."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 
8 from homeassistant.components import bluetooth
9 from homeassistant.components.device_tracker import SourceType
10 from homeassistant.components.device_tracker.config_entry import BaseTrackerEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import STATE_HOME, STATE_NOT_HOME
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from .entity import BasePrivateDeviceEntity
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
22  hass: HomeAssistant,
23  config_entry: ConfigEntry,
24  async_add_entities: AddEntitiesCallback,
25 ) -> None:
26  """Load Device Tracker entities for a config entry."""
28 
29 
31  """A trackable Private Bluetooth Device."""
32 
33  _attr_should_poll = False
34  _attr_has_entity_name = True
35  _attr_translation_key = "device_tracker"
36  _attr_name = None
37 
38  @property
39  def extra_state_attributes(self) -> Mapping[str, str]:
40  """Return extra state attributes for this device."""
41  if last_info := self._last_info_last_info:
42  return {
43  "current_address": last_info.address,
44  "source": last_info.source,
45  }
46  return {}
47 
48  @callback
50  self, service_info: bluetooth.BluetoothServiceInfoBleak
51  ) -> None:
52  self._last_info_last_info = None
53  self.async_write_ha_stateasync_write_ha_state()
54 
55  @callback
57  self,
58  service_info: bluetooth.BluetoothServiceInfoBleak,
59  change: bluetooth.BluetoothChange,
60  ) -> None:
61  self._last_info_last_info = service_info
62  self.async_write_ha_stateasync_write_ha_state()
63 
64  @property
65  def state(self) -> str:
66  """Return the state of the device."""
67  return STATE_HOME if self._last_info_last_info else STATE_NOT_HOME
68 
69  @property
70  def source_type(self) -> SourceType:
71  """Return the source type, eg gps or router, of the device."""
72  return SourceType.BLUETOOTH_LE
None _async_track_unavailable(self, bluetooth.BluetoothServiceInfoBleak service_info)
None _async_track_service_info(self, bluetooth.BluetoothServiceInfoBleak service_info, bluetooth.BluetoothChange change)
Definition: config_entry.py:1
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)