Add device tracker to Tesla Fleet (#122222)

This commit is contained in:
Brett Adams 2024-07-20 22:37:57 +10:00 committed by GitHub
parent 6be4ef8a1f
commit 0f079454bb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 261 additions and 1 deletions

View File

@ -34,7 +34,7 @@ from .coordinator import (
)
from .models import TeslaFleetData, TeslaFleetEnergyData, TeslaFleetVehicleData
PLATFORMS: Final = [Platform.BINARY_SENSOR, Platform.SENSOR]
PLATFORMS: Final = [Platform.BINARY_SENSOR, Platform.DEVICE_TRACKER, Platform.SENSOR]
type TeslaFleetConfigEntry = ConfigEntry[TeslaFleetData]

View File

@ -0,0 +1,106 @@
"""Device Tracker platform for Tesla Fleet integration."""
from __future__ import annotations
from homeassistant.components.device_tracker import SourceType
from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from .entity import TeslaFleetVehicleEntity
from .models import TeslaFleetVehicleData
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the Tesla Fleet device tracker platform from a config entry."""
async_add_entities(
klass(vehicle)
for klass in (
TeslaFleetDeviceTrackerLocationEntity,
TeslaFleetDeviceTrackerRouteEntity,
)
for vehicle in entry.runtime_data.vehicles
)
class TeslaFleetDeviceTrackerEntity(
TeslaFleetVehicleEntity, TrackerEntity, RestoreEntity
):
"""Base class for Tesla Fleet device tracker entities."""
_attr_latitude: float | None = None
_attr_longitude: float | None = None
def __init__(
self,
vehicle: TeslaFleetVehicleData,
) -> None:
"""Initialize the device tracker."""
super().__init__(vehicle, self.key)
async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
await super().async_added_to_hass()
if (
(state := await self.async_get_last_state()) is not None
and self._attr_latitude is None
and self._attr_longitude is None
):
self._attr_latitude = state.attributes.get("latitude")
self._attr_longitude = state.attributes.get("longitude")
@property
def latitude(self) -> float | None:
"""Return latitude value of the device."""
return self._attr_latitude
@property
def longitude(self) -> float | None:
"""Return longitude value of the device."""
return self._attr_longitude
@property
def source_type(self) -> SourceType | str:
"""Return the source type of the device tracker."""
return SourceType.GPS
class TeslaFleetDeviceTrackerLocationEntity(TeslaFleetDeviceTrackerEntity):
"""Vehicle Location device tracker Class."""
key = "location"
def _async_update_attrs(self) -> None:
"""Update the attributes of the entity."""
self._attr_latitude = self.get("drive_state_latitude")
self._attr_longitude = self.get("drive_state_longitude")
self._attr_available = not (
self.get("drive_state_longitude", False) is None
or self.get("drive_state_latitude", False) is None
)
class TeslaFleetDeviceTrackerRouteEntity(TeslaFleetDeviceTrackerEntity):
"""Vehicle Navigation device tracker Class."""
key = "route"
def _async_update_attrs(self) -> None:
"""Update the attributes of the device tracker."""
self._attr_latitude = self.get("drive_state_active_route_latitude")
self._attr_longitude = self.get("drive_state_active_route_longitude")
self._attr_available = not (
self.get("drive_state_active_route_longitude", False) is None
or self.get("drive_state_active_route_latitude", False) is None
)
@property
def location_name(self) -> str | None:
"""Return a location name for the current location of the device."""
return self.get("drive_state_active_route_destination")

View File

@ -38,6 +38,14 @@
}
}
},
"device_tracker": {
"location": {
"default": "mdi:map-marker"
},
"route": {
"default": "mdi:routes"
}
},
"sensor": {
"battery_power": {
"default": "mdi:home-battery"

View File

@ -107,6 +107,14 @@
"name": "Tire pressure warning rear right"
}
},
"device_tracker": {
"location": {
"name": "Location"
},
"route": {
"name": "Route"
}
},
"sensor": {
"battery_power": {
"name": "Battery power"

View File

@ -0,0 +1,101 @@
# serializer version: 1
# name: test_device_tracker[device_tracker.test_location-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.test_location',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Location',
'platform': 'tesla_fleet',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'location',
'unique_id': 'LRWXF7EK4KC700000-location',
'unit_of_measurement': None,
})
# ---
# name: test_device_tracker[device_tracker.test_location-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Test Location',
'gps_accuracy': 0,
'latitude': -30.222626,
'longitude': -97.6236871,
'source_type': <SourceType.GPS: 'gps'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.test_location',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'not_home',
})
# ---
# name: test_device_tracker[device_tracker.test_route-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.test_route',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Route',
'platform': 'tesla_fleet',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'route',
'unique_id': 'LRWXF7EK4KC700000-route',
'unit_of_measurement': None,
})
# ---
# name: test_device_tracker[device_tracker.test_route-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Test Route',
'gps_accuracy': 0,
'latitude': 30.2226265,
'longitude': -97.6236871,
'source_type': <SourceType.GPS: 'gps'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.test_route',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'not_home',
})
# ---

View File

@ -0,0 +1,37 @@
"""Test the Tesla Fleet device tracker platform."""
from syrupy import SnapshotAssertion
from tesla_fleet_api.exceptions import VehicleOffline
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import assert_entities, setup_platform
from tests.common import MockConfigEntry
async def test_device_tracker(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
normal_config_entry: MockConfigEntry,
) -> None:
"""Tests that the device tracker entities are correct."""
await setup_platform(hass, normal_config_entry, [Platform.DEVICE_TRACKER])
assert_entities(hass, normal_config_entry.entry_id, entity_registry, snapshot)
async def test_device_tracker_offline(
hass: HomeAssistant,
mock_vehicle_data,
normal_config_entry: MockConfigEntry,
) -> None:
"""Tests that the device tracker entities are correct when offline."""
mock_vehicle_data.side_effect = VehicleOffline
await setup_platform(hass, normal_config_entry, [Platform.DEVICE_TRACKER])
state = hass.states.get("device_tracker.test_location")
assert state.state == STATE_UNKNOWN