Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Traccar server sensors."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any, Literal
8 
9 from pytraccar import DeviceModel, GeofenceModel, PositionModel
10 
12  SensorDeviceClass,
13  SensorEntity,
14  SensorEntityDescription,
15  SensorStateClass,
16 )
17 from homeassistant.config_entries import ConfigEntry
18 from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfLength, UnitOfSpeed
19 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.typing import StateType
22 
23 from .const import DOMAIN
24 from .coordinator import TraccarServerCoordinator
25 from .entity import TraccarServerEntity
26 
27 
28 @dataclass(frozen=True, kw_only=True)
29 class TraccarServerSensorEntityDescription[_T](SensorEntityDescription):
30  """Describe Traccar Server sensor entity."""
31 
32  data_key: Literal["position", "device", "geofence", "attributes"]
33  entity_registry_enabled_default = False
34  entity_category = EntityCategory.DIAGNOSTIC
35  value_fn: Callable[[_T], StateType]
36 
37 
38 TRACCAR_SERVER_SENSOR_ENTITY_DESCRIPTIONS: tuple[
39  TraccarServerSensorEntityDescription[Any], ...
40 ] = (
41  TraccarServerSensorEntityDescription[PositionModel](
42  key="attributes.batteryLevel",
43  data_key="position",
44  native_unit_of_measurement=PERCENTAGE,
45  device_class=SensorDeviceClass.BATTERY,
46  state_class=SensorStateClass.MEASUREMENT,
47  suggested_display_precision=0,
48  value_fn=lambda x: x["attributes"].get("batteryLevel"),
49  ),
50  TraccarServerSensorEntityDescription[PositionModel](
51  key="speed",
52  data_key="position",
53  device_class=SensorDeviceClass.SPEED,
54  state_class=SensorStateClass.MEASUREMENT,
55  native_unit_of_measurement=UnitOfSpeed.KNOTS,
56  suggested_display_precision=0,
57  value_fn=lambda x: x["speed"],
58  ),
59  TraccarServerSensorEntityDescription[PositionModel](
60  key="altitude",
61  data_key="position",
62  translation_key="altitude",
63  state_class=SensorStateClass.MEASUREMENT,
64  native_unit_of_measurement=UnitOfLength.METERS,
65  suggested_display_precision=1,
66  value_fn=lambda x: x["altitude"],
67  ),
68  TraccarServerSensorEntityDescription[PositionModel](
69  key="address",
70  data_key="position",
71  translation_key="address",
72  value_fn=lambda x: x["address"],
73  ),
74  TraccarServerSensorEntityDescription[GeofenceModel | None](
75  key="name",
76  data_key="geofence",
77  translation_key="geofence",
78  value_fn=lambda x: x["name"] if x else None,
79  ),
80 )
81 
82 
84  hass: HomeAssistant,
85  entry: ConfigEntry,
86  async_add_entities: AddEntitiesCallback,
87 ) -> None:
88  """Set up sensor entities."""
89  coordinator: TraccarServerCoordinator = hass.data[DOMAIN][entry.entry_id]
92  coordinator=coordinator,
93  device=entry["device"],
94  description=description,
95  )
96  for entry in coordinator.data.values()
97  for description in TRACCAR_SERVER_SENSOR_ENTITY_DESCRIPTIONS
98  )
99 
100 
101 class TraccarServerSensor[_T](TraccarServerEntity, SensorEntity):
102  """Represent a tracked device."""
103 
104  _attr_has_entity_name = True
105  entity_description: TraccarServerSensorEntityDescription[_T]
106 
107  def __init__(
108  self,
109  coordinator: TraccarServerCoordinator,
110  device: DeviceModel,
111  description: TraccarServerSensorEntityDescription[_T],
112  ) -> None:
113  """Initialize the Traccar Server sensor."""
114  super().__init__(coordinator, device)
115  self.entity_descriptionentity_description = description
116  self._attr_unique_id_attr_unique_id_attr_unique_id = (
117  f"{device['uniqueId']}_{description.data_key}_{description.key}"
118  )
119 
120  @property
121  def native_value(self) -> StateType:
122  """Return the value of the sensor."""
123  return self.entity_descriptionentity_description.value_fn(
124  getattr(self, f"traccar_{self.entity_description.data_key}")
125  )
None __init__(self, TraccarServerCoordinator coordinator, DeviceModel device, TraccarServerSensorEntityDescription[_T] description)
Definition: sensor.py:112
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:87