Home Assistant Unofficial Reference 2024.12.1
device_tracker.py
Go to the documentation of this file.
1 """Support for the Locative platform."""
2 
3 from homeassistant.components.device_tracker import TrackerEntity
4 from homeassistant.config_entries import ConfigEntry
5 from homeassistant.core import HomeAssistant, callback
6 from homeassistant.helpers.dispatcher import async_dispatcher_connect
7 from homeassistant.helpers.entity_platform import AddEntitiesCallback
8 
9 from . import DOMAIN as LT_DOMAIN, TRACKER_UPDATE
10 
11 
13  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
14 ) -> None:
15  """Configure a dispatcher connection based on a config entry."""
16 
17  @callback
18  def _receive_data(device, location, location_name):
19  """Receive set location."""
20  if device in hass.data[LT_DOMAIN]["devices"]:
21  return
22 
23  hass.data[LT_DOMAIN]["devices"].add(device)
24 
25  async_add_entities([LocativeEntity(device, location, location_name)])
26 
27  hass.data[LT_DOMAIN]["unsub_device_tracker"][entry.entry_id] = (
28  async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
29  )
30 
31 
32 class LocativeEntity(TrackerEntity):
33  """Represent a tracked device."""
34 
35  def __init__(self, device, location, location_name):
36  """Set up Locative entity."""
37  self._name_name = device
38  self._attr_latitude_attr_latitude = location[0]
39  self._attr_longitude_attr_longitude = location[1]
40  self._attr_location_name_attr_location_name = location_name
41  self._unsub_dispatcher_unsub_dispatcher = None
42 
43  @property
44  def name(self):
45  """Return the name of the device."""
46  return self._name_name
47 
48  async def async_added_to_hass(self) -> None:
49  """Register state update callback."""
50  self._unsub_dispatcher_unsub_dispatcher = async_dispatcher_connect(
51  self.hass, TRACKER_UPDATE, self._async_receive_data_async_receive_data
52  )
53 
54  async def async_will_remove_from_hass(self) -> None:
55  """Clean up after entity before removal."""
56  self._unsub_dispatcher_unsub_dispatcher()
57 
58  @callback
59  def _async_receive_data(self, device, location, location_name):
60  """Update device data."""
61  if device != self._name_name:
62  return
63  self._attr_location_name_attr_location_name = location_name
64  self._attr_latitude_attr_latitude = location[0]
65  self._attr_longitude_attr_longitude = location[1]
66  self.async_write_ha_state()
def _async_receive_data(self, device, location, location_name)
def __init__(self, device, location, location_name)
bool add(self, _T matcher)
Definition: match.py:185
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103